Solved

Passing in any Types for a generic parameter of a function?

Posted on 2013-01-07
3
494 Views
Last Modified: 2013-01-07
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?
0
Comment
Question by:xenonn
3 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 38750625
Make the method generic:

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

Open in new window

0
 

Author Closing Comment

by:xenonn
ID: 38750629
Thank you for the help.
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 38750645
change to:
public void Attach<T>(ModelObject<T> obj)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …

679 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question