3

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!

6
  • your code works fine, compiler will infer the type Commented Apr 22, 2016 at 10:29
  • @EhsanSajjad Are you sure? Using the generic type 'Rextester.TestClass<T>' requires 1 type arguments Commented Apr 22, 2016 at 10:34
  • Are all the types that might be passed in TestClass<string>.Test("something"); call, known to you? Commented Apr 22, 2016 at 10:38
  • Why are you unable to move the type parameter off of the class and down to the methods? Commented Apr 22, 2016 at 10:43
  • @DavidB there are like 20 methods that uses the following generic type, am I supposed to rewrite it 20 times just to make the method caller no need to specify type? If I change the constraint I need to change 20 times? Commented Apr 25, 2016 at 1:08

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

If I understand you correctly you need this:

public static void Test<T>(T myValue) {. ..}

Then call it like this:

TestClass.Test("DoSomething");

Which will automatically infer the type string for you, you won´t need to specify it within the type-parameter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.