0

Intellisense gives me an error 'myType' is variable but used like a type

var myType = myObject.GetType();
var result = MyMethod<myType>(param);

Where:

var myObject = new MyType(); // MyType extends MyBaseType

public static string MyMethod<TArgs>(string param)
   where TArgs : MyBaseType
{
    // Do stuff...
}

So at the runtime the myObject.GetType() is known (it's MyType in our case).

Question:

How could I in a right way pass myType "dynamically" (which in a runtime could be MyType) to public static string MyMethod<TArgs>(string param) method?

pavjel
  • 486
  • 10
  • 25
  • typeof(myObject) rather than .GetType() ?? – C. Knight May 30 '17 at 10:17
  • 1
    What's the point of the type arguments here? For runtime purposes you better should use `object` or `Type` as a function parameter instead of a type parameter – Timo May 30 '17 at 10:18
  • 2
    Basically you can´t. You already mentioned that `myType` is a *runtime*-type which isn´t known during *compile*-time. So whilst you can *call* the method with the runtime-type inferred to the generic method (as shown in the duplicate) you can *not* expect the instance returned from `MyMethod` to be striongly typed. This is all you know is that it deried from `object`. – MakePeaceGreatAgain May 30 '17 at 10:18
  • @HimBromBeere Thats not correct. You can do it by using reflection: typeof(this) .GetMethod("MyMethod") .MakeGenericMethod(myType) .Invoke(this, new object[] { param }); – Romano Zumbé May 30 '17 at 10:20
  • @RomanoZumbé The point of my comment was that the instance that is returned by `Invoke` is just an `object`. The actual runtime-type however cannot be inferred from the compiler. – MakePeaceGreatAgain May 30 '17 at 10:31

0 Answers0