Google
 

Monday, May 28, 2007

The mechanism of property in C#

I will show you what's the mechanism of the property feature in C#.

Summary:
1.Write a demo class
2.Compile the demo as library
3.Explorer the library by ILDASM : See the detail implementation of property in IL


1.Write demo class
Here write a demo class: Student.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace PropertyTesting
{
public class Student
{
private string name = string.Empty;
public string Name
{
get { return name; }
set { name = value; }
}
}
}

Save the Student.cs.
2.Compile the demo as library
Open "Visual Studio 2005 Command Prompt" and compile the Student class as Student.dll with the following command:

csc /target:library Student.cs

3.Explorer the library by ILDASM : See the detail implementation of property in IL

Open the Student.dll by ILDASM.
You will see:
All detail:
There other two methods: ( get_Name,set_Name) has been added.

Property Name Detail:
The Name property is actually calling the two methods: get_Name and set_Name
set_Name detail:
There the value is used as a temporary variable with type as string.

get_Name detail:

Conclusion:
1.The property is actually two methods: get_PropertyName and set_PropertyName.
2.The keyword "value" used in set is a temporary variable with the same type as property.

No comments: