Monday, July 28, 2008

C# Auto Properties

I learned a short-cut today for properties.  They're called auto properties.  Properties in C# are simple getters and setters in Java.  auto properties make writing properties even easier.

Several times a day I have typed something similar to:

 public string Country

{

  get { return country; }

  set { country = value; }

}

I've been using Resharper for several months now, but just noticed today that it recommended that I write a property this way:

 public string Country { get; set; }

3 Comments:

At 6:04 PM, Blogger Jacob said...

Would it be more accurate to say simple getters and setters in Java are like the most basic properties in C#? In C# you can do stuff to other than get and set a field right?

That short cut is pretty nice. Almost as nice as the accessor macro in ruby. I am surprised someone with your experience did not know it already.

 
At 8:13 AM, Blogger Ryan said...

I always think of it the other way around because MS was trying to get rid of getFoo() setFoo().

I couldn't find a Microsoft based source that explained auto properties. They seemed to be a bit hidden.

 
At 8:17 AM, Blogger Ryan said...

I was able to find: http://msdn.microsoft.com/en-us/library/bb384054.aspx Although I'm not sure I would've googled for "auto properties" without having known about them first.

 

Post a Comment

<< Home