10 Not So Well Known Keywords in C#
- 12
- Add a Comment
Welcome Back! I hope you enjoy the content on this site. If you have not done so already, you may want to subscribe to my RSS feed or become a fan of this blog on Facebook. Thanks for visiting!
Ok before the flaming start let me state this. These are known to most hardcore programmers and not knowing them doesn’t make you less of a programmer either.
That said these keywords can come in handy and allow for better code quality and readability. Enjoy!
yield
The yield keyword signals to the compiler that the method in which it appears is an iterator block. The compiler generates a class to implement the behavior that is expressed in the iterator block. In the iterator block, the yield keyword is used together with the return keyword to provide a value to the enumerator object. This is the value that is returned, for example, in each loop of a foreach statement. The yield keyword is also used with break to signal the end of iteration.
example:
public classList
{
//using System.Collections;
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while(counter++ < exponent)
{
result = result * number;
yield returnresult;
}
}
static void Main()
{
// Display powers of 2 up to the exponent 8:
foreach (int i inPower(2, 8))
{
Console.Write("{0} ", i);
}
}
}
/*
Output:
2 4 8 16 32 64 128 256
*/
msdn reference: http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx
var
Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.
An application running on version 2.0 can also use the var keyword in their code as long as it’s compiled with 3.0 or up and set to output to 2.0.
example:
var i = 10; // implicitly typed
int i = 10; //explicitly typed
msdn reference: http://msdn.microsoft.com/en-us/library/bb383973.aspx
using()
Defines a scope, outside of which an object or objects will be disposed.
example:
using (C c = new C())
{
c.UseLimitedResource();
}
msdn reference: http://msdn.microsoft.com/en-us/library/yh598w02%28VS.80%29.aspx
readonly
The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
msdn reference: http://msdn.microsoft.com/en-us/library/acdd6hb7%28VS.80%29.aspx
as
The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception.
example:
class Base
{ public override string ToString()
{
return "Base";
}
}
class Derived : Base
{ }
class Program
{
static void Main()
{
Derived d = new Derived();
Base b = d as Base;
if (b != null)
{
Console.WriteLine(b.ToString());
}
}
}
msdn reference: http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx
is
Checks if an object is compatible with a given type.
An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.
The is keyword causes a compile-time warning if the expression is known to always be true or to always be false, but typically evaluates type compatibility at run time.
The is operator cannot be overloaded.
example:
class Class1{ }
classClass2{ }
classClass3: Class2{ }
classIsTest
{
static voidTest(objecto)
{
Class1a;
Class2b;
if(o isClass1)
{
Console.WriteLine("o is Class1");
a = (Class1)o;
// Do something with "a."
}
else if (o is Class2)
{
Console.WriteLine("o is Class2");
b = (Class2)o;
// Do something with "b."
}
else
{
Console.WriteLine("o is neither Class1 nor Class2.");
}
}
static void Main()
{
Class1 c1 = new Class1();
Class2 c2 = new Class2();
Class3 c3 = new Class3();
Test(c1);
Test(c2);
Test(c3);
Test("a string");
}
}
/*
Output:
o is Class1
o is Class2
o is Class2
o is neither Class1 nor Class2.
msdn reference: http://msdn.microsoft.com/en-us/library/scekt9xw.aspx
default
-
Whether T will be a reference type or a value type.
-
If T is a value type, whether it will be a numeric value or a struct.
n generic classes and methods, one issue that arises is how to assign a default value to a parameterized type T when you do not know the following in advance:
Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default returns a System.Nullabe<T>, which is initialized like any struct.
example:
T temp = default(T);
msdn reference: http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx
global
The global contextual keyword, when it comes before the :: operator, refers to the global namespace, which is the default namespace for any C# program and is otherwise unnamed.
example:
class TestClass : global::TestApp { }
msdn reference: http://msdn.microsoft.com/en-us/library/cc713620.aspx
volatile
The volatile keyword indicates that a field might be modified by multiple concurrently executing threads. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.
msdn reference: http://msdn.microsoft.com/en-us/library/x13ttww7%28VS.80%29.aspx
extern alias
It can sometimes be necessary to reference two versions of assemblies that have the same fully-qualified type names, for example when you need to use two or more versions of an assembly in the same application. By using an external assembly alias, the namespaces from each assembly can be wrapped inside root-level namespaces named by the alias, allowing them to be used in the same file.
To reference two assemblies with the same fully-qualified type names, an alias must be specified on the command line, as follows:
/r:GridV1=grid.dll
/r:GridV2=grid20.dll
This creates the external aliases GridV1 and GridV2. To use these aliases from within a program, reference them using the extern keyword. For example:
extern alias GridV1;
extern alias GridV2;
Each extern alias declaration introduces an additional root-level namespace that parallels (but does not lie within) the global namespace. Thus types from each assembly can be referred to without ambiguity using their fully qualified name, rooted in the appropriate namespace-alias
In the above example, GridV1::Grid would be the grid control from grid.dll, and GridV2::Grid would be the grid control from grid20.dll.
msdn reference: http://msdn.microsoft.com/en-us/library/ms173212%28VS.80%29.aspx
Hope this helps!
Hatim
12 Comments
Petar Petrov
December 8th, 2009
at 2:18pm
This is ridiculous. EVERY C# developer is familiar with this keyword. If it’s not I don’t wan to work with him/her.
Syed Tayyab Ali
December 8th, 2009
at 2:57pm
“var” and “using” both are well known keywords in C#.
brian canzanella
December 8th, 2009
at 4:30pm
I didn’t know about extern alias… thanks!
skilledDeveloper
December 9th, 2009
at 11:59am
useful post.
thank you.
csharphacker
December 9th, 2009
at 9:23pm
The “as” keyword only casts reference types, not value types, where using the “(Type) objectVar” cast will work for both reference and value types
William Yip
December 10th, 2009
at 7:31am
-__- I didn’t know half of them~~thx.
Dennis
December 11th, 2009
at 8:23pm
Petar, it is elitist pricks like you that give developers a bad image. If anything is ridiculous, it is your small brained comment.
DD
December 12th, 2009
at 5:54pm
Anybody who has atleast read some C# text box will know this keywords.
SS
December 22nd, 2009
at 12:00pm
This is BS. If a programmer working in C# at least for 6 months then he will know all of these keywords. Thanks anyways for giving heads up to people who are trying to learn C#.
Hatim
December 22nd, 2009
at 12:02pm
Thanks SS. This is indeed not intended for the super hackers but for all the rest of us who can still learn something each day even with few years of solid experience.
iChaib
December 27th, 2009
at 11:50pm
Thx for this useful post !
I’m programming with C# & I’m not an expert, I see here keywords that I know (that I saw in text books) but that I never use, I’m glad to see how it works.
Petar, I’m happy to not work with you too
Carl J
December 30th, 2009
at 9:28pm
You’d be surprised at the percentage of developers who either don’t know, or don’t use some of these, such as the “using” (which I mostly use for all my db connections).
Thanks for the list, Some I already knew, some of those you gave me a better understanding of (yield), and some I’ve never heard of before (extern alias).