473,769 Members | 2,085 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamically call a generic?

Ok, lets say I have a generic method:

public T Testing<T>() : where T:class
{
T myT = getStuff() as T;
// Do something with myT
return myT;
}

How do I call it dynamically? The following code does not work, but is
there any way to do it? My understnding of C# generics tells me that I
can... It is not compile-time like C++... I just don't know how.

public object Helper(Type t)
{
return Testing<t>();
}

Help is appreciated :)

Aug 9 '06 #1
2 1752

"Bilz" <Br**********@g mail.comwrote in message
news:11******** **************@ m79g2000cwm.goo glegroups.com.. .
Ok, lets say I have a generic method:

public T Testing<T>() : where T:class
{
T myT = getStuff() as T;
// Do something with myT
return myT;
}

How do I call it dynamically? The following code does not work, but is
there any way to do it? My understnding of C# generics tells me that I
can... It is not compile-time like C++... I just don't know how.

public object Helper(Type t)
{
return Testing<t>();
}

Help is appreciated :)
Reflection is your friend.

using System;
using System.Collecti ons.Generic;
using System.Reflecti on;
namespace csTest
{
class Program
{
public static object Helper(Type t)
{
MethodInfo mi = typeof(Program) .GetMethod("Tes ting");
return mi.MakeGenericM ethod(t).Invoke (null, null);
}

public static T Testing<T>() where T : class, new()
{
T myT = new T();
// Do something with myT
return myT;
}

class Foo
{
public Foo()
{
}

public override string ToString()
{
return "A Foo";
}
}
static void Main(string[] args)
{
Console.WriteLi ne(Helper(typeo f(Foo)));
Console.ReadKey ();
}
}
}
David
Aug 9 '06 #2

David Browne wrote:
"Bilz" <Br**********@g mail.comwrote in message
news:11******** **************@ m79g2000cwm.goo glegroups.com.. .
Ok, lets say I have a generic method:

public T Testing<T>() : where T:class
{
T myT = getStuff() as T;
// Do something with myT
return myT;
}

How do I call it dynamically? The following code does not work, but is
there any way to do it? My understnding of C# generics tells me that I
can... It is not compile-time like C++... I just don't know how.

public object Helper(Type t)
{
return Testing<t>();
}

Help is appreciated :)

Reflection is your friend.

using System;
using System.Collecti ons.Generic;
using System.Reflecti on;
namespace csTest
{
class Program
{
public static object Helper(Type t)
{
MethodInfo mi = typeof(Program) .GetMethod("Tes ting");
return mi.MakeGenericM ethod(t).Invoke (null, null);
}

public static T Testing<T>() where T : class, new()
{
T myT = new T();
// Do something with myT
return myT;
}

class Foo
{
public Foo()
{
}

public override string ToString()
{
return "A Foo";
}
}
static void Main(string[] args)
{
Console.WriteLi ne(Helper(typeo f(Foo)));
Console.ReadKey ();
}
}
}
David
Thanks! I had thought about reflection, but was hoping there might be
a quicker way.

B

Aug 9 '06 #3

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

Similar topics

5
2474
by: Alex Lyman | last post by:
Does anyone have any code handy (or know what a good direction for me to head in), to call functions, if you have an address of the function, its declspec (for my app, it's limited to _stdcall and thiscall), and what parameters it expects? I know all about the argument ordering on the stack, but I don't really know enough ASM to work with it. Does anyone out there know of a cheap way to do it in more standardized C++? (efficiency doesn't...
1
1748
by: Me, Myself, and I | last post by:
First off, i apologize if my terminology is off... I am currently in a project that is basically a front-end to a database. In coding this, I am taking into account that it has the *potential* to be front-ended on multiple databases as well as rendered in multiple browser types. That being said, is there a pre-constructed class out there that I can call from within my code to systematically "build" my SQL statement and have it take...
1
1842
by: Andy | last post by:
Can anyone tell me if it is possible to dynamically create generic collections? simply put I want to be able to something like this : public object test(SomeBaseClass param1) { if (param1.prop1 == "blah") { //logic to determine the type
4
10462
by: puzzlecracker | last post by:
I have seen these terms used in Gang of 4 but could never thoroughly understand what it meant I perceive that C++ is both, but apparently it is only a latter. Can someone explain it? thx
0
965
by: kjvspam | last post by:
I have a bunch of reports that are defined as metadata in a database. Each report has an ID and a collection of filters (e.g. filter the report where X is between 5 and 8). I need to expose the reports through a web service. I could write a single web method that takes in a report ID and an ArrayList of parameters, and returns the output for the requested report. That would work. But I think the generic method above is too generic. I...
9
7010
by: Allen | last post by:
The arguments of function is variable. Given function address, argument type and data, how to dynamically call the function? The following is pseudo code. int count = 0; int offset = 0; char buffer; count = getcount(buffer, offset); void* pfun = getmethod(buffer, offset);
3
1476
by: kj | last post by:
I've tried a bazillion ways to code dynamically generated methods, to no avail. The following snippet is a very simplified (and artificial) demo of the problem I'm running into, featuring my latest attempt at this. The idea here is to use __getattr__ to trap any attempt to invoke a nonexistent method, have it return a generic handler called _auto which creates the new method dynamically, invokes it, and "installs" it in the class, so...
20
4304
by: Nickolai Leschov | last post by:
Hello all, I am programming an embedded controller that has a 'C' library for using its system functions (I/O, timers, all the specific devices). The supplied library has .LIB and .H files. How can I dynamically load a LIB file and access all its functions? Surely someone has solved similar task? My intention is to use a Forth system for programming the controller,
4
7947
by: alan | last post by:
AFAIK a template parameter must be completely determinable by the compiler at compile time, is this correct? Currently my problem is, I have a class which contains a std::vector. The size of this vector can be determined at the time an object of the class is constructed, and is assured not to change over the lifetime of the object. Now this class is part of an intrusive memory pool management scheme, and while it's okay for the...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10049
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
9997
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
9865
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...
1
7413
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
5309
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...
1
3965
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3565
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.