Say I get an answer to my other question and I can get all my objects, which implement BaseClass<StorageClassBase>
, like this:
var t1 = myObjects.Where(o => o.GetType().HasBaseClassOf(typeof(BaseClass<>), typeof(StorageClassBase))).ToList();
How can I cast this list to List<BaseClass<StorageClassBase>>
?
I tried the following, but it results in a list of null
-s:
var res = t1.Select( x => x as BaseClass<StorageClassBase>).ToList();
For completeness sake:
BaseClass
is a generic abstract class, which is implemented by the selected objectsStorageClassBase
is also an abstract class. All the selected objects implementBaseClass
with some specific implementation ofStorageClassBase
.- the extension function
HasBaseClassOf
checks, whether theType
inherits fromBaseClass
with generic type parameterStorageClassBase
Minimal reproducible example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinimalReproducibleExample
{
public abstract class StorageClassBase
{
}
public class CoolStorageClass : StorageClassBase
{
}
public abstract class BaseClass<T> where T : StorageClassBase
{
}
public class CoolClass : BaseClass<CoolStorageClass>
{
}
public static class TypeExtensions
{
//https://stackoverflow.com/a/457708
public static bool HasBaseClassOf(this Type t, Type toCheck, Type genericParameter)
{
while ((t != null) && (t != typeof(object)))
{
var cur = t.IsGenericType ? t.GetGenericTypeDefinition() : t;
if (toCheck == cur)
{
//also check whether the generic types match
if (t.GenericTypeArguments[0].IsSubclassOf(genericParameter))
{
return true;
}
}
t = t.BaseType;
}
return false;
}
}
class Program
{
static void Main(string[] args)
{
List<object> myObjects = new List<object>();
myObjects.Add(new CoolClass());
myObjects.Add(new CoolClass());
myObjects.Add(new object());
myObjects.Add(new object());
var t1 = myObjects.Where(o => o.GetType().HasBaseClassOf(typeof(BaseClass<>), typeof(StorageClassBase))).ToList();
var t2 = t1.Select(o => o as BaseClass<StorageClassBase>).ToList();
Console.ReadKey();
}
}
}