Wednesday, November 21, 2007

C# Short-Hand Tricks

Nothing earth-shattering, but this is a list of some of the lesser-known wrist-friendly shortcut features in the C# 3.0 compiler (and one that has been around for awhile).
These features are cool, because they all make the code smaller and easier to read, without adding perl-style cryptic confusion and making us a contender in any code obfuscation contest.

Coalesce
How often do we write something like this:

object outerObject = null;
...time goes by....
object innerScopedObject;
if (outerObject == null)
innerScopedObject = new object();
else
innerScopedObject = outerObject;

or

object outerObject = null;
...time goes by....
object innerScopedObject = outerObject ==null? new object();

with the coalesce operator (double question mark) '??' the following statement is equivalent:

object innerScopedObject = outerObject ?? new object():

Its nice, because the coalesce operator is specifically for handling null cases.

Automatic Properties
How often do we write something like this:

private int foo;
public int Foo
{
get { return foo; }
set { foo = value; }
}
The point is, you are encapsulating a private variable just to expose it via a property without any accessor logic. In C# 3.0, the following statement is equivalent:

public int Foo
{
get;
set;
}

The compiler will automatically generate the private variable for you. One less variable to worry about; less code is better code.

Nullable Primitives
(This trick has been around for awhile now) Ever needed to do this:

DateTime dt = null;

Just to find out it won't compile? Why is it they give us a database that allows for nullable integers and DateTimes, but a C# language that forbids it?
The 'nullable' operator (the question mark operator) '?' lets this work.

DateTime? dt = null;

That will compile. Don't get carried away with that trick; null can mean so many different things. Truth is, it is VERY rare when null values are handy in terms of database persistence.

Labels:

0 Comments:

Post a Comment

<< Home