I have this code:
Type leftType = workItem[LeftFieldName].GetType();
I then want to declare a variable of that type:
leftType someVar;
Is that possible?
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 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.
var someVar = workItem[LeftFieldName], nevertheless it's not safe, because you can accidentally alter (in case of a reference type) value of the original object. I'd recommend you to stick with the strategy described in the Austin's answer (var someVar = Activator.CreateInstance(workItem[LeftFieldName].GetType());)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.
Form object and I add the fields I want to edit using something like new EditField<MemberAddress>(e => e.AddressId). I use the MemberExpression to create the right form element, but some types need a default value. EG long has default 0 and DateTime has a date as default. Instead of creating a lot of If statements to set the proper default value for every type, I simple create an Instance like Austin explained and use .ToString() to get the right default value.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.
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
var someVar; to var someVar = which assigns it then to implicitly type someVar. This gets around typing someVar specifically which is what the OP was after. Like not having to figure out a db column type.