Variable Return Type of a Method in C#

sanchop22 picture sanchop22 · May 8, 2012 · Viewed 30.3k times · Source

I want to give a parameter to a method and i want my method to return data by looking the parameter. Data can be in type of boolean, string, int or etc. How can i return a variable type from a method? I don't want to return an object type and then cast it to another type. For example:

BlaBla VariableReturnExampleMethod(int a)
{
    if (a == 1)
        return "Demo";
    else if (a == 2)
        return 2;
    else if (a == 3)
        return True;
    else
        return null;
}

The reason why i want that is i have a method that reads a selected column of a row from the database. Types of columns are not same but i have to return every column's information.

Answer

Jon Skeet picture Jon Skeet · May 8, 2012

How can i return a variable type from a method? I don't want to return an object type and then cast it to another type.

Well that's basically what you do have to do. Alternatively, if you're using C# 4 you could make the return type dynamic, which will allow the conversion to be implicit:

dynamic VariableReturnExampleMethod(int a)
{
    // Body as per question
}

...

// Fine...
int x = VariableReturnExampleMethod(2);

// This will throw an exception at execution time
int y = VariableReturnExampleMethod(1);

Fundamentally, you specify types to let the compiler know what to expect. How can that work if the type is only known at execution time? The reason the dynamic version works is that it basically tells the compiler to defer its normal work until execution time - so you lose the normal safety which would let the second example fail at compile time.