Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a variable using a Type variable

Tags:

c#

c#-4.0

I have this code:

Type leftType = workItem[LeftFieldName].GetType(); 

I then want to declare a variable of that type:

leftType someVar; 

Is that possible?

like image 597
Vaccano Avatar asked Jan 26 '11 00:01

Vaccano


People also ask

How do you declare a variable type?

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.

How do you declare a variable in Python with type?

Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.

How do you define a type variable in TypeScript?

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.


2 Answers

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.

like image 77
Austin Salonen Avatar answered Oct 14 '22 11:10

Austin Salonen


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.

like image 21
SLaks Avatar answered Oct 14 '22 09:10

SLaks