How to use a local variable as a type? The compiler said that "it is a variable, but is used as a type"

I have a code ...

in the run-time environment, we don’t know what type the variable v1 is! For this reason, we must write "if else" many times!

if (v1 is ShellProperty<int?>) { v2 = (v1 as ShellProperty<int?>).Value; } else if (v1 is ShellProperty<uint?>) { v2 = (v1 as ShellProperty<uint?>).Value; } else if (v1 is ShellProperty<string>) { v2 = (v1 as ShellProperty<string>).Value; } else if (v1 is ShellProperty<object>) { v2 = (v1 as ShellProperty<object>).Value; } 

I wrote it 4 times! The only difference is ShellProperty <AnyType>

Therefore, instead of writing this many lines using "if else statement"
I decided to use Reflection to get the type of the property at runtime!

  Type t1 = v1.GetType().GetProperty("Value").PropertyType; dynamic v2 = (v1 as ShellProperty<t1>).Value; 

This code can get what type of PropertyType is v1, and assignment is a good local variable t1.
But after that, my compiler says that "t1 is a variable, but is used as a type"
Therefore, it does not allow me to write t1 inside ShellProperty <>

Please tell me how to solve this problem and how to get a more compact code than me?
Do I need to create a new class?

+6
source share
2 answers

You were very close, you just missed the call to MakeGenericType .

I believe your code will look like this:

 Type t1 = v1.GetType().GetProperty("Value").PropertyType; var shellPropertyType = typeof(ShellProperty<>); var specificShellPropertyType = shellPropertyType.MakeGenericType(t1); dynamic v2 = specificShellPropertyType.GetProperty("Value").GetValue(v1, null); 

Edit: As @PetSerAl pointed out, I added several layers of indirection that were unnecessary. Sorry OP, you probably need one liner, for example:

 dynamic v2 = v1.GetType().GetProperty("Value").GetValue(v1, null); 
+8
source

For generics, you must create them dynamically.

 MethodInfo method = typeof(Sample).GetMethod("GenericMethod"); MethodInfo generic = method.MakeGenericMethod(myType); generic.Invoke(this, null); 

To create a shared object, you can

 var type = typeof(ShellProperty<>).MakeGenericType(typeof(SomeObject)); var v2 = Activator.CreateInstance(type); 

Refer to Initializing a Common Variable from a C # Type Variable

+5
source

All Articles