Why in a generic-type method extension do I not need to spell out a type when calling it?

Asked

Viewed 38 times

2

In the link below is a code snippet consisting of nothing more than a Shuffle method that is used as a Extension Method of Array. Although the method is generic type, I don’t need to pass a guy when I call him. Why does this happen?

I don’t need to do:

var randomDigits = Enumerable.Range(0, 10).ToArray().Shuffle<int>();

Suffice:

var randomDigits = Enumerable.Range(0, 10).ToArray().Shuffle();

Link.

1 answer

2


The question should be

Why in a generic-type method extension I don’t need to spell out a type when calling it?

Because the answer is precisely the inference that the compiler makes. The Enumarable.Range() produces an enumerable type of int. And the ToArray() achieves this (probably unnecessarily), but does not change the type. So Shuffle(), which is generic, can be inferred by the compiler that it is an integer that is manipulating.

In many cases the compiler is prepared to discover the type to be used, as long as it has this information quietly and simply, which is the case. It is no different than what allows you to use var, compiler can identify which type is all that and let you omit the type.

Not everything the compiler can infer, and even some things that seem to give can be ambiguous, at least for the compiler that was not always created to see certain patterns, then you would have to make explicit.

It is better not to have to write when it is easily identifiable.

Then understand that there is as if using the var, but even that is not necessary to write.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.