Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting fields in Constructor vs.{ get;set;} properties

Tags:

c#

Given a class:

public class NicePeople {
     public string VNP_Name;
     public int VNP_Age;
     public float VNP_Score;

     public NicePeople(string inName, int inAge, float inScore){
         VNP_Name = inName;
         VNP_Age = inAge;
         VNP_Score = inScore;
    }
}

and then you use it like:

NicePeople nicePerson = new NicePeople("Joe", 55, 1.6f);

Is there any difference between that and:

public class NicePeople {
     public string VNP_Name {set;get;}
     public int VNP_Age {set;get;}
     public float VNP_Score {set;get;}        
}

If not, are constructors just for when you want do some extra work (like checking for valid values etc.) and totally not needed for basic stuff?

like image 283
D12.Erica Avatar asked Jul 27 '17 19:07

D12.Erica


2 Answers

Real question here is when to use constructor parameters vs properties. Others have already mentioned reasons. Here's another one.

Use parameterized constructor when your class instance cannot be created without those values. Any optional attributes of the instance can be set using properties. Consider a Person class. Any person needs at least a name to be identified. Age can be optional information, however.

public class Person {
    public Person(string name) {
        Name = name;
    }

    public string Name { get; private set; }
    public int Age { get; set; }
}
like image 72
Nikhil Vartak Avatar answered Oct 07 '22 16:10

Nikhil Vartak


Fields VS. Properties

The first way you are saying it is simply listing them as fields being accessed publicly without accessors:

 public string VNP_Name;
 public int VNP_Age;
 public float VNP_Score;

The second way is is wrapping a field with an accessor. It is called a property and is a member of a class not just a field. Such as this:

 public string VNP_Name {set;get;}
 public int VNP_Age {set;get;}
 public float VNP_Score {set;get;}

These act as normal get set statements would if they were broken apart. You could also do this which makes the properties set-able by the class only, but get-able publicly:

 public string VNP_Name { private set; get;}
 public int VNP_Age { private set; get;}
 public float VNP_Score { private set; get;}

As Far as the Constructor is Concerned They are the same. You could easily set a field in a constructor just as you would a field.

like image 43
Travis Tubbs Avatar answered Oct 07 '22 17:10

Travis Tubbs