Reputation: 615
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
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
Reputation: 615
I found a way:
public dynamic GetAnything(dynamic val)
{
return val;
}
Upvotes: 0
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"));
}
Upvotes: 1