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.
Comments
Anonymous
February 24, 2007
PingBack from http://www.hedgate.net/articles/2007/02/24/public-fields-vs-properties-and-a-bit-of-yagniAnonymous
July 21, 2007
This is an excellent find! Thanks for sharing.Anonymous
September 14, 2007
science investigatory project titleAnonymous
July 10, 2008
PingBack from http://www.mblmsoftware.com/mblm/20080710-C-Sharp-3.0-Automatic-Properties-Vs-Public-Fields.aspxAnonymous
February 12, 2009
I had a freaked 'Field not found' in my release version of our program. This helped. It was a volatile int variable. I changed it to property and it works ... :). Thanks for sharing this information.Anonymous
May 14, 2009
PingBack from http://aleembawany.com/2009/05/14/properties-vs-fields/Anonymous
May 22, 2009
wow...you saved my day...thanks alot.Anonymous
February 03, 2010
Hi, I had this error, and a clean did not work. The error was originating from a ascx file I had on the server. Opening the ascx file, and resaving it with a minor alteration to force the file attributes to change, cleared up the error in the page.Anonymous
February 04, 2010
Great informaton , thanks for sharing