473,804 Members | 3,272 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pass regular type to generic method

Hi all,

I've tried searching for this one, but can't seem to come up with the
proper terms.

I want to know how to pass a type to a generic method. Something like
this:

public void MyMethod(Type objType){
DoSomething<obj Type>();
}

This of course doesn't compile, any ideas what I can do to get it to
work?

DoSomething is just a generic method

public void DoSomething<T>( ){
Console.WriteLi ne("Do Something");
}

thanks,
Henri
Jun 27 '08 #1
7 3209
Answer courtesy of Jon Skeets book (plug)
http://www.amazon.co.uk/C-Depth-What...3645816&sr=8-1

I'm only about 100 (ish) pages into it and it's great!
Pete


namespace ConsoleApplicat ion7
{
class Program
{
static void Main(string[] args)
{
new Tester().DoSome thing(typeof(st ring));
}
}

public class Tester
{
public void DoSomething(Typ e type)
{
MethodInfo methodInfo = GetType().GetMe thod("GenericMe thod");
MethodInfo genericMethodIn fo = methodInfo.Make GenericMethod(n ew Type[]
{ type });
genericMethodIn fo.Invoke(this, null);
}

public void GenericMethod<T >()
{
Console.WriteLi ne(typeof(T).Na me);
}
}

}
Jun 27 '08 #2
Thanks alot Pete.

Although it does seem a wee bit complicated... I guess I don't
understand enough about .NET to comprehend why I would need to use
reflection for (what seems to me to be) such a trivial exercise.

-H.C.

Jun 27 '08 #3
One way is to change the caller method...But I get the feeling that
this is not really something that you want to do:

public void MyMethod<T>(T objType)
{
DoSomething<T>( );
}

On Jun 16, 2:34*pm, Henri.Chinas... @googlemail.com wrote:
Hi all,

I've tried searching for this one, but can't seem to come up with the
proper terms.

I want to know how to pass a type to a generic method. Something like
this:

public void MyMethod(Type objType){
*DoSomething<ob jType>();

}

This of course doesn't compile, any ideas what I can do to get it to
work?

DoSomething is just a generic method

public void DoSomething<T>( ){
*Console.WriteL ine("Do Something");

}

thanks,
Henri
Jun 27 '08 #4
On Jun 16, 2:15*pm, qglyirnyf...@ma ilinator.com wrote:
One way is to change the caller method...But I get the feeling that
this is not really something that you want to do:

public void MyMethod<T>(T * objType)
{
* * DoSomething<T>( );

}

Yep, its a possibility, I know. I'm involved in a bit of a "refactor
for generics" thing, which led to this question. I can pretty much
work around everything, but now I'm just plain curious to see if there
is a trivial (non reflection) way to do what I've described above.

-H.C.
Jun 27 '08 #5
Although it does seem a wee bit complicated... I guess I don't
understand enough about .NET to comprehend why I would need to use
reflection for (what seems to me to be) such a trivial exercise.
Imagine this

DoSomething<T>( )

is a set of overloads like this

DoSomething(str ing)
DoSomething(byt e)

etc

You'd need code like this

void CallDoSomething (object value)
{
if (value is string)
DoSomething( (string)value);
else if (value is byte)
DoSomething( (byte)value);
}

If you wanted to do it dynamically you'd need to use reflection and Invoke.
If you think about generic methods as overloaded methods which do not exist
until runtime maybe that makes it a bit more clear?

--
Pete
=============== =============== ===========
I use Enterprise Core Objects (Domain driven design)
http://www.capableobjects.com/
=============== =============== ===========
Jun 27 '08 #6
He************* @googlemail.com wrote:
Although it does seem a wee bit complicated... I guess I don't
understand enough about .NET to comprehend why I would need to use
reflection for (what seems to me to be) such a trivial exercise.
Because you're trying to fit a round peg into a square hole. The Type class
is for passing type information at runtime; generics are for passing type
information at compile time.

Think of generics as a way to insert a ____ blank in a sentence -- you have
to fill it in *before* you have a complete sentence you can read aloud.
Using a Type parameter, on the other hand, is like saying "Take any type,
let's call it T. Given this T, I want to do the following...". Here you
always use complete sentences, but it's a much more roundabout way of doing
things and fundamentally incompatible with the placeholder approach. The
compiler, of course, demands that your sentences always make sense in every
circumstance, even though they might not be true at runtime.

If you really want this you could implement it the other way around: have
the method that takes a Type do the work and have the generic implementation
delegate to it by means of typeof. That's the "right way around", and the
solution there really is trivial. Of course, the method that uses Type may
be anything but.

--
J.
http://symbolsprose.blogspot.com
Jun 27 '08 #7
Jeroen & Peter

thanks for the explanations, the generics/compile time and Type/
runtime thing is clear now.

-H.C.
Jun 27 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
2162
by: andrea | last post by:
Sorry for the stupid question, I know, but sometimes is necessary starts from the basic. I don't know how to pass the result of a method generated from a DAL class to a BL class returning the results as it is. I mean, for instance, something like this. namespace DAL {
9
12856
by: mps | last post by:
I want to define a class that has a generic parameter that is itself a generic class. For example, if I have a generic IQueue<Tinterface, and class A wants to make use of a generic class that implements IQueue<Tfor all types T (so it can make use of queues of various object types internally). As useful as this is, it doesn't seem possible. The natural (but illegal) notation would be something like class A<QueueClasswhere QueueClass :...
13
3038
by: Francois Appert | last post by:
This post was originally in the C# Corner site, but their server is down. I'd like to see if this group can answer. I program in C++ and am learning C#. The issue is: why should anybody bother in C# with pass-by-reference using the "ref" keyword or "out" for objects in a method parameter list, when, after all, it appears in C# that for all intents and purposes a reference is always being passed, rather than the real object (with, it...
24
55244
by: =?Utf-8?B?U3dhcHB5?= | last post by:
Can anyone suggest me to pass more parameters other than two parameter for events like the following? Event: Onbutton_click(object sender, EventArgs e)" Event handler: button.Click += new EventHandler(Onbutton_click); I want to pass more information related that event. & want to use that
0
9708
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10589
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10340
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10327
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10085
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9161
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7625
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3828
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.