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.