Why generic method not required type? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why generic method not required type?

When you doing generic method in C#, you set type T in triangle brackets. SO, when you call that method you don't required set type in triangle brackets? Method: public static void Foo<T>(T arg1, T arg2) { ....return Some; } What I do: Foo<int>(1, 2); What I can do: Foo(1, 2); Question: Why????

28th Jun 2021, 4:27 AM
a SnowFlake
a SnowFlake - avatar
3 Answers
+ 4
This is called type inference, specifically generics. Basically it works because the type of the method is known from its argument, which is also T. The compiler uses the information and instantiate the generic based on it. If you use other known types instead of T in the arguments, this won't work.
28th Jun 2021, 4:46 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 2
It's not. The type is known in compile time. Dynamic typing is: public static void Foo(dynamic arg1, dynamic arg2) {}
28th Jun 2021, 6:30 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 1
CarrieForle, then It is can be called dynamic typing?
28th Jun 2021, 4:47 AM
a SnowFlake
a SnowFlake - avatar