Welcome to MSDN Blogs Sign in | Join | Help

Changing a Field to a Property

When you change a field to a property you need to re-build all code that used that field.

Even though it might be obvious to many but it isn't to at least some people. The reason is that the client code exactly remains the same!!! In one of the internal DLs someone raised this as a potential .NET bug. Lets look into the code

He had a class library that looked something like

using System;
namespace FieldToProp
{
public class MyClass
{
public string Author = "Abhinaba";
}
}

This class library is accessed from a client application as

MyClass mc = new MyClass();
Console.WriteLine(mc.Author);

Now the field Author is changed to a property with the same name

public class MyClass
{
public string Author
{
get { return "Abhinaba"; }
}
}

Since a property is used with the same syntax as a field the user expected the same client binary to just work when he dropped the new class-lib assembly. However, he got the exception "System.MissingFieldException: Field not found: 'FieldToProp.MyClass.Author'". On rebuilding the client the issue gets resolved.

The reason is that when a property as above is present in a class a method with the following MSIL signature is generated

.method public hidebysig specialname instance
string get_Author() cil managed

So the property needs to be called from the client as a method call.

callvirt instance string [FieldToProp]FieldToProp.MyClass::get_Author()

The compiler figures out that the target is a property and inserts the appropriate method call. However when the reference is to a filed the following MSIL is used in the client.

ldfld string [FieldToProp]FieldToProp.MyClass::Author

So without re-building the whole thing just doesn't work.

Published Tuesday, April 11, 2006 2:02 PM by abhinaba
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Public fields vs properties and a bit of YAGNI

Saturday, February 24, 2007 12:55 PM by Public fields vs properties and a bit of YAGNI

# re: Changing a Field to a Property

Saturday, July 21, 2007 9:17 AM by Ashish

This is an excellent find! Thanks for sharing.

# science investigatory project title

Friday, September 14, 2007 1:35 PM by science investigatory project title

science investigatory project title

# C-Sharp 3.0 Automatic Properties Vs Public Fields - MBLM Blog

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker