xenonn
asked on
Passing in any Types for a generic parameter of a function?
I have a method in C# that needs to take in an object that has generic type. The method looks like this:
The type T can be any type. This means the method Attach should be able to take in a ModelObject<string>, ModelObject<bool> or any other types for the generic, like:
Because the type T is only used within the method Attach and no where else in the class, I don't wish to put the generic type at the class declaration. Moreover, declaring the type as a class generic will not allow me to have different types of T as the parameter for the method Attach.
What other workarounds can I use to be able to pass any types of T as the ModelObject<T> to the method Attach without having to define the generics at the class declaration?
public class MyTestclass {
public void Attach(ModelObject<T> obj)
{
//...
}
}
The type T can be any type. This means the method Attach should be able to take in a ModelObject<string>, ModelObject<bool> or any other types for the generic, like:
var cls = new MyTestClass();
cls.Attach(new ModelObject<string>());
cls.Attach(new ModelObject<bool>());
Because the type T is only used within the method Attach and no where else in the class, I don't wish to put the generic type at the class declaration. Moreover, declaring the type as a class generic will not allow me to have different types of T as the parameter for the method Attach.
What other workarounds can I use to be able to pass any types of T as the ModelObject<T> to the method Attach without having to define the generics at the class declaration?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
change to:
public void Attach<T>(ModelObject<T> obj)
public void Attach<T>(ModelObject<T> obj)
ASKER