Your issue is caused by your usage of ref
, which the C# spec defines as:
A parameter declared with a ref modifier is a reference parameter.
A reference parameter does not create a new storage location. Instead,
a reference parameter represents the same storage location as the
variable given as the argument in the function member, anonymous
function, or local function invocation. Thus, the value of a reference
parameter is always the same as the underlying variable.
If the type is modified as part of the call, it can no longer be the same underlying variable.
Passing the reference by value does not have the same restriction:
TryMe(child);
Console.WriteLine("Hello World");
static void TryMe(ParentClass parent)
{
}
static ChildClass child = new ChildClass();
public class ParentClass
{
public int i;
}
public class ChildClass : ParentClass
{
public char a;
}
As mentioned in the comments, you either need to remove ref
and pass the references by value, or you need to include methods for all polymorphic cases:
TryMe(ref child);
TryMe(ref parent);
static void TryMe(ref ParentClass parent) { }
static void TryMe(ref ChildClass parent) { }
static ChildClass child = new ChildClass();
static ParentClass parent = new ParentClass();
public class ParentClass
{
public int i;
}
public class ChildClass : ParentClass
{
public char a;
}