Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am using VS2010, and C#4. I have created a Console application in which I have a class that looks like this:
C#
class cl
{
  public int a, b;

  public cl()
  {
  }
  public cl(int x = 10, int y = 20)
  {
    this.a = x;
    this.b = y;
  }
  public void add()
  {
    Console.WriteLine(a+b);
  }
}


I call this from the Main function like this:
C#
class Program
{
  static void Main(string[] args)
  {
    cl obj = new cl(10);
    obj.add();
    Console.ReadKey();
  }
}
I would expect this program to fail to compile since I am passing a single parameter while creating the class object. Can somebody help me in understanding this behaviour?
Posted
Updated 4-Jul-11 2:28am
v3
Comments
CPallini 4-Jul-11 8:33am    
You created an application that correctly exploits a language feature that you don't know? Wow!
shikhar gilhotra 4-Jul-11 8:57am    
this is not the reply...

The reason it's not failing is because you are supplying default values in your two-parameter constructor. This feature was added in C#4, so that's quite legitimate. You can find more details on named and optional parameters here[^].
 
Share this answer
 
Comments
Abhinav S 4-Jul-11 8:34am    
perfect answer. my 5.
Sergey Alexandrovich Kryukov 4-Jul-11 16:17pm    
Correct, a 5.
--SA
public cl(int x = 10, int y = 20)

When you define some values in the constructor, you are indirectly defining optional parameters in .Net 4.0.
Thus your code works.

AFAIK, if you were using .Net 3.0, you would have got an error.

Read about optional arguments here[^].
 
Share this answer
 
Comments
Pete O'Hanlon 4-Jul-11 8:16am    
That's correct. This wouldn't have compiled in .NET3. My 5.
shikhar gilhotra 4-Jul-11 8:17am    
thx..i got it
Sergey Alexandrovich Kryukov 4-Jul-11 16:20pm    
Good question, but you should change 3.0 to 3.5 -- last version before 4.0 where default parameters were not yet introduced. (However, it was introduced is some other languages at least some 20 years ago, but I think earlier.) I voted 4.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900