?
Solved

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

Posted on 2013-01-07
3
Medium Priority
?
497 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 2000 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

New benefit for Premium Members - Upgrade now!

Ready to get started with anonymous questions today? It's easy! Learn more.

Question has a verified solution.

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

Computer science students often experience many of the same frustrations when going through their engineering courses. This article presents seven tips I found useful when completing a bachelors and masters degree in computing which I believe may he…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …
Introduction to Processes

752 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