Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Casting object with inner generic

I'm trying to cast a concrete class with generics to its interfaces and getting an error. I'm not sure what I'm missing. I need to get them into the common type.

Unable to cast object of type 'HierarchalLocationFilterSet' to type 'ImAFilterSet`1[ModelBase]'.

Everything compiles and runs, I just cant seem to do something like below.

ImAFilterSet<IModelBase> c = new HierarchalLocationFilterSet()

I can go half way ok

var thisWorks = c as FilterSetBase<LocationModel>;
var thisAlsoWorks = c as ImAFilterSet<LocationModel>;
//This is a hard fail   
var x = ((ImAFilterSet<ModelBase>) c );
var y = ((ImAFilterSet<IModelBase>) c );

Given

public interface ImAFilterSet<C> where C : IModelBase
{
     List<C> Children { get; set; }
}

public abstract class FilterSetBase<C> : ImAFilterSet<C> where C : IModelBase

public class HierarchalLocationFilterSet : FilterSetBase<LocationModel>

public class LocationModel : ModelBase

public abstract class ModelBase : IModelBase

Thanks!

like image 568
William Avatar asked Jan 25 '26 14:01

William


1 Answers

Generic classes/interfaces are invariant by default in .NET. That's why your code fails.

To cast FilterSetBase<T1> to ImAFilterSet<T2> T1 has to be the same T2. Having T1 inherit T2 is not enough.

You can fix that by changing declaration of FilterSetBase<C>:

public abstract class FilterSetBase<C> : ImAFilterSet<IModelBase>
    where C : IModelBase { }

or you can make ImAFilterSet covariant:

public interface ImAFilterSet<out C>
    where C : IModelBase { }

That's only possible when your interface doesn't declare any methods/properties with argument typed as C.

like image 104
MarcinJuraszek Avatar answered Jan 28 '26 04:01

MarcinJuraszek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!