Got into a tricky situation in using optional parameters in tandem with method overriding and interfaces in C#. I have read this.
Just wanted to add another dimension to the whole picture. There were quite a few code illustrations in that post. I picked up the one involving tags by VS1 and added another dimension to it as it had interfaces as well as inheritance being demonstrated. Though the code posted over there does work and displays the appropriate string as found in the sub class, base class, and interface, the following code does not.
void Main()
{
SubTag subTag = new SubTag();
ITag subTagOfInterfaceType = new SubTag();
BaseTag subTagOfBaseType = new SubTag();
subTag.WriteTag();
subTagOfInterfaceType.WriteTag();
subTagOfBaseType.WriteTag();
}
public interface ITag
{
void WriteTag(string tagName = "ITag");
}
public class BaseTag :ITag
{
public virtual void WriteTag(string tagName = "BaseTag") { Console.WriteLine(tagName); }
}
public class SubTag : BaseTag
{
public override void WriteTag(string tagName = "SubTag") { Console.WriteLine(tagName); }
}
And the output is
SubTag
ITag
BaseTag
So, it appears that the type of reference holding the reference to the inherited/implemented subclass does matter in determining which optional parameter value gets picked up.
Has anyone faced similar issue and found a solution? Or has C# has got some workaround for this in the later releases? (The one I am using is 4.0)
Thanks.