0

Say, we have a generic class like this:

public sealed class Class1<T>
{
    private T _value;
    public T Value
    {
        get { return _value; }
    }
}

I want to initiate an object of type Class1 but type argument T is only dynamically available using GetType(). Is that possible to use a generic class with dynamic type as follows?

Class1<anObject.GetType()> obj = new Class1<anObject.GetType()>();

I know this code even can not be compiled but I need some sort of generic usage like this. According to this answer I should use MakeGenericType to infer the T argument using the reflection and create the object as follows:

Type typeArgument = anObject.GetType();
Type genericClass = typeof(Class1<>);
Type constructedClass = genericClass.MakeGenericType(typeArgument);
object created = Activator.CreateInstance(constructedClass);

But I don't know how to use object created, later! Because this is an implicit object and do not have access to its property Value. I also can't cast it to the Class1, If I could I didn't have to use MakeGenericType at first! How could I access the Value after I created the object ?

Community
  • 1
  • 1
a.toraby
  • 3,232
  • 5
  • 41
  • 73
  • The link was so helpful. Please review my edited question and remove the duplicate if you agree. Thanks for your attention. – a.toraby Aug 09 '15 at 12:36
  • 2
    The problem is that you do not know the type of `Value`, so how are you supposed to use it at compile time? You can get `Value` as type `object`, but you will be stuck in the "reflection world". It depends what you want to do with the class after you have constructed it, but you may need to rethink your approach. If you post a more specific question on building and _using_ the class, you may get more a useful response. – Rhumborl Aug 09 '15 at 13:02
  • 1
    Yep, sounds like you're coming at this from the wrong angle - there is more than likely a statically-typed way of doing this but nobody can help unless you post your usage. – Ant P Aug 09 '15 at 17:20
  • @a.toraby What are you really trying to accomplish here? How *would* you expect to know how to use `.Value` later? Is there some sort of constraint at play? What greater/outer thing exactly are you trying to accomplish? – Tyree Jackson Aug 10 '15 at 14:30

0 Answers0