Adrian
Adrian

Reputation: 836

Use variable like type / Generic method

I am trying to refactor below two methods

method 1

public void DoSomething(Bus a, string str)
{
   var temp = new List<Bus>();
   ...
}

method 2

public void DoSomething(Car a, string str)
{
   var temp = new List<Car>();
   ...
}

Below doesn't work, and gives 'a is a variable, but used like a type' error. In addition to that, I can't even imagine how to call this method / what to put in the first parameter.

public void DoSomething<T>(T a, string str)
{
   var temp = new List<a>();
   ...
}

DoSomething<Bus>(Bus, "str");
DoSomething<Car>(Car, "str");
  1. Other posts suggest to use MakeGenericMethod. Is this the only way? Use variable as Type
  2. If I want those methods to return List<T> (Car / Bus) instead of void, how can I use #1 solution with Generics?

Update As I left in the comments -> @ChetanRanpariya, How to call this method, then? DoSomething(?, ?);

Upvotes: 0

Views: 136

Answers (2)

TheGeneral
TheGeneral

Reputation: 81503

You used a (the instance) instead of the actual type T

public void DoSomething<T>(T a, string str)
{
   var temp = new List<T>(); // you need to use T here, it's the actual type
}

...

DoSomething<Bus>(myBus, "str");
DoSomething<Car>(myCar, "str");

Additional Resources

Generics (C# Programming Guide)

Update

41686d6564 made an interesting point

It's hard to tell if you are actually trying to pass the type into the methods parameter:

DoSomething<Bus>(whatYouPassInHereWouldNeedToBeAnInstanceNotAtype,"str");`

If you don't need to use the instance, there is no need to pass it in. Just use the generic parameter

public void DoSomething<T>(string str)

...

DoSomething<Bus>("str");

Upvotes: 4

sunriax
sunriax

Reputation: 821

It seems that you either have a typo or the list is not defined correctly

public void DoSomething<T>(T a, string str)
{
   // Incorrect
   var temp = new List<a>();

   // Correct
   var temp = new List<T>();

   // ...
}

DoSomething<Bus>(Bus, "str");
DoSomething<Car>(Car, "str");

Maybe this helps...

Upvotes: 0

Related Questions