Adam Tibi on ASP.NET, C# & SEO

Working with other colleagues, I found these C# syntaxes are still not well-known and used, so I thought of blogging on 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 '??'

While all of use, especially those coming from C/C++ background have used the ternary operator '?:', such as:

    Point point1 = null;
    // some code to initialise the point1...
    Point point2 = (point1 == null ? new Point() : point1);
However, C# 2.0 introduced this new syntax:
    Point point1 = null;
    // some code to initialise the point1...
    Point point2 = (point1 ?? new Point());

Which does exactly the same as the previous syntax.

3 - Initialising 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};

Probably if you are using LINQ then you have used this code several times.

Kick It on DotNetKicks.comdigg it
Stumble It!Delicious

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading