Reputation: 14736
I have an interface like this:
public interface IStuff
{
bool DoSomethingWith<T>(T type);
}
And this class that implements it
public class MyStuff<T> : IStuff
{
readonly ISomeClass<T> _cls;
public MyStuff(ISystemCache cache)
{
_cls= cache.Get<T>();
}
public bool DoSomethingWith<T>(T type)
{
//dummy code here that returns a bool
Type theType = typeof(T);
return theType == typeof(T);
}
}
Now the reason the type T
is on the Class MyStuff is because I want it to be available in the constructor of the class that implements IStuff. MyStuff will be passed in some type to work with in its DoSomethingWith method.
Now DoSomethingWith also has a type T
because I want it to be available on all the classes that implement IStuff.
IStuff
will be having at most one or two implementations; at the moment just one, but once I finalize the design there will be another one added. But there will about 5-6 different implementations of ISomeClass
sent in to the MyStuff
class. I don't want to repeat MyStuff
for each implementation of ISomeClass
. Later on MyStuff_V2
will do something else will the implementations of ISomeClass
that will be sent in.
How do I go about designing this so that I don't get that compiler warning "The Type parameter T has the same name as the Type parameter from the outer class MyStuff<T>
?
EDIT This is a very contrived example that may not be perfect, but the objective is to be able to create a generic type on the interface methods that is also available to the constructor of the classes that implement that interface.
Upvotes: 3
Views: 610
Reputation: 49988
Do you want the two types to be different? Just change the type:
public bool DoSomethingWith<T2>(T2 type)
{
//dummy code here that returns a bool
Type theType = typeof(T2);
return theType == typeof(T);
}
Otherwise you'll have to do what @Marcin suggests.
A more complete example:
void Main()
{
IStuff s = new MyStuff<int>();
Console.WriteLine(s.DoSomethingWith(2.34)); // compare will be false (double != int)
Console.WriteLine(s.DoSomethingWith(5)); // compare will be true (int == int)
}
// Define other methods and classes here
public interface IStuff
{
bool DoSomethingWith<T2>(T2 type);
}
public class MyStuff<T> : IStuff
{
public MyStuff()
{
// Do whatever with type T
}
public bool DoSomethingWith<T2>(T2 type)
{
// dummy code here that returns a bool
Type theType = typeof(T2);
return theType == typeof(T);
}
}
Upvotes: 1
Reputation: 125630
You'd have to make IStuff
generic:
public interface IStuff<T>
{
bool DoSomethingWith(T type);
}
change MyStuff<T>
to implement IStuff<T>
:
public class MyStuff<T> : IStuff<T>
and with that you can just remove generic parameter from DoSomething
implementation:
public bool DoSomethingWith(T type)
{
//dummy code here that returns a bool
Type theType = typeof(T);
return theType == typeof(T);
}
Upvotes: 1