Using either depends on the requirement.
If you want your class object to have some state (properties assigned) at the time of instantiation then use parametrized constructor. If your class doesn't have a default constructor (no parameters) then there will be no way for the user to instantiate a class without any state.
By default each class would have a default constructor (without any parameter), but once you define a parametrized constructor, there will be no default constructor unless you provide one explicitly.
Imagine if you have class like:
public class ClassName
{
public int ID { get; set; }
public string Name { get; set; }
public ClassName(int id, string name)
{
ID = id;
Name = name;
}
}
Since you have provided a parametrized constructor, User can't instantiate an object without passing ID
and Name
values. (ignoring reflection)
ClassName obj = new ClassName(); //This will error out
This is useful in scenarios where it is compulsory for an object to have some values at the time of instantiation.
Consider the DirectoryInfo
class provided by the .Net framework, you can't instantiate an object of DirectoryInfo
without parameter
DirectoryInfo dirInfo = new DirectoryInfo();//This will error out
Since DirectoryInfo
requires the object to have a path pointing to the directory, It would be of no use without a path, therefore it is provided with only a parametrized constructor
DirectoryInfo dirInfo = new DirectoryInfo(@"C:\Somefolder");