MSIL Trivia - 3 (Constructors in .NET)
Background: Let's write the following code in C# (cons.cs)
using C = System.Console;
public class X
{
int i, j;
public X()
{
}
public X(int i)
{
this.i = i;
}
public X(int i, int j)
{
this.i = i;
this.j = j;
}
public void PrintValues()
{
C.WriteLine("i = {0}, j = {1}", this.i, this.j);
}
}
public class Constructor_Test
{
public static void Main()
{
C.WriteLine("Create an object of class X");
X objX1 = new X(100);
C.WriteLine("We created an object with i = 100. Let's print it now...");
objX1.PrintValues();
C.WriteLine("Hmm... let's create another object with i = 5 and j = 10 and print the values");
X objX2 = new X(5, 10);
objX2.PrintValues();
C.WriteLine("Trying to create a new object with default constructor and print the values");
X objX3 = new X();
objX3.PrintValues();
}
}
Compile it using csc, and execute it. Everything works fine. Now comment out...
public X()
{
}
Try compiling again, and you will see the following...
I:\Code>csc cons.cs
Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.42
for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727
Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.
cons.cs(34,13): error CS1501: No overload for method 'X' takes '0' arguments
cons.cs(8,9): (Location of symbol related to previous error)
cons.cs(12,9): (Location of symbol related to previous error)
That implies that you can't use
X objX3 = new X(); if you don't have a default constructor. Right?
Question> But then, how does this one work??
using C = System.Console;
public class X
{
int i, j;
public void PrintValues()
{
C.WriteLine("i = {0}, j = {1}", this.i, this.j);
}
}
public class Constructor_Test
{
public static void Main()
{
X objX3 = new X();
objX3.PrintValues();
}
}
Answer> Notice how the default constructor is created for you, even if you don't have a constructor defined.
On the other hand, if you have the default contructor and the following commented out in the first code snippet...
X objX3 = new X();
objX3.PrintValues();
...your cs file should compile and you get something as follows...
Notice that, since you have a couple of constructors defined, CSC doesn't create an empty and default constructor for you and that's the reason why you were seeing the compile error message above.
Cheers,
Rahul
Comments
- Anonymous
February 11, 2008
PingBack from http://www.biosensorab.org/2008/02/11/msil-trivia-3-constructors-in-net/