Working with other colleagues, I found these C# syntaxes are still not well known or widely used, so I thought I would blog about them.
1 – Properties Without Members
In the old days, before C# 3.0, we used to write syntax like:
public class Point {
private int _x;
private int _y;
public int X {
get {
return _x;
}
set {
_x = value;
}
}
public int Y {
get {
return _y;
}
set {
_y = value;
}
}
}
But if you are not doing any special processing in your property, you can use a shorter syntax introduced in C# 3.0:
public class Point {
public int X {
get;
set;
}
public int Y {
get;
set;
}
}
2 – The null-coalescing operator ??
Most of us, especially those coming from a C/C++ background, have used the ternary operator ?:, such as:
Point point1 = null;
// some code to initialize point1...
Point point2 = (point1 == null ? new Point() : point1);
C# 2.0 introduced this new syntax:
Point point1 = null;
// some code to initialize point1...
Point point2 = (point1 ?? new Point());
This does exactly the same thing as the previous syntax.
3 – Initializing Properties When Creating an Object
Point point = new Point();
point.X = 1;
point.Y = 1;
Or you can use the C# 3.0 syntax:
Point point = new Point { X = 1, Y = 1};
If you use LINQ, you have probably written code like this several times.