I have a situation where I just want the return type to be different for a method overload, but you can't do this in C#.
What's the best way to handle this? Is the fact that I need this mean my program structure flawed?
Given the fact that this is impossible in C#, what is the recommended approach?
Typically you simply give the methods different names.
An example of this is IDataReader
with GetInt32
, GetInt64
etc.
To be honest, I believe this usually makes it clearer what you're trying to do anyway - particularly if you're then calling an overloaded method with the result:
Console.WriteLine(reader.GetInt32()); // This is clear
Console.WriteLine(foo.OverloadedGet()); // Which overload of OverloadedGet?
Given the fact that this is impossible in C#, what is the recommended approach?
It depends on why you need this.
The most common approach is to just use a different name. The framework does this in many cases, such as the Convert class.
If you want to support multiple types, you can do this via generic methods:
T SomeMethod<T>()
// Optionally add constraints:"
where T : IFoo
{
The generic method approach is common for repostories, as it's common that there's an "Entity" type of base class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With