Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Overload return type - recommended approach

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?

like image 345
richard Avatar asked May 23 '13 19:05

richard


2 Answers

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?
like image 74
Jon Skeet Avatar answered Sep 21 '22 12:09

Jon Skeet


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.

like image 29
Reed Copsey Avatar answered Sep 20 '22 12:09

Reed Copsey