Is it possible to cast a type definition in C#? Such as the following:
Type t = typeof(Activity) as typeof(System.Data.Entity.DbSet<MyDomain.Activity>)
Or trying to force a cast:
Type t2 = typeof(System.Data.Entity.DbSet<MyDomain.Activity>) typeof(Activity);
I want to create a type definition System.Data.Entity.DbSet<MyDomain.Activity>
I'm doing this because I'm using reflection on my domain, trying to pull on the properties on the context, in case anyone asks.
// get types we are interested in IHit
var instances = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetInterfaces().Contains(typeof(IHit))
&& t.GetConstructor(Type.EmptyTypes) != null
select Activator.CreateInstance(t) as IHit;
// loop and cast
foreach (var instance in instances)
{
Type t = instance.GetType()
Type t2 = typeof(System.Data.Entity.DbSet<t>) as typeof(t);
// do something with type 2
}
I want to create a type definition
System.Data.Entity.DbSet<MyDomain.Activity>
So you are actually asking t
to be the type of System.Data.Entity.DbSet<MyDomain.Activity>
. Why do you need to cast one type of another? The type MyDomain.Activity
doesn't have to do anything with the type you are actually requesting.
This should work for you:
Type t = typeof(System.Data.Entity.DbSet<MyDomain.Activity>)
If you don't have the type of MyDomain.Activity
yet, you should use Type.MakeGenericType
:
Type dbSetType = typeof(System.Data.Entity.DbSet<>);
Type t = dbSetType.MakeGenericType(yourActivityType);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With