Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a downcast to a derived class with no data members be done in C#?

Tags:

c#

casting

I'm attempting to make a wrapper using inheritance. In reality I am working with de-serialization code that has very generic names and I am looking to save a few keystrokes over the method that wraps an inner object.

public class Base
{
  public string Foo { get; set; }
}

public class Derived : Base
{
  public string Bar { get { return this.Foo; } }
}

Base base = new Base();

Derived d = (Derived)base;

I get an error trying to downcast. Is this type of thing possible in C#? There's no additional data in the derived class so my C++ brain is telling me a downcast is possible...

like image 624
Aaron Anodide Avatar asked Feb 26 '23 00:02

Aaron Anodide


1 Answers

Nope. Class identity is determined by more than just data layout (and that's true in C++ too for non-POD types).

You might want to look into using extension methods to add additional functionality that doesn't require storage of additional data.

like image 122
Ben Voigt Avatar answered Apr 26 '23 16:04

Ben Voigt