C# Call Functionsby Name

C# Function

Calling functions in C#.NET is one of the most basic aspects of programming .NET applications. C# developers extensively use C# functions to structure code and efficiently accomplish tasks.

However what many developers do not know is that there is more than one way to call a function.

Calling Functions

The simplest and most common way to call a function in C# is to do so directly. Some functions return a value, some do not (or "return" void). Similarly some functions take parameters while others do not. Some example C# function calls:

showMessage();
int result = multiply(3, 4);

That is the most effective way to call a C# function in most cases. However more complex applications and more advanced implementations could require a different way to access functions.

Reflection

The System.Reflection namespace holds a variety of classes and functions that takes C# programming to another level. Similarly to accessing properties by name, a C# function can be invoked from its string name.

For example, let's take showMessage from our example above. The function does not return a value and does not take parameters. To call it with .NET reflection it would be done something like so:

A word of warning. If you get a null-object exception that means the method was not found. The method has to be public for it to be able to be invoked through reflection. Also obfuscating the C# application can potentially cause the name of the method to change, which will cause the code to fail. These are just things to keep in mind.

Now let's try to invoke the multiply function from the example above, which takes parameters and returns a value. The code is not all that different: