Heisenberg
Heisenberg

Reputation: 33

Use Private variables or Properties in Constructor function

    class Person 
{
    private string fname;
    private string lname;

    public string F 
    {
        get { return fname; }
        set { fname = value; }
    }

    public string L
    {
        get { return lname; }
        set { lname = value; }
    }

    public Person(string fname, string lname) 
    {
        this.fname = fname;
        this.lname = lname;
    }
}

Which is better, to use the properties in the constructor, or to keep it as it is above? why?

P.s. I was using a function that uses the properties, that's why I didn't use auto properties.

Upvotes: 1

Views: 214

Answers (3)

Quality Catalyst
Quality Catalyst

Reputation: 6795

If you want an immutable class do this:

class Person 
{
    public string F { get; private set; }
    public string L { get; private set; }

    public Person(string f, string l) 
    {
        F = f;
        L = l;
    }
}

For a mutable class do this:

class Person 
{
    public string F { get; set; }
    public string L { get; set; }
}

and use it like this:

Person p = new Person { L = "laugh", F = "fun" };

Upvotes: 3

V Maharajh
V Maharajh

Reputation: 9629

  • Use properties if callers have to modify them after constructing the object.
  • Use get-only properties if callers have to read, but not change them.
  • Use the constructor parameters to force callers to create objects that have a "good state" (eg. non-null first and last names)

Upvotes: 0

Derrick Moeller
Derrick Moeller

Reputation: 4950

It isn't going to matter, in your case I would use auto-implemented properties because you aren't performing any work in the getter or setters.

class Person 
{
    public string F { get; set; }

    public string L { get; set; }

    public Person(string fname, string lname) 
    {
        F = fname;
        L = lname;
    }
}

Upvotes: 1

Related Questions