473,695 Members | 2,688 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Invoking generic method with type constraint at runtime


I need to invoke a generic method determined at runtime. The method has two
arguments, a string and a generic type that is constrained to a struct:

public void Add<T>(string key, T value) where T : struct

The method is an instance member located on a class called
CmsPropertyMana ger. I also have a number of other "Add" methods with
different overloads.

Usually, I find it quite easy to go by reflecting the type and bind to the
method, but this time it's been really hard to determine the correct binding
parameters. When I inspect the method info, I can see that the generic
argument is having a base type of System.ValueTyp e. However, using this as
the binding signature doesn't yield any results.

// Acquire the method info (this is the part that I'm having trouble with)
MethodInfo methodInfo = typeof(CmsPrope rtyManager).Get Method("Add", new
Type[] { typeof(string), typeof(System.V alueType) });

// Acquire the generic method info
MethodInfo genericInfo = methodInfo.Make GenericMethod(t ype.Type);

// Invoke with a struct (represented by o)
genericInfo.Inv oke(null, new object[] { this.uiKeyName. Value, o });

Please note that once I have the method / generic method info everything is
fine and dandy; that is, if I hardcode the methodinfo reference to the right
index in the reflected type (CmsPropertyMan ager) the rest of the reflection
part works perfectly).

Thanks in advance.

With regards
Anders Borum / SphereWorks
Microsoft Certified Professional (.NET MCP)

Oct 1 '08 #1
3 2259
There is no single GetMethod overload that does what you want; you
need to do it manually:

static MethodInfo FindAddMethod()
foreach(MethodI nfo method in typeof(CmsPrope rtyManager)
.GetMethods(Bin dingFlags.Publi c | BindingFlags.In stance))
if (method.Name == "Add" &&
method.IsGeneri cMethodDefiniti on)
Type[] typeArgs = method.GetGener icArguments();
ParameterInfo[] args = method.GetParam eters();
if (typeArgs.Lengt h == 1 && args.Length == 2
&& args[0].ParameterType == typeof(string)
&& args[1].ParameterType == typeArgs[0])
return method;
return null;

[C# MVP]
Oct 2 '08 #2
Hi Marc,

I found a few examples like yours on the net and was curious if there's
really no other way. Then again, I guess it doesn't matter if I am the one
doing the looping instead of the reflection infrastructure. In any case,
thanks a lot for the feedback - I'm sure I can take it from here :)

With regards
Anders Borum / SphereWorks

Oct 2 '08 #3
If you have LINQ (.NET 3.5/C# 3.0) then you can get rid of the looping
etc - but I'll let you make your own decision as to whether it is any

MethodInfo add = (
from method in typeof(CmsPrope rtyManager)
.GetMethods(Bin dingFlags.Publi c | BindingFlags.In stance)
where method.Name == "Add" && method.IsGeneri cMethod
let typeArgs = method.GetGener icArguments()
where typeArgs.Length == 1
let args = method.GetParam eters()
where args.Length == 2
&& args[0].ParameterType == typeof(string)
&& args[1].ParameterType == typeArgs[0]
select method).Single( );

Oct 2 '08 #4

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

Similar topics

by: Andreas Huber | last post by:
What follows is a discussion of my experience with .NET generics & the ..NET framework (as implemented in the Visual Studio 2005 Beta 1), which leads to questions as to why certain things are the way they are. ***** Summary & Questions ***** In a nutshell, the current .NET generics & .NET framework make it sometimes difficult or even impossible to write truly generic code. For example, it seems to be impossible to write a truly generic
by: Robert Zurer | last post by:
This method works but FxCop rightly complains "Generic methods should provide type parameter" http://www.gotdotnet.com/team/fxcop/docs/rules.aspx?version=1.32 &url=/Design/GenericMethodsShouldProvideTypeParameter.html public sealed class ReflectionAgent { public static T GetCustomAttribute<T>(MemberInfo memberInfo)
by: Jethro Guo | last post by:
C++ template use constraint by signature,It's very flexible to programmer but complex for complier, and at most time programmer can not get clear error message from complier if error occur. C# generic use constraint by type,complier is relaxed, but it is very limited to programmer.Is there a way to get merits of both? Maybe the following way can achieve this purpose : //First add a keyword "constrant" to modify class or struct just...
by: Lorraine | last post by:
Hi all, I have test application written in C# from which I am trying to dynamically invoke a DLL. I have two dll's the only difference being one is written in C# and the other in VB.NET. The test application is able to sucessfully invoke the dll written in C#. However when attempting to invoke the VB.NET version of the dll the following error message occurs: Unhandled Exception: System.ArgumentNullException: Value cannot be null....
by: Brian Richards | last post by:
I'm trying to write a generic function (List<TPanelType> GetGenericPanels<TPanelType, TObjectType>()) that returns all UserControls that derive from T and and implement an interface IGenericPropertyPanel<V> such that U implements or derives from V. The idea being that I can discover (via reflection) all the controls that display or allow editing of an object properties, it's base classes and interfaces. Then I can put them in some kind of...
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 :...
by: Suds | last post by:
Hi, I'm having an issue with invoking a Generic method that takes Generic Arguments. My method signature is public void GenericMethodWithGenericArguments<E, V>(List<EtheFirstList, List<VtheSecondList); I pass the name of the method, the arguments for the "GenericMethodWithGenericArguments" to another method, which is supposed to invoke this method using the Invoke method in the MethodInfo class. My process of invocation is as follows
by: Steve Richter | last post by:
in a generic class, can I code the class so that I can call a static method of the generic class T? In the ConvertFrom method of the generic TypeConvert class I want to write, I have a call to the static Parse method of the conversion class. if (InValue is string) return T.Parse((string)InValue); else return base.ConvertFrom(context, culture, InValue);
by: =?Utf-8?B?TW9ydGVuIFdlbm5ldmlrIFtDIyBNVlBd?= | last post by:
"Anders Borum" wrote: Hi Anders, I'm afraid the GetMethod() does not currently support filtering on generic parameters so you will have to loop through the existing methods using GetMethods() MethodInfo methods = t.GetMethods();
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,...
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...
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...
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,...
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...
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...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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
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.