Fields vs. Properties in C#

There is a very significant difference between a field and property within a class. The difference is in the behaviour of the field when defined as either a static or instance. Basically, if you create 2 instances of class which has a static field, when you change the value of that field, the values in both classes are changed. This may be needed in some requirements but you need to be aware of this and implement it wisely. However, if you field is an instance variable, then changing the value will only modify the value of that class instance.

I created 2 classes, a class with an instance field and a class with a static field.

public class InstanceCustomer
{
   public InstanceCustomer(string name) { Name = name; }
 
   //Property
   public string Name { get; set; }
 
   //Insatnce Field
   public string name = "<default value="">";
}
public class StaticCustomer
{
   public StaticCustomer(string name){ Name = name; }
 
   //Property
   public string Name { get; set; }
 
   //Static Field (not a good idea...)
   public static string name = "<default value="">";
 
   public static string GetStaticName(StaticCustomer sCustomer)
   {
      return name;
   }
}

Create 2 instances of each class:

InstanceCustomer iCustomer1 = new InstanceCustomer("John");
InstanceCustomer iCustomer2 = new InstanceCustomer("Yolanda");
StaticCustomer sCustomer1 = new StaticCustomer("Juan");
StaticCustomer sCustomer2 = new StaticCustomer("Chantel");
iCustomer1.name = "John Insatnce";

However, modifying the value of the class sCustomer1 does modify the:

StaticCustomer.name = "Fred";

If you choose to use fields instead of properties it is good practice to leave them as instance unless you actually need them to be static. As well, if you make a field static, it’s probably a good idea to make is protected so it can only be changed from within the class. By doing this you could put some logic around a change to the field.

Download the source.



Leave a Comment

Your email address will not be published.