+ 1

Generic methods <string> vs <T,U>

I didn't understand the explanation in the lesson If you have a single type parameter you need to explicitly name it ? string x = "Hello"; string y = "World"; Swap<string>(ref x, ref y);//<----- <string> //Now x is "World", y is "Hello" If you have 2 different type of parameters do not need to name the type explicitly. static void Func<T, U>(T x, U y) { Console.WriteLine(x+" "+y); } static void Main(string[] args) { double x = 7.42; string y = "test"; Func(x, y); //<---- I would expect something like Func<string, double>(x,y); } Why is it that if you have a single parameter in a generic method you need to name the type like Swap<string>(ref a, ref b) and if you have more parameters you do not need it like Func(x,y) It does work though https://code.sololearn.com/cwlo7qP7T8rR

25th Aug 2017, 8:39 PM
sneeze
sneeze - avatar
2 odpowiedzi
+ 1
You can even leave the <string> away. When the compiler processes your code, he knows what types your variables have (you initialize the variables with their type declared in the beginning). The <> is optional, but not necessary.
26th Aug 2017, 6:21 AM
StoneSmasher
StoneSmasher - avatar
+ 1
Thank you for your explanation. It works.
26th Aug 2017, 8:04 PM
sneeze
sneeze - avatar