Click here to Skip to main content
15,890,557 members
Articles / Programming Languages / C#

[C#] Validate a Method’s Signature in Run Time

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
30 Apr 2012CPOL 8.5K   3  
A little validation method which will validate a specified method against my signature

Usage of interfaces is always the recommended way to enforce a method’s signature – there are no doubts about that. But there are some occasions where you cannot use an interface to achieve this.

I had a scenario this week, in which I had to use some methods dynamically by reflecting them in run time. Basically, these assemblies are created by others and I just consume the methods in run time. To add more problem, there can be any number of these methods. Even though there is an agreed signature for these methods, often times people can forget those ‘trivial’ details, resulting in run time exceptions, which may not be a nice thing to happen in a production system :-). So I wrote a little validation method which will validate a specified method against my signature. First, define a delegate which matches your requirement.

C#
delegate bool MyDesiredSignature(string param1, stringparam2);

Now, extract the method information from the user’s assembly and attempt to create a delegate which matches my delegate (in this case, it will be MyDesiredSignature).

C#
boolValidateSignature(string methodName, object typeInstance, TypedelegateType)
{
      MethodInfo methodInfo = this.GetType().GetMethod(
        methodName, // The method's name.
        BindingFlags.Instance | BindingFlags.NonPublic);
        // Change this accordingly for static/public methods.

      // Attempt to create a delegate of my delegate type from the method info.
      Delegate methodDelegate = Delegate.CreateDelegate(delegateType, typeInstance, methodInfo, false);

      // If we have 'methodDelegate' as null, then that
      // means the delegate does not match our signature
      // or else we have a match.
      return (methodDelegate != null);
}

Now, we can just call this method for method verification like this:

C#
boolisValidSignature = ValidateSignature("UsersMethodName", this, typeof(MyDesiredSignature));

Happy coding!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --