Tuesday, November 30, 2010

Automatically Implemented Properties for readonly case And Object Initializer -- Let's review the C# 3.0 feature

public class ReadOnlyPoint
{
public int X {get; private set;}
public int Y {get; private set;}

public ReadOnlyPoint(int x, int y){X=x; Y=y;}
}

notice the word "private".

We can also use public int X {get;}
//new notes

And the for example there is a class Point, it has the default constructor and a second constructor take the variable x.

public class Point
{
public int X{get;set;}
public int Y{get;set;}
public Point {};
public Point(int x){X=x;}
}

When we initialize this object, we can use the default constructor like:

Point p1=new Point{X=3,Y=4};

or we can use the 2nd constructor:

Point p2=new Point(1){Y=3};

We can also get the intializer nested:

public Class Circle
{
public Point Origin{get;set;}
public int Radius{get;set;}
}

var myCircle=new Circle{Origin=new Point{X=2, Y=4}, Radius=3};

For the Collections or the class which implemented IEnumerable interface.

We can write://this is nothing new

List < Point> pointlst=new List< Point>{new Point{X=2, Y=4},
new Point{X=1,Y=5},
new Point{X=3,Y=7}};

No comments: