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?
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.
This gets around the "class lacks bare constructor" problem, plus reduces maintenance ( I can set more things without changing the constructor ).
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.
Depends on your requirment, but the most effective way to create is:
Or you can use a data file to put many person objects in to a list or array. You do need to use the System.IO for this. And you need a data file which contains all the information about the objects.
A method for it would look something like this:
If you think less code means more efficient, so using construct function is better. You also can use code like:
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: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:
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.