Let’s say I have these classes:
public class BaseMapClass<T1, T2>
{
protected T1 Thing1;
protected T2 Thing2;
}
public class InstanceMapClass1 : BaseMapClass<Type1, Type2>
{
public InstanceMapClass(Type1 x, Type2 y)
{
Thing1 = x;
Thing2 = y
}
}
public class InstanceMapClass2 : BaseMapClass<Type3, Type4>
{
public InstanceMapClass(Type3 x, Type4 y)
{
Thing1 = x;
Thing2 = y
}
}
Now I have a third class, I’d ideally want to have two generic IEnumerables that take their type based on the generics of the type passed in BaseMapClass
public class Three<T> where T : BaseMapClass<dynamic, dynamic>
{
IEnumerable<??> TypeXThings; // should be of the first dynamic type
IEnumerable<??> TypeYThings; // should be of the second dynamic type
}
so if I created a new class
Three<InstanceMapClass1> three = new Three<InstanceMapClass1>();
Type1 t1 = three.TypeXThings.FirstOrDefault();
or
Three<InstanceMapClass2> another = new Three<InstanceMapClass2>();
Type3 t3 = another.TypeXThings.FirstOrDefault();
Using dynamics and generics is it possible to set the type of these IEnumerables to the generic types of the BaseMapClass at runtime? What I really want is to be able to pass in this one mapping class and then be able to create collections based on their generic parameters. I feel like I’m going about this the wrong way, but the only other way I can think of doing it is
public class Three<T1, T2, T3>
{
IEnumerable<T2> Type1Things;
IEnumerable<T3> Type2Things:
}
Thanks! Also, I realize this may make no sense so please let me know where clarification is needed.
From your question:
dynamicisn’t used this way, and has nothing to do with generics. It is basically anobjectthat supports any method/property/field, and uses runtime compilation to pull up each method/property/field access.This isn’t a magic bullet, and will still throw an exception at runtime –
RuntimeBinderException– because Thing1/Thing2 areprotected.This is the blessing and the curse of
dynamic‘s use of runtime compilation 🙂Solution (to get your code to compile)
Your third example makes the most sense. Here it is combined with your existing code:
Though you’ll still inherit:
If this isn’t desirable, don’t inherit from
BaseMapClass, or change how it is defined.Suggestions on your final design
If this isn’t helping you solve your original problem, you might want to post your code on the Code Review site and see if you can get some feedback on your design.
My initial thoughts are that you should investigate if it would make sense to use
interfaces in your design, rather than inheriting from concrete types.Also see if there are existing types in the .Net framework that suit your purposes instead of inventing new ones (e.g.
Tuple<T1, T2>or maybeDictionary<T1, T2>).