I had a class like this
public class Child
{
public string ToXml()
{
return "Child : ToXml()";
}
public string ToXml( params string[] fields )
{
return "Child : ToXml(...)";
}
}
creating an instances of class Child and calling ToXml() returns the first overloaded function which was fine and dandy.
var obj = new Child();
Console.WriteLine( obj.ToXml() );
Output:
Child : ToXml()
But when I added a Parent class and changed the Child class to this :
public class Parent
{
public virtual string ToXml()
{
return "Parent : ToXml()";
}
}
public class Child : Parent
{
public override string ToXml()
{
return "Child : ToXml()";
}
public string ToXml( params string[] fields )
{
return "Child : ToXml(...)";
}
}
The output has changed to this :
Child : ToXml(...)
My question is, why is the behaviour like this? (I’m using VS2010 using .NET 3.5)
I kind of ‘fixed’ this problem by changing the second overloaded function to this : (I took out the params keyword
public class Child : Parent
{
public override string ToXml()
{
return "Child : ToXml()";
}
public string ToXml( string[] fields )
{
return "Child : ToXml(...)";
}
}
Which brings me to my second question (let me know if I should split this to 2 different post), what is the difference between the functions
ToXml( params string[] fields )
and
ToXml( string[] fields )
They both seems to work when I call the functions like so :
var obj = new Child();
Console.WriteLine( obj.ToXml( new [] { "foo", "bar" ) );
For your first question, this is by design:
For your second question, a params modifier make that parameter act as a varargs parameter, meaning it can receive multiple parameters comma-separated, and the array is created implicitly by the compiler.