1

I want to create a method that takes a dynamic input parameter and returns a dynamic that I can use to fill a typed variable. Is there a way to get the type of the variable being assigned to from within the method?

double dbl = AssignValue("Hello");

public dynamic AssignValue(dynamic ValueToAssign)
{
    Type type = //do something to get the type of variable "dbl"

    switch (type.Name)
    {
        case "Double":
             return double.Parse(AssignValue);
             break;
        case "Decimal":
             return decimal.Parse(AssignValue);
             break;
        //...
    }    
}

I tried to locate something in the StackFrame but, with no luck.

Any terminology to research further would be very much appreciated as well.

beeker
  • 780
  • 4
  • 17

1 Answers1

1

Is there a way to get the type of the variable being assigned to from within the method?

No. There is no way for a method to retrieve any information about the variable that its result will be assigned to.

However, you could use generics to tell the method the type of object you want it to return:

double dbl = AssignValue<double>("Hello");

public T AssignValue<T>(object valueToAssign)
{
    Type type = typeof(T);
    switch(type.Name)
    {
        //...
    }
}
BJ Myers
  • 6,617
  • 6
  • 34
  • 50
  • Ok, I am looking into these now. I guess I was assuming it *might* be possible because you are able to do similar things like, use StackFrame to get the name of the calling method, like this: http://stackoverflow.com/questions/3095696/how-do-i-get-the-calling-method-name-and-type-using-reflection – beeker Jan 28 '16 at 04:40
  • Ok, telling me that it's not possible is as good an answer as any so, I'll use this option you provided instead. Thanks very much! – beeker Jan 28 '16 at 04:51