for instance in the below code from the page http://msdn.microsoft.com/en-us/library/k6sa6h87.aspx constructors CoOrds() are created in the class CoOrds , but we can also implement by not creating them and directly creating the objects p1 and p2 in the main() and setting the values of x and y...so what is the purpose of creating a constructor...
class CoOrds { public int x, y; public CoOrds() { x = 0; y = 0; } public CoOrds(int x, int y) { this.x = x; this.y = y; } 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); Console.WriteLine("CoOrds #1 at {0}", p1); Console.WriteLine("CoOrds #2 at {0}", p2); Console.ReadKey(); } }
i am new at this so please explain in detail and excuse me for asking a basic thing...thanx....
Datta KharadPosted Nov 22, 2011, 6:05 AM
Constructor:-
Whenever you will create object of class then compiler automatically create default constructor even if you didn't create constructor. But in this case you can set default value of x and y is 0 and suppose you want to set your values to x and y (explicitly) then you need to create parameterized constructor and pass value to x and y.
public int x,y;
// Default constructor:
public CoOrds
{
x=0;
y=0;
}
//Parameterized Constructor
public CoOrds(int x, int y)
{
this.x=x;
this.y=y;
}
Datta KharadPosted Nov 22, 2011, 7:27 AM
neha dhimanPosted Nov 22, 2011, 6:16 AM
Satyapriya NayakPosted Nov 22, 2011, 5:58 AM
Please refer Our recommended articles.
Thanks