As everybody may already know, Default Parameter is a new feature comes from .NET 4, but I would like to show some code snippets to demo how it works in overload method.
So let’s start write some code here, I am trying to use default parameter every where in this demo, it may doesn’t make any sense at all, just for demo purpose:
1: public class Foo
2: {
3: private int x, y;
4:
5: public Foo(int x = 1, int y = 2)
6: {
7: this.x = x;
8: this.y = y;
9: }
10:
11: public void PrintOut()
12: {
13: Console.WriteLine("x is {0}, y is {1}", x, y);
14: }
15:
16: public void PrintOut(int x = 5)
17: {
18: Console.WriteLine("x is {0}, this is being called from single parameter method:PrintOutMethod", x);
19: }
20:
21: public void PrintOut(int x = 5, int y = 6)
22: {
23: Console.WriteLine("x is {0}, y is {1}, this is being called from two parameter method", x, y);
24: }
25: }
So the caller using some code like this:
1: var Foo = new Foo();
2:
3: Foo.PrintOut();
4: Foo.PrintOut(50);
5: Foo.PrintOut(x: 60);
6: Foo.PrintOut(y: 60);
No surprise, the result comes out:
Looks like C# compiler using its best guess, if caller pass in one value, it doesn’t matter if it is explicit the parameter’s name or not, it will call the fittest method.
So, Basically, I think named parameter provides a lots of convenience, but like everything else It may brings some confusion when using it reckless in the code.
Homework:
You may try another kind of overload method, like DoMath(int a), DoMath(double a), DoMath<T>(T a) and call it with DoMath(2), guess which one is pops up~
As a matter of fact, we can do a lot of fun stuff with generic type, you can comment out another single parameter method, and add
1: public void PrintOut<T>(T x)
2: {
3: Console.WriteLine("x is {0}, this is being called from generic parameter method", x);
4: }
And after you tried out, maybe change the “x” parameter name to another one, like “y”, then call again, see what is gonna happen, very interesting.
Another interesting thing about named parameter is built two calsses, and use virtual and override method in them, something like below and test it out.
1: public class BaseClass
2: {
3: public virtual void Calculate(int y, int x)
4: {
5: Console.WriteLine("The x: {0}, y:{1} from base class", x, y);
6: }
7: }
8:
9: public class SubClass : BaseClass
10: {
11: public override void Calculate(int x, int y)
12: {
13: Console.WriteLine("The x: {0}, y:{1} from Man class", x, y);
14: }
15: }
The caller use named parameter to call this.
The reason is C# assign those value at compile time, when comes to base class, it remember y’s position in the first palace, and when the program actually running, the sub class’s method will run, and assign Y to Subclass’s X.