Reputation: 621
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!
Upvotes: 3
Views: 1168
Reputation: 37000
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.
Upvotes: 1
Reputation: 136094
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
Upvotes: 1