473,725 Members | 2,243 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Late binding: call a method by string name

Is there a way to execute a method if all we know is its name as a string?

Let's say we have the following class. What is the code for the Execute
method? I need a solution that works with the Compact Framework.

public class Executor {

public static Execute(string p_whichFunction ) {

// call the function named p_whichFunction
}

private static _function1() {
// processing code
}

private static _function2() {
// processing code
}

private static _function3() {
// processing code
}
}

Thanks in advance for all suggestions.

Joel Finkel
fi****@sd-il.com
Dec 8 '05 #1
9 2773
Joel,

Assuming they all have the same signature, you can get the MethodInfo
instance for the method using the string name, and the type of the class
Executor (through reflection). Basically, get the type for Executor, and
call the GetMethod instance, passing the string, as well as the flags for
binding which represent private and static as well.

Then, you can call Invoke on the MethodInfo, passing null for the
instance. Something like this:

public static Execute(string p_whichFunction /* this is a bad parameter
name, by the way */)
{
// Get the type.
Type t = typeof(Executor );

// Get the method info.
MethodInfo methodInfo = t.GetMethod(p_w hichFunction,
BindingFlags.No nPublic | BindingFlags.Pu blic | BindingFlags.St atic);

// Invoke the method.
methodInfo.Invo ke(null, null);
}

I included the public flag in case you change the accessibility of the
methods later.

Also, the p_whichFunction parameter should not be prefixed with "p_".
The public naming guidelines state that you should not use type/locality
identifiers before things that are publically exposed. Also, a more apt
name for the parameter would be "method".

Additionally, I fail to see the use of this method, since the two lines
I gave you are really not that much of a savings at all in terms of coding,
and the reflection APIs are not so obscure.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Joel Finkel" <Jo********@dis cussions.micros oft.com> wrote in message
news:3F******** *************** ***********@mic rosoft.com...
Is there a way to execute a method if all we know is its name as a string?

Let's say we have the following class. What is the code for the Execute
method? I need a solution that works with the Compact Framework.

public class Executor {

public static Execute(string p_whichFunction ) {

// call the function named p_whichFunction
}

private static _function1() {
// processing code
}

private static _function2() {
// processing code
}

private static _function3() {
// processing code
}
}

Thanks in advance for all suggestions.

Joel Finkel
fi****@sd-il.com

Dec 8 '05 #2
Maybe it's just a bad example of what you want to do, but since the methods
are all known to the Executor class, there is no need for reflection in your
example; ignoring the grungy method / parameter names (another poster
already picked that up), what's wrong with:

public static void Execute(string p_whichFunction ) {
switch(p_whichF unction) {
case "_function1 ": _function1(); break;
case "_function2 ": _function2(); break;
case "_function3 ": _function3(); break;
default: throw new ArgumentExcepti on();
}
}

This also avoids the caller accessing code that they shouldn't be (unless
they do their own reflection).

Marc

"Joel Finkel" <Jo********@dis cussions.micros oft.com> wrote in message
news:3F******** *************** ***********@mic rosoft.com...
Is there a way to execute a method if all we know is its name as a string?

Let's say we have the following class. What is the code for the Execute
method? I need a solution that works with the Compact Framework.

public class Executor {

public static Execute(string p_whichFunction ) {

// call the function named p_whichFunction
}

private static _function1() {
// processing code
}

private static _function2() {
// processing code
}

private static _function3() {
// processing code
}
}

Thanks in advance for all suggestions.

Joel Finkel
fi****@sd-il.com

Dec 8 '05 #3
(you could even make the parameter an enum for a caller-friendly list of the
available options, rather than having to remember a random string)

"Marc Gravell" <mg******@rm.co m> wrote in message
news:eR******** ******@TK2MSFTN GP10.phx.gbl...
Maybe it's just a bad example of what you want to do, but since the
methods are all known to the Executor class, there is no need for
reflection in your example; ignoring the grungy method / parameter names
(another poster already picked that up), what's wrong with:

public static void Execute(string p_whichFunction ) {
switch(p_whichF unction) {
case "_function1 ": _function1(); break;
case "_function2 ": _function2(); break;
case "_function3 ": _function3(); break;
default: throw new ArgumentExcepti on();
}
}

This also avoids the caller accessing code that they shouldn't be (unless
they do their own reflection).

Marc

"Joel Finkel" <Jo********@dis cussions.micros oft.com> wrote in message
news:3F******** *************** ***********@mic rosoft.com...
Is there a way to execute a method if all we know is its name as a
string?

Let's say we have the following class. What is the code for the Execute
method? I need a solution that works with the Compact Framework.

public class Executor {

public static Execute(string p_whichFunction ) {

// call the function named p_whichFunction
}

private static _function1() {
// processing code
}

private static _function2() {
// processing code
}

private static _function3() {
// processing code
}
}

Thanks in advance for all suggestions.

Joel Finkel
fi****@sd-il.com


Dec 8 '05 #4
Marc,

What you have provided is exactly what I am now doing. I want to change it
to eliminate a source of coding errors, that is, the switch statement.

The methods are called in a sequence that is not known until runtime. The
sequence is stored in a database. I need to ensure that the strings are
identical in both the database and the code. If I can eliminate the swich
statement, I eliminate a source of potential errors. I need only ensure that
the names stored in the database match the method names; and I can do this in
the UI that is used to maintain the database if I implement the solution
provided by Nicholas.

"Marc Gravell" wrote:
Maybe it's just a bad example of what you want to do, but since the methods
are all known to the Executor class, there is no need for reflection in your
example; ignoring the grungy method / parameter names (another poster
already picked that up), what's wrong with:

public static void Execute(string p_whichFunction ) {
switch(p_whichF unction) {
case "_function1 ": _function1(); break;
case "_function2 ": _function2(); break;
case "_function3 ": _function3(); break;
default: throw new ArgumentExcepti on();
}
}

This also avoids the caller accessing code that they shouldn't be (unless
they do their own reflection).

Marc

"Joel Finkel" <Jo********@dis cussions.micros oft.com> wrote in message
news:3F******** *************** ***********@mic rosoft.com...
Is there a way to execute a method if all we know is its name as a string?

Let's say we have the following class. What is the code for the Execute
method? I need a solution that works with the Compact Framework.

public class Executor {

public static Execute(string p_whichFunction ) {

// call the function named p_whichFunction
}

private static _function1() {
// processing code
}

private static _function2() {
// processing code
}

private static _function3() {
// processing code
}
}

Thanks in advance for all suggestions.

Joel Finkel
fi****@sd-il.com


Dec 8 '05 #5
Nicholas,

Thank you. This is exactly what I need. Please see my response to Marc,
which explains my desire to do this. I did not want to include this in my
original post so as to keep it as simple and generic as possible.

/Joel Finkel

"Nicholas Paldino [.NET/C# MVP]" wrote:
Joel,

Assuming they all have the same signature, you can get the MethodInfo
instance for the method using the string name, and the type of the class
Executor (through reflection). Basically, get the type for Executor, and
call the GetMethod instance, passing the string, as well as the flags for
binding which represent private and static as well.

Then, you can call Invoke on the MethodInfo, passing null for the
instance. Something like this:

public static Execute(string p_whichFunction /* this is a bad parameter
name, by the way */)
{
// Get the type.
Type t = typeof(Executor );

// Get the method info.
MethodInfo methodInfo = t.GetMethod(p_w hichFunction,
BindingFlags.No nPublic | BindingFlags.Pu blic | BindingFlags.St atic);

// Invoke the method.
methodInfo.Invo ke(null, null);
}

I included the public flag in case you change the accessibility of the
methods later.

Also, the p_whichFunction parameter should not be prefixed with "p_".
The public naming guidelines state that you should not use type/locality
identifiers before things that are publically exposed. Also, a more apt
name for the parameter would be "method".

Additionally, I fail to see the use of this method, since the two lines
I gave you are really not that much of a savings at all in terms of coding,
and the reflection APIs are not so obscure.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Joel Finkel" <Jo********@dis cussions.micros oft.com> wrote in message
news:3F******** *************** ***********@mic rosoft.com...
Is there a way to execute a method if all we know is its name as a string?

Let's say we have the following class. What is the code for the Execute
method? I need a solution that works with the Compact Framework.

public class Executor {

public static Execute(string p_whichFunction ) {

// call the function named p_whichFunction
}

private static _function1() {
// processing code
}

private static _function2() {
// processing code
}

private static _function3() {
// processing code
}
}

Thanks in advance for all suggestions.

Joel Finkel
fi****@sd-il.com


Dec 8 '05 #6
> Also, the p_whichFunction parameter should not be prefixed with "p_".
The public naming guidelines state that you should not use type/locality
identifiers before things that are publically exposed. Also, a more apt
name for the parameter would be "method".


Nicholas,

I have been using "p_" to preface parameter names for over 20 years. This
allows me to easily identify parameter variables within the function (okay,
"method").

Actually, when I worked for DEC, I used a modified Hungarian notation for
parameter variables, which allowed me to also easily identify the variable's
type.

In my opinion, the most important thing is to adopt a naming methodology and
stick with it throughout the project.

Thanks again, and regards,
Joel Finkel

Dec 8 '05 #7
Joel Finkel <Jo********@dis cussions.micros oft.com> wrote:
Also, the p_whichFunction parameter should not be prefixed with "p_".
The public naming guidelines state that you should not use type/locality
identifiers before things that are publically exposed. Also, a more apt
name for the parameter would be "method".


Nicholas,

I have been using "p_" to preface parameter names for over 20 years. This
allows me to easily identify parameter variables within the function (okay,
"method").

Actually, when I worked for DEC, I used a modified Hungarian notation for
parameter variables, which allowed me to also easily identify the variable's
type.

In my opinion, the most important thing is to adopt a naming methodology and
stick with it throughout the project.


It's certainly important to adopt one - but I think it's more important
to be consistent with the platform you're working on that with what
you've done on other platforms.

As it is, you'll be calling some methods in PascalCaseLikeT his, and
some with_the_conven tion_from_C - that's not going to be consistent, is
it?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 8 '05 #8
Jon,

An interesting discussion. Unfortunately, I am under an extreme deadline,
so forgive me for asking that we postpone this until we can discuss it over a
beer.

Regards,
Joel Finkel
It's certainly important to adopt one - but I think it's more important
to be consistent with the platform you're working on that with what
you've done on other platforms.

As it is, you'll be calling some methods in PascalCaseLikeT his, and
some with_the_conven tion_from_C - that's not going to be consistent, is
it?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Dec 8 '05 #9
Joel Finkel <Jo********@dis cussions.micros oft.com> wrote:
An interesting discussion. Unfortunately, I am under an extreme deadline,
so forgive me for asking that we postpone this until we can discuss it over a
beer.


No problem - definitely something to think about for the next project
though, if nothing else :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 8 '05 #10

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

Similar topics

5
1554
by: Daniel Bass | last post by:
..Net is great for modulerising libraries, so that all you need do to access a DLL, is simply call Add Reference and wallah, it's as though the library were written in your project. But what happens when i know that a library must have some method, say void StoreXML ( string XMLmsg ) but want to late bind, as in, only at run time, decide which library i wish to use.
9
387
by: Scott English | last post by:
I am writing an C# program. I call a method on a COM object that returns Object. I don't know the type of the object (and reflection just says its a __ComObject), but I know there is supposed to be Controls property. How can I call the Controls property without knowing the type of the object? In VB.NET, you can just do this if Option Explicit is off by just writing SomeObject.Controls. The VB.NET runtime will handle the late binding...
1
2841
by: Jim | last post by:
Hey all I'm trying to late bind a VB6 object in Component Services using c#. I've been able to do tons of late binding, but now that I have a com+ object that doesn't have a method exposed directly, I'm having tons of trouble. (lots of research, lots of newsgroups, but no success! I have an existing COM+ object "Company.Person" which has several interfaces. To load my object, I have to invoke a method that is "Imported" to "Person", the...
30
2829
by: lgbjr | last post by:
hi All, I've decided to use Options Strict ON in one of my apps and now I'm trying to fix a late binding issue. I have 5 integer arrays: dim IA1(500), IA2(500), IA3(500), IA4(500), IA5(500) as integer The integers in these arrays are actually pointers to different columns of data in a text file.
12
1970
by: Peter Van Wilrijk | last post by:
Hi, In VB6 I have the following code ... Dim frmLink As Form Set frmLink = Forms.Add(stringformname) frmLink.Show 'wait until all data has been loaded Do Until frmLink.Loaded = 21 DoEvent
7
6526
by: Entwickler | last post by:
hello, i have the following problem. i want to write a code that enables the user to call functions from a unmanaged code .dll at running time . so i have to use the late binding . i tried the following code but it doesn't walk : Assembly assemblyInstance = Assembly.LoadFrom(@"C:\myData\UnmanagedCode.dll"); i don't know if somebody can help me . Regards,
6
1893
by: Tim Roberts | last post by:
I've been doing COM a long time, but I've just come across a behavior with late binding that surprises me. VB and VBS are not my normal milieux, so I'm hoping someone can point me to a document that describes this. Here's the setup. We have a COM server, written in Python. For completeness, here is the script: ----- testserver.py ----- import pythoncom
3
16069
ADezii
by: ADezii | last post by:
The process of verifying that an Object exists and that a specified Property or Method is valid is called Binding. There are two times when this verification process can take place: during compile time (Early Binding) or run time (Late Binding). When you declare an Object Variable as a specific Data Type, you are using Early Binding so the verification can take place during compile time. When you declare a Variable of the generic Object Data...
4
2611
by: =?Utf-8?B?Y2xhcmE=?= | last post by:
Hi all, what is the difference between the late binding and reflection? clara -- thank you so much for your help
0
8752
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
9401
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
9257
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
9179
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
9116
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
6702
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
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
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.