I have this code:
Type leftType = workItem[LeftFieldName].GetType();
I then want to declare a variable of that type:
leftType someVar;
Is that possible?
You can use declarative statements to explicitly declare the variables you will use in your program. You can implicitly declare a variable's type simply by using the variable in an assignment statement.
Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.
The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable. Declare its type and value in one statement.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With