Search code examples
c#propertiesencapsulation

Should you use properties to initialize your fields in the constructor?


Pretty simple question really, should I use my properties to initialize fields in the constructor or reference them directly?

Example:

public class Foo()
{
   private string example;

   public String Example
   {
      get/set etc..
   }

   public Foo(string exampleIn)
   {
      Example = exampleIn;
   }
}

Or is it better practice to do this:

public class Foo()
{
   private string example;

   public String Example
   {
      get/set etc..
   }

   public Foo(string exampleIn)
   {
      example = exampleIn;
   }
}

Either way, I don't think either would violate encapsulation so I am wondering if there is a preferred way to go?


Solution

  • Before automatic properties, which were introduced in C# 3.0, your second example is more "proper" in my opinion. Now with automatic properties I think this is best:

    public class Foo()
    {
       private string example;
    
       public String Example
       {
          { get; set; }
       }
    
       public Foo(string exampleIn)
       {
          Example = exampleIn;
       }
    }