C
C#16mo ago
arch_il

❔ How does class casting work?

public class Foo
{
public virtual void Func()
{
Console.WriteLine("Foo");
}
}

public class Boo : Foo
{
public override void Func()
{
Console.WriteLine("Foo");
}
}


public class Program
{
public static void Main()
{
var myObjects = new List<Foo>();

myObjects.Add(new Foo()); // works
myObjects.Add(new Boo()); // works
myObjects.Add((Boo)(new Foo())); // how to make this work?

foreach (var myObject in myObjects)
myObject.Func();
}
}
public class Foo
{
public virtual void Func()
{
Console.WriteLine("Foo");
}
}

public class Boo : Foo
{
public override void Func()
{
Console.WriteLine("Foo");
}
}


public class Program
{
public static void Main()
{
var myObjects = new List<Foo>();

myObjects.Add(new Foo()); // works
myObjects.Add(new Boo()); // works
myObjects.Add((Boo)(new Foo())); // how to make this work?

foreach (var myObject in myObjects)
myObject.Func();
}
}
I think code explains itself, but still. How do i cast parent class to child class?
7 Replies
Thinker
Thinker16mo ago
(Boo)(new Foo()) will never work because a Foo isn't a Boo
arch_il
arch_ilOP16mo ago
but adding Boo to list of Foo works just fine
Thinker
Thinker16mo ago
Yes, because a Boo is a Foo myObjects accepts Foo objects, and you can implicitly cast a Boo to a Foo because one inherits from the other But Foo doesn't inherit from Boo, thus you cannot cast from Foo to Boo
arch_il
arch_ilOP16mo ago
can i define it somewhere?
Pobiega
Pobiega16mo ago
you can make a ToBoo method on Foo, or add an explicit conversion but at this point, this sounds like an $xy problem
MODiX
MODiX16mo ago
The XY Problem
Asking about your attempted solution rather than your actual problem
Accord
Accord16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server