Let's have a simple class, and main method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
bar bar = new bar();
bar.foo("a");
}
}
public class bar
{
public void foo(String a, String b = "b")
{
Console.WriteLine("Foo1");
}
}
}
This will write
Foo1
into the console.
Now, let's add an overload of the method into the class, using optional parameters:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
bar bar = new bar();
bar.foo("a");
}
}
public class bar
{
public void foo(String a, String b = "b")
{
Console.WriteLine("Foo1");
}
public void foo(String a)
{
Console.WriteLine("Foo2");
}
}
}
This will write
Foo2
into the console.
I was expecting compile time error because I expect that foo(String a, String b = "b") represents both foo(String a) and foo(String a, String b) signature, because of the optional parameters. But I was wrong. Why is this allowed?