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?
Creating a JavaScript ObjectCreate a single object, using an object literal. Create a single object, with the keyword new . Define an object constructor, and then create objects of the constructed type. Create an object using Object.create() .
In Java, we can create objects with 6 different methods which are: By new keyword. By newInstance() method of Class class. By newInstance() method of constructor class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With