C# 3.0: Auto properties and Object Initializer : Example

Sample code for two new C# 3.0 features: Auto-properties and Object Initializers.
Here's a side-by-side example so the difference is clear.
//The long version (all .net versions)
public class LongPerson{
	private string name;
		public string Name{
		set{
			this.name = value;
		}
		get{
			return this.name;
		}
	}
}

//Autoproperty -- C# > 3.0
public class ShortPerson{
	public string Name { get; set; }
}

public class test{
	public static void Main(string[] args){

		//The long version: create an instance, set a property ...
		LongPerson longPerson = new LongPerson();
		longPerson.Name = "Bob";
		Console.WriteLine(String.Format("Hi {0}", longPerson.Name));
		
		//C# 3.0 -- Create an instance with an object initializer
		ShortPerson shortPerson = new ShortPerson(){ Name = "Bob"};
		Console.WriteLine(String.Format("Hi {0}", shortPerson.Name));
	}
}	
| Comments (0)TrackBacks (0)

0 TrackBacks

Listed below are links to blogs that reference this entry: C# 3.0: Auto properties and Object Initializer : Example.

TrackBack URL for this entry: http://www.rootsilver.com/mt-tb.cgi/78

Leave a comment