Unable to understand method output with optional parameter

Today I wrote a small program to understand the basics of advanced C # options.

The following is the program:

abstract class AbstractClass { internal abstract void Test(); } sealed class DerivedClass : AbstractClass { internal override void Test() { Console.WriteLine("In override DerivedClass.Test() method"); } internal void Test(int a = 1) { Console.WriteLine("In DerivedClass.Test(int a=1) method " + a); } internal void Test(int b, int a = 1) { Console.WriteLine("In DerivedClass.Test(int b, int a=1) method " + string.Format("{0} {1}", b, a)); } } 

This is what I called the Test() method:

  DerivedClass d = new DerivedClass(); d.Test(); d.Test(6); d.Test(b:7); 

Output:

In the DerivedClass.Test method (int a = 1) 1

In the DerivedClass.Test method (int a = 1) 6

In the DerivedClass.Test method (int b, int a = 1) 7 1

Regarding d.Test(); : Here, I understand that it will treat Test() as a method with an optional parameter and will call Test(int a = 1) with this output:

In the DerivedClass.Test method (int a = 1) 1

But this is what confuses me when doing d.Test(6); : why this method call does not give an output like:

In the DerivedClass.Test method (int b, int a = 1) 6 1

According to my understanding, "6" is a required parameter, and it should call

 internal void Test(int b, int a = 1) 

Please explain what is wrong with my understanding.

Also how to call overriden method?

 internal override void Test() 
+5
source share
2 answers

The rule match for internal void Test(int a = 1) matches your code d.Test(6); best: it matches the number of arguments, types. This makes the method the best.

When called d.Test(b:7); you force it to run as the last method, since you map to the parameter name. This makes the best method the best.

The first ( d.Test(); ) does not match the method you expected ( void Test() ), since "native" methods are preferable to derived methods. Try to remove the base class or use the new operator for the method, and you will see.

+6
source

The rules around optional parameters can be a bit confusing, but a simple rule of thumb to keep in mind is that it will always use a method with fewer parameters than one with more.

So for

 d.Test(6); 

single parameter method:

 internal void Test(int a = 1) 

although this is an optional parameter.

0
source

All Articles