Skip to content
Advertisement

How to merge methods with unrelated parameter types into one generic one?

For java/C#

There is my code:

class Room{
  HashSet tables;
  HashSet cups;

  void AddTable(Table table){ tables.Add(table); }
  void AddCup(Cup cup){ cups.Add(cup); }
  Table GetTable(){...}
  Cup GetCup(){...}
  ...
}

Can I merge AddTable and AddCup into one method like Add<T>

like this:

        void Add<T>(T t)
        {
            if (t is Table table) { ... }
            else if (t is Ground ground) { ... }
            ...
        }

        T Get<T>(){
            ...
        }

The problem is that there are too many if else.

Do you have any better suggestions?

Advertisement

Answer

Name the methods the same so that they will be overloads of each other:

  void Add(Table table){ tables.Add(table); }
  void Add(Cup cup){ cups.Add(cup); }

The compiler is smart enough to call the correct method. (And Table and Cup are unrelated classes, so there are no caveats).

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement