When you learn a new language you tend to settle into using it in a particular way. So if you missed a little known feature it is unlikely you will suddenly find it unless someone points it out. Here are 5 of my favorite C# features that you might not already be using.
1 – ?? Operator
The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand. So instead of using code like this…
if (reference == null)
return _defaultInstance;
else
return reference;
You can just write the following statement instead…
return reference ?? _defaultInstance;
Much cleaner and it even works for nullable value types.
2 - DebuggerStepThrough
This attribute can be added to a method or property accessor and used to speed up debugging. When debugging and using step-into the debugger will step past the method with this attribute. This is really useful in preventing you stepping in and out of the many one liners in the code. To apply do this…
public string Name { [DebuggerStepThrough] get { return _name; } [DebuggerStepThrough] set { _name = value; } }
3 – Automatic Properties
Sick and tired of adding get/set code for simple properties? This is no longer a problem with the automatic properties added in C# 3.0. Instead of this…
private string _name; public string Name { get { return _name; } set { _name = value; } }
…just do this…
public string Name { get; set; }
4 - Object Initializers
Also introduced in C# 3.0 are object initializers. This allows you to set property values inside the new statement. Without this you either create additional overloaded constructor with the possible set of initial values or you write the long hand like this…
Employee emp = new Employee();
emp.Name = "John Smith";
emp.Age = 10;
…but this is clearer…
Employee emp = new Employee {Name="John Smith", Age=10}
5 - Constant flags
Want to specify a float instead of a double for a constant? Most people know the ‘f’ modifier after a constant number informs the compiler to make it a single float value. But did you know the full list of others flags?
100m (decimal)
100f (float)
100d (double)
100u (uint)
100l (long)
100ul (ulong)
Let me know if I have missed one you really like.
