Norman Sasono

Beauty is the first test: there is no permanent place in the world for ugly Mathematics – G.H. Hardy
See also: Other Geeks@INDC

About Me

Auto-Implemented Properties

I've blogged about Type Inferencing, Extension Methods, Lambda Expressions and maybe Anonymous Type, as all these are foundations of LINQ. This time, I'd like to highlight something in C# 3.0 called: Auto-Implemented Properties.

I bet you did a lot of something like this, by hand or by code-gen:

private string _name;
public string Name
{
    get { return _name; }
    set { _name = value; }
}

In C# 3.0, you can simply write:

public string Name { get; set; }

The compiler will create for you a private anonymous backing field that can only be accessed thru the getter and the setter above. Note also:

  • The property must have both "get" and "set". If you want the property to be read only, just put the setter as private.
  • Attributes are not allowed. If you need ones, just create a regular property.
Share this post: | | | |
Posted: Aug 13 2007, 08:04 AM by norman | with 1 comment(s)
Filed under: ,

Comments

csharpindonesia said:

I like the first note that mentioned about the private addition for the setter :)

# August 13, 2007 4:50 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 
Are you human?:  


Enter the numbers above: