+ 2
Why do we use constructors instead of methods ?
4 Answers
+ 22
^_^
+ 8
They are used to create new objects of a class.
Even if you didn't make one for a class,its created by default,as without it, objects can't be created.
String m=new String("Hello");
here, string("Hello") is a constructor,used to make an object 'm' of class string with initial value "Hello"
+ 7
Thanks @Frost, I just love these FROSTy Storms.
- 2
In C#,
Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments. Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read.
Ref: https://msdn.microsoft.com/en-us/library/ace5hbzh.aspx
-------------------------------------------------------------------------------------------------
For e.g.
int myInt = new int();
is
int myInt = 0;
-------------------------------------------------------------------------------------------------
class CoOrds
{
public int x, y;
// Default constructor:
public CoOrds()
{
x = 0;
y = 0;
}
// A constructor with two arguments:
public CoOrds(int x, int y)
{
this.x = x;
this.y = y;
}
// Override the ToString method:
public override string ToString()
{
return (String.Format("({0},{1})", x, y));
}
}
class MainClass
{
static void Main()
{
CoOrds p1 = new CoOrds();
CoOrds p2 = new CoOrds(5, 3);
// Display the results using the overriden ToString method:
Console.WriteLine("CoOrds #1 at {0}", p1);
Console.WriteLine("CoOrds #2 at {0}", p2);
Console.ReadKey();
}
}
/* Output:
CoOrds #1 at (0,0)
CoOrds #2 at (5,3)
*/
Ref: https://msdn.microsoft.com/en-us/library/k6sa6h87.aspx