Some useful C# 2.0 features

Our team has recently moved over to the .NET Framework 2.0 and I've decided to catch up on this new skill by reading the C# 2.0 specification. There are a couple of well-known features such as iterators, anonymous methods (yuck) and generics, but I noticed two small features that might have a tremendous effect on our team's productivity.

The first is the new double-question-mark operator. Consider the following code snippet:

object foo = bar ?? String.Empty;

This piece of code will assign foo to bar only if bar is not null. If bar is null, then foo will be assigned to String.Empty. As a matter of interest, this operator was introduced as part of the nullable types feature, but it will work with any reference type.

The second feature is called Property Accessor Accessibility. I really missed this feature while developing in .NET 1.1, but now it is part of C# 2.0, and allows you to modify the accessibility of a property's get or set accessor.

Let's say that you have a property that you want to be read publicly, but you only want to modify it internally, then you will write a code snippet similar to the following:

public object Foo
{
     get return foo; }
    internal set { foo = value; }
}

powered by IMHO 1.3

Published Sunday, March 19, 2006 10:59 AM by trumpi
Filed under:

Comments

# re: Some useful C# 2.0 features

Yep, the coalescing operator was introduced with nullable types. It really rocks!

Sunday, March 19, 2006 10:47 PM by Pieter

# re: Some useful C# 2.0 features

Correct me if I'm wrong, but this object foo = bar ?? String.EMPTY is the same as going ...

foo = bar == null ? String.Empty : bar

Do you not have this ? : operator in C#?

Wednesday, March 29, 2006 6:04 PM by Michael Wiles

# re: Some useful C# 2.0 features

Yes, it's the same, and we have it in C# of course, but the new ?? as you can see lets you write even less code.

Time to migrate to .NET? :D

Sunday, April 02, 2006 7:22 PM by Simone Busoli

# re: Some useful C# 2.0 features

Hey Mike

Yep - the ? ternary operator is in C#, and you are quite correct - the two expressions that you have shown are equivalent in their functionality.

Happy Javaing dude!

Thursday, April 13, 2006 11:45 PM by trumpi