I am new to using C#. I am most familiar with C++ and Java when it comes to Object-Oriented Programming and polymorphism. Can someone tell me why this upcast does not work in C#, and what I can do to get the upcast to work with ref.
using System;
public class ParentClass
{
public int i;
}
public class ChildClass : ParentClass
{
public char a;
}
public class Program
{
static void TryMe(ref ParentClass parent)
{
}
static ChildClass child = new ChildClass();
public static void Main()
{
TryMe(ref child);
Console.WriteLine("Hello World");
}
}
Your issue is caused by your usage of
ref, which the C# spec defines as: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:
As mentioned in the comments, you either need to remove
refand pass the references by value, or you need to include methods for all polymorphic cases: