I have this code:
Type leftType = workItem[LeftFieldName].GetType();
I then want to declare a variable of that type:
leftTy
GetType
is evaluated at run-time, and non-dynamic
declaration is at compile-time (it does get more specific than that, yes), so no. Even var
will require you to assign a value to it that is of unambiguous type.
You can do something like these and cast them to a known interface.
var someVar = Convert.ChangeType(someOriginalValue, workItem[LeftFieldName].GetType());
var someVar = Activator.CreateInstance(workItem[LeftFieldName].GetType());
If you replace var
with dynamic
(and you are using .Net 4), you can call the methods you expect on the someVar object. If they don't exist, you'll just get a MissingMethodException.
No, that is not possible. The type of a variable has to be known at compile time.
You can declare a variable of type object
, it will be capable of storing any data type.
You cannot do that.
You could use the dynamic type for .Net 4, but for earlier .Net versions, the only type that will fit is object
, which you will need to manually cast later by again testing .GetType()
on what you assigned to the object
-typed variable.
Reading: SO link: whats-the-difference-between-dynamicc-4-and-var
object x = Activator.CreateInstance(Type) will let you create the object. Whether you can do much with it beyond that point, I'm not sure.
This is not possible.
Variable types are a compile-time concept; it would make no sense to declare a variable of a type which is not known until runtime.
You wouldn't be able to do anything with the variable, since you wouldn't know what type it is.
You're probably looking for the dynamic
keyword.