Suppose that I have created a method like this

private void Test<t>(t str)


Now from another method i call it

private void BtnClick()
    string a = "";

    test<Here I Want To assign The Type what ever the type of 'a' is>();

How can I do this ?

No correct solution


Well, if a is a string, you can write:


And if a is an int, you can write:


Pretty obvious. If you don't know the type of a upfront, that means that BtnClick should be generic, the problem would be moved to BtnClick's caller:

private void BtnClick<T>()
    T a = ...;


C# 2.0 and later offers type inference, so you wouldn't have to specify the type:


You simply call the function passing a as the parameter. Type inference will determine what T should be for a.

static void Main()
    string temp = "blah";

private static void Test<T>(T input)

System.String would be printed to the console.

Edit: But, yes, absent type inference, and when you know what your type your variable is, you can always be explicit with the type. Test<string>(temp);

In your example, a is always a string, so you can simply use either Test<string>(a) or Test(a). If, however, you mean that you have a Type instance hanging around somewhere, then you get into the area of reflection. Note that this works, but is slow if used in a tight-loop, so make sure that you understand the performance aspect;

        object arg = ...;
        MethodInfo method = typeof(YourType)
            .GetMethod("Test", BindingFlags.NonPublic | BindingFlags.Instance)
        method.Invoke(this, new object[] { arg });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow