static List<T> GetInitializedList<T>(T value, int count)
{
List<T> list = new List<T>();
for (int i = 0; i < count; i++)
{
list.Add(value);
}
return list;
}
Above displayed generic methods can be called as follows...
EX-1
List<bool> list1 = GetInitializedList(true, 5);
EX-2
List<string> list2 = GetInitializedList<string>("Perls", 3);
I want know about the difference between calling this generic methods using the EX-1 and EX-2
what is the most efficient /standard / best way of calling the genric method.
EX-1 or EX-2
They're equivalent. Basically, if you don't specify the type arguments to the method (i.e. the types in the <>
in the method invocation), the compiler will try to use type inference to work out which type arguments you meant, based on the actual arguments (the expressions in the ()
in the method invocation).
They compile to exactly the same code, when the compiler infers the type arguments you wanted. In some cases you need to specify type arguments if:
The type can't be inferred by the compiler. Example:
GetInitializedList<string>(null, 5);
Here the compiler can't infer the type argument because null
has no type.
The type that the compiler would infer isn't what you want. Example:
List<object> objects = GetInitializedList<object>("foo", 5);
Here the compiler would infer a type argument of string
, which isn't what we want.
See more on this question at Stackoverflow