Creating a method with generic param

I am trying to create a generic method in a static class like below to which I will pass paramData at run time.

 public static void InsertBulk<T>(string procedure, IDictionary<T,T> paramData)

    {
        //Body
    }

This is valid but as soon as i remove <T> following method name like below, it start showing type error. Why is it behaving so.

public static void InsertBulk(string procedure, IDictionary<T,T> paramData)
        {

       }

IDictionary<int,string> myparams= new IDictionary<int,string>();

As far as my understanding I can call this method using classname.InsertBulk("MyProc",myparams); so, why is it asking for after method name. What is its use.

Jon Skeet
people
quotationmark

There are two separate things to understand here:

  • How you declare a generic method
  • How you call a generic method

You need to include the <T> in the method declaration to make it a generic method. Without that, the compiler doesn't know what T is... it expects it to be the name of a regular type.

Now when you call a generic method, you can specify type arguments like this:

InsertBulk<int>("MyProc", myParams);

Here there's just one type argument: int. (This won't compile for reasons described below, but it's an example of specifying a type argument.)

... or you can let the compiler try to infer the type arguments based on the arguments to the method - in this case, it will look at myParams and work out what the type argument has to be to make the call compile. The details of type inference are very complicated, but they're designed so that where reasonable, you can get away without specifying type arguments.

In your case, as myParams is an IDictionary<int, string> it can't compile anyway, as there's no T for which an IDictionary<int, string> is an IDictionary<T, T>. You could potentially make your method have two type parameters instead:

public static void InsertBulk<TKey, TValue>(
    string procedure, IDictionary<TKey, TValue> paramData)

That that point you can call InsertBulk("MyProc", myParams) and the compiler will infer type arguments of int and string.

people

See more on this question at Stackoverflow