Solved

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

Posted on 2013-01-07
3
493 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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
VB.NET 2008 - Windows Protected Your PC 7 41
Help with error in Query 2 31
backup program with robocopy 6 42
.NET Enums [Flags] & Bitwise Design Question 6 19
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.

809 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