Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling method in static generic class without specifying type

Consider the following code, I want to do something like this, this doesn't work but this is what I want

class Program
{
    static void Main(string[] args)
    {
        TestClass.Test("something");
    }
}

public static class TestClass<T>
{
    public static void Test(T something) { }
}


The code below will work but I have like 20 generic methods in the same class and they are repeating their constraints over and over again.

public static class TestClass
{
    public static void Test<T>(T something) { }
}


I don't want to do this because I don't want the people who use my code specifies string as the type, because "something" is already a string

 TestClass<string>.Test("something");


To explain my question in another way round, I want to pull the same generic type and constraints from like 20 methods in the same class, I don't want them to repeat over and over, and I don't want user to specify the type when they use my methods, the parameter they pass in will supply the type.

Thanks!

like image 937
Lee Song Avatar asked Dec 17 '25 16:12

Lee Song


1 Answers

If you specify the generic on the class itself, you need to specify it, as you noted in your question - this would work:

TestClass<string>.Test("something")

If you want the compiler to infer it, you need to put it on the method instead:

public static class TestClass
{
    public static void Test<T>(T something) { }
}

TestClass.Test("something");// T is infered.

Live example: http://rextester.com/VOF10456

like image 137
Jamiec Avatar answered Dec 19 '25 06:12

Jamiec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!