1

I am following c# complete reference. Following is the example that demonstrates Constructor and inheritance ,

class TwoDShape {
  double pri_width;
  double pri_height;
  // Properties for Width and Height.
  public double Width {
     get { return pri_width; }
     set { pri_width = value < 0 ? -value : value; }
  }
  public double Height {
     get { return pri_height; }
     set { pri_height = value < 0 ? -value : value; }
  }

class Triangle : TwoDShape {
  string Style;
  // Constructor.
  public Triangle(string s, double w, double h) {
    Width = w;   
    Height = h;  
    Style = s;   
  }

Now in Program.cs inside Main() i have

static void Main() {
    Triangle t1 = new Triangle("isosceles", 4.0, 4.0);
    Triangle t2 = new Triangle("right", 8.0, 12.0);
}

My question is that when we are using properties and can initialize our fields using them why we use constructor and then inside this Constructor fields are initialized.

Which is better approach use construct / properties or this approach. Please also explain this approach as i am unable to get this logic (both constructor and properties for initialization)

Hassan
  • 5,360
  • 2
  • 22
  • 35
Sikander
  • 2,799
  • 12
  • 48
  • 100
  • 1
    Following should answer your question: http://stackoverflow.com/questions/863045/what-is-the-preferred-way-of-constructing-objects-in-c-constructor-parameters http://stackoverflow.com/questions/830657/constructor-with-all-class-properties-or-default-constructor-with-setters – sundar Jun 02 '14 at 10:55

3 Answers3

3

Constructors should be used for classes that requires that certain variables (properties) are set for the class to be in a correct state. If you are using just properties, there is no guarantee that those properties are initialized as you get no compile errors and it's easy for the dev to forget to initialize them.

For instance, imagine that you have a class that do work in a database. If you define it like this:

public class UserRepository
{
    public DbConnection Connection { get; set; }

    public User GetUser(string id)
    {
        //...
    }
}

.. the following code would compile fine:

var repos = new UserRepository();
var user = repos.GetUser("22");

.. but when you run it you'll get an exception.

If you instead use a constructor you won't be able to use the class unless you pass a database connection.

public class UserRepository
{
    public UserRepository(DbConnection connection)
    {
        if (connection == null) throw new ArgumentNullException("connection");

        Connection = connection;
    }

    public DbConnection Connection { get; private set; }

    public User GetUser(string id)
    {
        //...
    }
}


//Now forced to init the class correctly
var repos = new UserRepository(dbConnection);
var user = repos.GetUser("22");

Another aspect of this is code maintenance. When you initially write code you usually have full control over what it contains and how you should initialize the classes. Hence everything is working well. But when you come back to the project in a couple of months you'll probably forgot a lot. If you are using constructors then you can be sure that all classes you create have been initialized properly.

jgauffin
  • 99,844
  • 45
  • 235
  • 372
  • as a beginner up-till now i used either constructor or properties is it standard practice to always use properties inside constructor or it should be used where i have to make sure its initialized ? and for such situations is it ok to use just constructor as it will make sure initialization is done , – Sikander Jun 02 '14 at 11:12
  • 2
    Use a constructor every time a class requires some sort of information to be fully functional. The constructor is used to communicate that some information is required while properties with public setters communication that something is optional. – jgauffin Jun 02 '14 at 11:16
1

In simple terms using the constructor abstracts the work that is being done, placing it in a black box of sorts.

Setting the values on the properties gives the user more freedom at the risk that they may do something the developer of the class did not expect.

It all boils down to how much freedom you are willing to give those that use your class.

David Pilkington
  • 13,528
  • 3
  • 41
  • 73
1

The constructor shoud set all the fields that are mandatory for the object. So you should implement a constructor that create a consistent instance.

Once the instance is created you can use properties to change the object state, but this could be dangerous because these changes can cause an incorrect state for your instance.

I always prefer to implement my classes as immutable types, so you set state in the constructor and only provide "getters" to access fields value.

davioooh
  • 23,742
  • 39
  • 159
  • 250