Saturday, March 03, 2007 2:34 PM bart

C# 3.0 Automatic Properties explained

A few months ago in the TechEd: Developers Europe timeframe I blogged about the Automatic Property feature in C# 3.0. Today I'm finally able to give you a little demo on it via the Orcas March 07 CTP. In case you missed it, tons of people have blogged about the availability of the March 07 CTP, including David.

So here's the code sample I'm talking about:

1 using System; 2 3 namespace ConsoleApplication1 4 { 5 class Program 6 { 7 public string Name { get; set; } 8 9 static void Main(string[] args) 10 { 11 var p = new Program(); 12 p.Name = "Bart"; 13 } 14 } 15 }

The clue is on line 7 where I've declared an automatic property. Basically this frees me from the burden of declaring a private variable and a get and set accessor to it by means of a property. Although you can just use the "prop" code snippet in Visual Studio, this is much cleaner in case you don't need the private fields at all. Imagine some entity mapping class that consists of 20 properties, do you want to see all of the private variable, getter and setter noise around your class? I don't think so.

Please notice that the use of automatic properties is not equal to just defining a public field - you still keep the get_PropertyName and set_PropertyName methods behind the scenes as well as all the metadata that goes with a property, as illustrated below:

This means your code can be upgraded at any time to define getters/setters together with an explicitly defined member variable when you need to do so, without having to recompile external consumers of your code (i.e. the "contract" remains untouched). Behind the scenes what happens is the injection of a private member variable, prefixed with <>k__AutomaticallyGeneratedPropertyField#, like this:

.field private string '<>k__AutomaticallyGeneratedPropertyField0' .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )

The CompilerGeneratedAttribute attribute is useful for tools to find out about these auto-generated things. Next, the compiler emits a getter and setter for you:

.method public hidebysig specialname instance string get_Name() cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: ldarg.0 IL_0001: ldfld string ConsoleApplication1.Program::'<>k__AutomaticallyGeneratedPropertyField0' IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret } // end of method Program::get_Name .method public hidebysig specialname instance void set_Name(string 'value') cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld string ConsoleApplication1.Program::'<>k__AutomaticallyGeneratedPropertyField0' IL_0007: ret } // end of method Program::set_Name

All the stuff in here is pretty much the same as a manually defined property, except for the presence of the CompilerGeneratedAttribute attribute. Finally, there's the metadata for the property:

.property instance string Name() { .get instance string ConsoleApplication1.Program::get_Name() .set instance void ConsoleApplication1.Program::set_Name(string) } // end of property Program::Name

Notice that automatic properties should have both a getter and a setter declared. Read-only or write-only properties are not permitted. After all, a typical use for automatic properties is to define "property bag" kind of classes or structs. Of course, there's IntelliSense too:

With the screenshot above I've also shown that local type inference (keyword "var") has now full IDE support (i.e. when you type p. the IDE already knows the type of the variable in order to provide accurate IntelliSense). Enjoy!

Technorati tags: , ,
Del.icio.us | Digg It | Technorati | Blinklist | Furl | reddit | DotNetKicks

Filed under:

Comments

# re: C# 3.0 Automatic Properties explained

Saturday, March 03, 2007 3:28 PM by frederik

Hmm, It would've been nice if automatic properties would also support 'getter' only props.

# Automatische Properties

Saturday, March 03, 2007 4:09 PM by TheUndeadable entwickelt

Juchhu, Orcas scheint eine wahre Pracht zu werden: http://community.bartdesmet.net/blogs/bart/rss.aspx Kurz und schmerzlos: Vorher: public class Klasse { String _Name; public String Name { get { return _Name; } &

# New C# "Orcas" Language Features: Automatic Properties, Object Initializers, and Collection Initializers

Thursday, March 08, 2007 11:19 PM by Community Blogs

Last week we shipped the March CTP of our Visual Studio and .NET Framework "Orcas" release. It is available

# New C# "Orcas" Language Features: Automatic Properties, Object Initializers, and Collection Initializers

Thursday, March 08, 2007 11:31 PM by BusinessRx Reading List

Last week we shipped the March CTP of our Visual Studio and .NET Framework "Orcas" release. It is available

# re: C# 3.0 Automatic Properties explained

Friday, March 09, 2007 8:59 PM by halo

frederick,

I've not toyed with the CTPs but I imagine that scenario could be accomplished using different accessability:

public string Name { get; private set; }

That way you can only set Name within the class.  I imagine someone else can confirm or deny this functionality.

# re: C# 3.0 Automatic Properties explained

Saturday, March 10, 2007 12:12 PM by e.thermal

automatic properties seem interesting, but in all the write ups this one included there is no mention of how to access the private member within the class that gets automatically generated.   When writing data back to the database I always get the data from the private member.  How would one do this now?   Use the convoluted automatically created member name?  or use the public property from within the class?

# re: C# 3.0 Automatic Properties explained

Saturday, March 10, 2007 1:59 PM by bart

Hi e.thermal,

There are lots of valid answers to your question. First of all, let's point out that there is no way to refer to the private member - it's hidden and it stays hidden as long as you use an automatic property.

Concerning the database functionality, you'll need to use the public getter. In fact, the real question should be where you want to put database logic - inside the class (which acts as an entity, e.g. Person - and therefore is in the BLL) or somewhere else in another layer, consuming the public interface of the entity object, typically in the DAL. I prefer the latter solution. Automatic properties fit in this strategy because these allow an elegant definition of entity classes.

Another typical usage of entity objects that only use public properties are classes that are meant to be serialized, acting as a container for multiple data fields.

-Bart

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Saturday, March 10, 2007 6:12 PM by Joycode@Ab110.com

【原文地址】 New C# "Orcas" Language Features: Automatic Properties, Object Initializers, and Collection Initializers

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Saturday, March 10, 2007 6:49 PM by Athrun

【原文地址】NewC#

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Sunday, March 11, 2007 8:58 PM by ljianl

【原文地址】New C#

# Expert Texture &raquo; Automatic Properties in C# 3.0

Tuesday, March 13, 2007 8:36 AM by Expert Texture » Automatic Properties in C# 3.0

# Teccky - eccky techlog &raquo; New C# &#8220;Orcas&#8221; core language features:

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Sunday, March 18, 2007 8:31 PM by shoutor

上个星期,我们发布了我们的Visual Studio和.NET框架Orcas版三月份的CTP,这是个谁都可以下的免费下载,同时提供VPC镜像(允许你在一个虚拟机里运行它)以及单独的安装文件(注:如果你在运行Vista的话,你要确认你只使用VPC版本)。你可以在这里下载。

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Tuesday, March 20, 2007 4:22 AM by 清清月儿

除了那些框架和工具类的精彩新特性外,我认为开发人员(包括所有的.NET应用类型的开发人员)会非常喜爱Orcas的一件事情是,VB和C#将包含一些新语言特性和改进。这些语言改动将以既微妙又深刻的方式改进我们的开发体验,势将改进效率,减小我们需要键入的代码量。

# Nuevas caracter??sticas de la nueva versi??n de C# Orcas &laquo; Thinking in .NET

# New C# "Orcas" Language Features: Automatic Properties, Object Initializers, and Collection Initializers

Thursday, March 29, 2007 4:20 AM by ASP.NET

Last week we shipped the March CTP of our Visual Studio and .NET Framework "Orcas" release. It is available

# The IQueryable tales - LINQ to LDAP - Part 0

Thursday, April 05, 2007 7:04 PM by B# .NET Blog

Here we are again for some cool LINQ stuff. In the past I've been blogging on C# 3.0 language innovation

# The IQueryable tales - LINQ to LDAP - Part 0: Introduction

Friday, April 06, 2007 5:04 AM by B# .NET Blog

Here we are again for some cool LINQ stuff. In the past I've been blogging on C# 3.0 language innovation

# The IQueryable tales - LINQ to LDAP - Part 1: Key concepts

Friday, April 06, 2007 8:14 AM by B# .NET Blog

Introduction Welcome to the first real part of our LINQ-to-LDAP series. So far, we've been discussing:

# The IQueryable tales - LINQ to LDAP - Part 2: Getting started with IQueryable<T>

Friday, April 06, 2007 5:45 PM by B# .NET Blog

Introduction Welcome back to the LINQ-to-LDAP series. So far, we've been discussing: Part 0: Introduction

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Saturday, April 28, 2007 5:31 PM by 清风涤尘

.net c# 改进 语言 特性 .net3.0新特新

# C# 3.0 Automatic Properties &laquo; Technoblog by Boris Kirzner

Pingback from  C# 3.0 Automatic Properties &laquo; Technoblog by Boris Kirzner

# Lo nuevo de C# 3.0 (1 de n): Propiedades automáticas

Sunday, July 15, 2007 9:21 PM by .NET a 2.860 m de altura

Hace algunos d&iacute;as ya, baj&eacute; la m&aacute;quina virtual con el Beta 1 de Visual Studio 2008

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Tuesday, August 14, 2007 8:43 PM by 林西

新的C#语言特性:自动属性(AutomaticProperties)

如果你现在是C#开发人员的话,你大概非常习惯编写象下面这个代码片段一样带有基本属性的类型:

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Tuesday, August 21, 2007 6:53 PM by BoardPung

Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Wednesday, August 22, 2007 4:58 AM by 瑞克

【原文地址】NewC#

# Orcas中C#语言的新特性:自动属性,对象初始化器,和集合初始化器

Wednesday, August 22, 2007 4:58 AM by 瑞克

【原文地址】NewC#

# Expert Texture &raquo; Automatic Properties Follow-up

Monday, August 27, 2007 11:49 AM by Expert Texture » Automatic Properties Follow-up

Pingback from  Expert Texture &raquo; Automatic Properties Follow-up

# C# 3.0 Orcas Language Features - Automatic Properties

Monday, October 01, 2007 3:07 AM by Doga Oztuzun

C# 3.0 Orcas Language Features - Automatic Properties

# Auto implemented properties C# 3.0

Monday, October 01, 2007 11:54 PM by Willem Meints

Saturday evening I was coding again on my scheduling app when something odd striked me. Visual Studio

# C# automaatsed omadused

Thursday, November 15, 2007 2:31 PM by DT blogi

C# 3.0 teeb klassidele omaduste defineerimise senisest mõnusamaks. Klasside kood jääb lühemaks ning muutub paremini loetavaks. Uue lisandi nimi on automatic properties. Oletame, et meil on klass, kus on terve rivi omadusi, mis ainult tagastavad m...

# Automatic Properties

Monday, November 19, 2007 8:55 AM by Gyun's Blog

Automatic Properties

# Automatic Properties

Monday, November 19, 2007 8:55 AM by Gyun's Blog

Automatic Properties

# New C# 3.0 -

Tuesday, November 27, 2007 2:12 AM by Vu Nguyen's Blog

New C# 3.0 -

# Automatic properties and replacing the Visual Studio 2008 'prop' snippet

Tuesday, December 04, 2007 3:20 AM by Dennis van der Stelt

In .NET Framework 3.5, we&#39;ve gained automatic properties. Automatic properties are really simple

# Automatic Properties

Thursday, December 06, 2007 1:07 AM by Gyun's Blog

Automatic Properties

# Chris online &raquo; How To: Automatic Properties

Saturday, December 22, 2007 3:25 PM by Chris online » How To: Automatic Properties

Pingback from  Chris online &raquo; How To: Automatic Properties

# .NET3.5?????????,????????????????????????????????????????????????????????? | Richie's Blog

Pingback from  .NET3.5?????????,????????????????????????????????????????????????????????? | Richie's Blog

# C# 3.0: Automatic Properties

Wednesday, January 23, 2008 4:57 PM by Corey's .NET Tip of the Day

In reading blogs today, I had overlooked this feature and I am not sure what to think about it so I thought

# Using The Silverlight DataGrid

Thursday, March 20, 2008 10:50 PM by Scott Morrison

If you have ever worked on an application that displayed large amounts of data, one of the cornerstones

# http://bartdesmet.net/blogs/bart/archive/2007/03/03/c-3-0-automatic-properties-explained.aspx

# Technoblog &raquo; Blog Archive &raquo; C# 3.0 Automatic Properties

Thursday, March 27, 2008 3:38 PM by Technoblog » Blog Archive » C# 3.0 Automatic Properties

Pingback from  Technoblog &raquo; Blog Archive   &raquo; C# 3.0 Automatic Properties

# Where did my Property Snippet go in Visual Studio 2008?

Saturday, April 12, 2008 6:46 PM by Rare Groove Rider

Where did my Property Snippet go in Visual Studio 2008?

# C??ng ngh??? m???i &raquo; Blog Archive &raquo; New C# &#8220;Orcas&#8221; Language Features: Automatic Properties, Object Initializers, and Collection Initializers

Pingback from  C??ng ngh??? m???i  &raquo; Blog Archive   &raquo;  New C# &#8220;Orcas&#8221; Language Features: Automatic Properties, Object Initializers, and Collection Initializers

# 今天找到關於Silverlight DataGrid 的一些技巧,記錄下來,以備後用.

Thursday, June 05, 2008 12:47 AM by 蓝色飞翔

今天找到關於SilverlightDataGrid的一些技巧,記錄下來,以備後用.

# New C# &#8220;Orcas&#8221; Language Features: Automatic Properties, Object Initializers, and Collection Initializers &laquo; using &#8230;

Pingback from  New C# &#8220;Orcas&#8221; Language Features: Automatic Properties, Object Initializers, and Collection Initializers  &laquo; using &#8230;

# C#的新特性:自动属性,对象初始化器,和集合初始化器(转载)

Saturday, December 27, 2008 7:16 AM by 小戚园地

【原文地址】NewC#

# .NET: 3.0 - Automatic Properties

Tuesday, January 06, 2009 1:32 AM by .NET

&lt;p&gt;&lt;img align=&quot;right&quot; alt=&quot;&quot; src=&quot;/Portals/SkySigal/BlogImages/blog_csharp.png&quot; /&gt;&lt;/p&gt; &lt;p&gt;The &lt;a title=&quot;C# Version 3.0 Specification&amp;quot ...

# Automatic Properties in C# 3.0

Thursday, April 02, 2009 8:43 PM by Technical Musings

We just upgraded our servers to support .Net 3.x, so at last I'm able to start migrating some of my code. I haven't taken a close look at all the features available yet, but one that caught my eye and...

# The Chefbook database schema &laquo; Adventures in Coding

Wednesday, April 08, 2009 8:17 PM by The Chefbook database schema « Adventures in Coding

Pingback from  The Chefbook database schema &laquo; Adventures in Coding

# Diving into Test Driven Development &laquo; Adventures in Coding

Pingback from  Diving into Test Driven Development &laquo; Adventures in Coding

# C# - Automatic Properties

Friday, April 24, 2009 4:32 PM by Блогот на Глигур

Оние кои го користат C# најверојатно знаат што се Properties, како да ги користат и која е придобивката од нивната употреба. Но, доколку не сте чул

# Visual Studio 2010 Class Designer = (VS2008 Class Designer)--?

Thursday, May 28, 2009 7:49 PM by Jersson on Geeks·ms

El Class Designer que trae el Visual Studio, desde la versi&oacute;n 2005 , me parece muy bueno. Con

# 新的C#语言特性:自动属性(Automatic Properties)

Tuesday, August 11, 2009 8:28 PM by 袁磊

新的C#语言特性:自动属性(AutomaticProperties)如果你现在是C#开发人员的话,你大概非常习惯编写象下面这个代码片段一样带有基本属性的类型:

# Using LINQ : Automatic Properties, Object Initializer and Collection Initializers &laquo; T. Nayak

Pingback from  Using LINQ : Automatic Properties, Object Initializer and Collection Initializers &laquo; T. Nayak

# Illistrated 20properties | 360inconline

Sunday, March 27, 2011 4:33 PM by Illistrated 20properties | 360inconline

Pingback from  Illistrated 20properties | 360inconline

# Datagrid in Silverlight with C# | The WoOz

Tuesday, April 02, 2013 5:36 AM by Datagrid in Silverlight with C# | The WoOz

Pingback from  Datagrid in Silverlight with C# | The WoOz