Sunday, August 10, 2008

Automatic Properties

Now we can declare properties in single step instead of two steps in previous versions [declare private variable then encapsulate it with properties],

With c# 3.0 can declare properties directly as following







How it’s work

In background the compiler generates private variable for you , compiler generate it with same property name between brackets

In previous example property name is FirstName, then the compiler generates private variable with name

Compiler uses this method to naming variable to prevent conflict with user defined variable because user can’t use the bracket in variable names.





When we use automatic properties in struct, we must explicitly call default constructor from the constructor we wrote.

e.g.
public struct Person

{

public Person(string fname, string lname) :this()

{

FirstName = fname;

LastName = lname;

}

public string FirstName { set; get; }

public string LastName { set; get; }

}



No comments: