Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Return Type of a Method in C#

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.

like image 912
sanchop22 Avatar asked May 08 '12 13:05

sanchop22


People also ask

What is return variable in C?

A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.

What is the return type of the main method in C?

Master C and Embedded C Programming- Learn as you go The normal exit of program is represented by zero return value. If the code has errors, fault etc., it will be terminated by non-zero value. In C++ language, the main() function can be left without return value. By default, it will return zero.

What is return type in C with example?

Not using return statement in void return type function: When a function does not return anything, the void return type is used. So if there is a void return type in the function definition, then there will be no return statement inside that function (generally). Example: C.

How many return types are there in C?

Similarly, a function can return something, otherwise does not return anything. So we can categorize them into four types.


1 Answers

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.

like image 55
Jon Skeet Avatar answered Sep 30 '22 19:09

Jon Skeet