Reputation: 836
I am trying to refactor below two methods
public void DoSomething(Bus a, string str)
{
var temp = new List<Bus>();
...
}
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");
MakeGenericMethod
. Is this the only way? Use variable as TypeList<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
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");
Generics (C# Programming Guide)
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
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