Link to home
Start Free TrialLog in
Avatar of xenonn
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:

public class MyTestclass {
       public void Attach(ModelObject<T> obj)
        {
            //...
        }
}

Open in new window


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>());

Open in new window


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
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of xenonn
xenonn

ASKER

Thank you for the help.
change to:
public void Attach<T>(ModelObject<T> obj)