hadi khodabandeh
hadi khodabandeh

Reputation: 615

Derive method return type from parameter type

I want to know if it's possible to create a method like this:

public var test (var value)
{
    // ...
    return value;
}  

Meaning, if value is a bool, I want to return a bool, if value is a string, I want to return a string, etc.

Upvotes: 1

Views: 53

Answers (3)

Tobias Tengler
Tobias Tengler

Reputation: 7454

If your return type is supposed to be the same as the type of your value parameter, you could create a method with a generic parameter:

public T Test<T>(T value)
{
    return value;
}

Learn more about generics here.

You mentioned that you could also do this using the dynamic keyword, but I would advise against the use of dynamic for a scenario like this. In some special cases dynamic should be used over generics, but it mainly becomes relevant when you're dealing with COM interop.

Upvotes: 1

hadi khodabandeh
hadi khodabandeh

Reputation: 615

I found a way:

public dynamic GetAnything(dynamic val)
{
    return val;
}

Upvotes: 0

Steve
Steve

Reputation: 216302

According to your final statement, you want to return the same type that you receive in input, so, you can do it with a Generic function

public T test<T>(T input)
{
    return input;
}

void Main()
{
    Console.WriteLine(test(true));
    Console.WriteLine(test(1));
    Console.WriteLine(test("Steve"));
}

More info on Generics

Upvotes: 1

Related Questions