Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining Generic Methods

Tags:

c#

generics

All, I have a method that is currently used to invoke DLLs of return type bool, this works great. This method is

public static bool InvokeDLL(string strDllName, string strNameSpace, 
                             string strClassName, string strMethodName, 
                             ref object[] parameters, 
                             ref string strInformation, 
                             bool bWarnings = false)
{
    try
    {
        // Check if user has access to requested .dll.
        if (!File.Exists(Path.GetFullPath(strDllName)))
        {
            strInformation = String.Format("Cannot locate file '{0}'!",
                                           Path.GetFullPath(strDllName));
            return false;
        }
        else
        {
            // Execute the method from the requested .dll using reflection.
            Assembly DLL = Assembly.LoadFrom(Path.GetFullPath(strDllName));
            Type classType = DLL.GetType(String.Format("{0}.{1}", 
                                         strNameSpace, strClassName));
            if (classType != null)
            {
                object classInstance = Activator.CreateInstance(classType);
                MethodInfo methodInfo = classType.GetMethod(strMethodName);
                if (methodInfo != null)
                {
                    object result = null;
                    result = methodInfo.Invoke(classInstance, new object[] { parameters });
                    return Convert.ToBoolean(result);
                }
            }

            // Invocation failed fatally.
            strInformation = String.Format("Could not invoke the requested DLL '{0}'! " + 
                                           "Please insure that you have specified the namespace, class name " +
                                           "method and respective parameters correctly!",
                                           Path.GetFullPath(strDllName));
            return false;

        }
    }
    catch (Exception eX)
    {
        strInformation = String.Format("DLL Error: {0}!", eX.Message);
        if (bWarnings)
            Utils.ErrMsg(eX.Message);
        return false;
    }
}

Now, I want to extend this method so that I can retrieve return values from a DLL of any type. I planned to do this using generics but immediately have gone into territory unknown to me. How do I return T when it is unknown at compile time, I have looked at reflection but I am unsure how it would be used in this case. Take the first check in the above code

public static T InvokeDLL<T>(string strDllName, string strNameSpace, 
                             string strClassName, string strMethodName, 
                             ref object[] parameters, ref string strInformation, 
                             bool bWarnings = false)
{
    try
    {
        // Check if user has access to requested .dll.
        if (!File.Exists(Path.GetFullPath(strDllName)))
        {
            strInformation = String.Format("Cannot locate file '{0}'!",
                                           Path.GetFullPath(strDllName));
            return "WHAT/HOW??";
        ...

How can I achieve what I want, or shall I just overload the method?

Thanks very much for your help.

like image 220
MoonKnight Avatar asked Jun 22 '12 14:06

MoonKnight


People also ask

What are generic methods in Java?

What are generic methods in Java? Similar to generic classes you can also define generic methods in Java. These methods use their own type parameters. Just like local variables, the scope of the type parameters of the methods lies within the method.

What is the body of a generic method?

A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char). Following example illustrates how we can print an array of different type using a single Generic method −

How to have two types of parameters in a generic method?

You can have two generic type parameters of the different type as shown below. We can specify the restrictions on the types of parameters using the where clause. A compile-time error is generated when you call your generic method with the wrong types The Value type like int, float, struct etc. must be used as the parameter

What is the difference between function and generic method?

It is exactly like a normal function, however, a generic method has type parameters that are cited by actual type. This allows the generic method to be used in a more general way. The compiler takes care of the type of safety which enables programmers to code easily since they do not have to perform long, individual type castings.


2 Answers

Replace

return false;

by

return default(T);

and

return Convert.ToBoolean(result);

by

return (T)result;
like image 132
Heinzi Avatar answered Sep 28 '22 23:09

Heinzi


When you've not got a real value from the DLL, you obviously have to create a value from somewhere. The only way that works for every possible type T is return default(T) which gives whatever the default value for that type is (i.e. 0 for int, null for any reference type).

If you place type constraints on the type parameter you can get more options, but at the expense of genericity.

like image 44
Matthew Walton Avatar answered Sep 28 '22 22:09

Matthew Walton