1

I want to cast a generic class to its base type, having the class and the type inheritance.

I have these classes:

public class Segment<K> : SomeStructure where K : SomeStructure{...}

public class XXXXXXData : Segment<Key> {...}

public class Key : SomeStructure {...}

I have an instance of XXXXXXData called data but if I make a cast like

data as Segment<SomeStructure> It returns null.

Where I have these code, the variable can be a XXXXData or any kind of Segment<>. What can I do to cast to Segment<AmtsCobolStructure> so I could use the methods of these base class?

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
popiandro
  • 317
  • 1
  • 17
  • A Base class always has the minimum number of property of any of the inherited classes. So you can always cast the base class to any of the inherited classes, but cannot cast inherited classes to the base because number of properties are greater in the inherited classes. You do not have to do anything to get the properties of the base class, they are automatically part of the inherited class. – jdweng Sep 17 '19 at 10:18
  • 2
    Only because two classes have an inheritance-relation does not mean generic classes that use those first ones as generic arguments have the same relationship. In fact they don´t have **anything** in common. – MakePeaceGreatAgain Sep 17 '19 at 10:19
  • @HimBromBeere: You are absolutely wrong. The inherited class has all the properties of the base class. – jdweng Sep 17 '19 at 10:22
  • @jdweng Huuum? I never doubted about that. I just said the generic classes don´t have anything in common, even if their generic *arguments* have – MakePeaceGreatAgain Sep 17 '19 at 10:24

1 Answers1

1

You cannot do that in C#. You can only do it by introducing a generic interface on top level which is co-variant on the generic parameter using out like:

public class Segment<K> : ISegment<K> where K : SomeStructure{...}

While your interface should look like:

public interface ISegment<out T>
{

}

and your code for casting will use interface type now :

data as ISegment<SomeStructure>

check this demo fiddle as example.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160