Reputation: 479
Is there a way to unbox/cast using variable types like
var varType = typeof(int);
var variable = 5;
return (varType)variable;
Upvotes: 2
Views: 443
Reputation: 7111
You question requires a little more info to answer, so I'm going to add some. Consider that you have a function like
int GetSomeInt () {
var i = (object)5; //at this point, i is a boxed int
return (int)i; //we are unboxing I back into an int and returning it
}
The other thing you could do is:
object GetBoxedInt () {
var i = 5;
return (object)i; //here we are returning boxed int back to the caller
}
What you can't do is return a boxed anything back to a caller as anything other than an object
; as far as I know there's no way to express a type that conceptually might be:
Boxed<T> where T: struct
And,
object
"Oh... You put more words in your question. My answer predates your first line of code: var varType = typeof(int);
I had assumed that varType
was a type name (like object
or int
or MyClass
). However, my answer still mostly holds - with the exception that the answer to your exact question (after editing) is *No*
Upvotes: 1
Reputation: 685
There's an issue in the premise of your question. C# is a statically typed language, and the type of each variable must be known at compile time. There is no getting around this, so you either have to specify the type of your object, or use dynamic
as a type (please don't unless you're doing interop or something similar).
In your example, the type of varType
is Type
. The type of variable
is int
. But what is then the return type of this function if what you proposed existed in C#? Since varType
could hold any type, the return type of this function would only be known at run-time, which is not possible in a statically typed language.
Perhaps if you provided a more concrete example of where you think you need to use something like this, there might be a better way to accomplish that.
Upvotes: 2