neha dhiman

neha dhiman

  • NA
  • 14
  • 11.7k

Constructor purpose

Nov 22 2011 5:39 AM
I am bit confused about the purpose of constructors......
 
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....



Answers (4)