best way to create object

146,117

Solution 1

Decide if you need an immutable object or not.

If you put public properties in your class, the state of every instance can be changed at every time in your code. So your class could be like this:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Person(){}
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    //Other properties, methods, events...
}

In that case, having a Person(string name, int age) constructor is not so useful.

The second option is to implement an immutable type. For example:

public class Person
{
    public string Name { get; private set; }
    public int Age { get; private set; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    //Other properties, methods, events...
}

Now you have a constructor that sets the state for the instance, once, at creation time. Note that now setters for properties are private, so you can't change the state after your object is instantiated.

A best practice is to define classes as immutable every time if possible. To understand advantages of immutable classes I suggest you read this article.

Solution 2

Really depends on your requirement, although lately I have seen a trend for classes with at least one bare constructor defined.

The upside of posting your parameters in via constructor is that you know those values can be relied on after instantiation. The downside is that you'll need to put more work in with any library that expects to be able to create objects with a bare constructor.

My personal preference is to go with a bare constructor and set any properties as part of the declaration.

Person p=new Person()
{
   Name = "Han Solo",
   Age = 39
};

This gets around the "class lacks bare constructor" problem, plus reduces maintenance ( I can set more things without changing the constructor ).

Solution 3

There's not really a best way. Both are quite the same, unless you want to do some additional processing using the parameters passed to the constructor during initialization or if you want to ensure a coherent state just after calling the constructor. If it is the case, prefer the first one.

But for readability/maintainability reasons, avoid creating constructors with too many parameters.

In this case, both will do.

Solution 4

In my humble opinion, this is just a matter of deciding if the arguments are optional or not. If an Person object shouldn't (logically) exist without Name and Age, they should be mandatory in the constructor. If they are optional, (i.e. their absence is not a threat to the good functioning of the object), use the setters.

Here's a quote from Symfony's docs on constructor injection:

There are several advantages to using constructor injection:

  • If the dependency is a requirement and the class cannot work without it then injecting it via the constructor ensures it is present when the class is used as the class cannot be constructed without it.
  • The constructor is only ever called once when the object is created, so you can be sure that the dependency will not change during the object's lifetime.

These advantages do mean that constructor injection is not suitable for working with optional dependencies. It is also more difficult to use in combination with class hierarchies: if a class uses constructor injection then extending it and overriding the constructor becomes problematic.

(Symfony is one of the most popular and respected php frameworks)

Solution 5

If you think less code means more efficient, so using construct function is better. You also can use code like:

Person p=new Person(){
Name='abc',
Age=15
}
Share:
146,117

Related videos on Youtube

DevT
Author by

DevT

.net developer #SOreadytohelp - SOF helps resolve my probs

Updated on July 09, 2022

Comments

  • DevT
    DevT almost 2 years

    This seems to be very stupid and rudimentary question, but i tried to google it, but couldn't a find a satisfactory answer,

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public Person(){}
        public Person(string name, int age)
        {
            Name = name;
            Age = age;
        }
        //Other properties, methods, events...
    }
    

    My question is if i have class like this, what is the best way to create an object?

    Person p=new Person("abc",15)
    

    OR

    Person p=new Person();
    p.Name="abc";
    p.Age=15;
    

    What is the difference between these two methods and what is the best way to create objects?

    • Marc Gravell
      Marc Gravell over 11 years
      Just to add a third option to the mix: Person p=new Person { Name="abc", Age=15 }; - or a fourth: Person p = new Person(name: "abc", age: 15);. As X.L.Ant says: none is automatically "better"
  • GodsCrimeScene
    GodsCrimeScene over 11 years
    Easier to test classes as well if they don't require parameters in their constructors.
  • Servy
    Servy over 11 years
    Your immutable class should probably have public getters and private setters.
  • Kyle
    Kyle about 7 years
    As of C# 6 you can also drop the setters entirely to create readonly properties. This will actually guarantee that you don't accidentally modify the properties outside of a constructor.
  • Sinjai
    Sinjai almost 7 years
    Is it possible to use a constructor like the one above, but still do something with the values after they're declared? Currently I'm using that type of constructor everywhere in my program, but now I need to add additional constructor logic (using one of the parameters) -- major oversight.
  • habib
    habib almost 6 years
    You cannot use using() with a custom class without overloading Disposable function.