Type inference in C #

I know that msdn should probably be the first place, and that will be after I get the scoop here. What msdn did not actually provide as part of the technical specification is what I will ask now:

  • How exactly is the subject useful in the daily development process?
  • Does it correlate in any form or form with anonymous types inside clr?
  • What does it mean that without it could not be done?
  • What .net functions are object-dependent and cannot exist without any part of the structure?

To bring a note to the question, it would be really interesting to know (in pseudo-code) how the compiler can actually determine the type if the method was called using lambdas and type inference

I am looking to see the compiler logic flow on how to find this type.

+3
source share
2 answers

Type inference occurs in many places in C #, at least the following:

  • A keyword varthat tells the compiler to infer (infer) the correct type of a variable from what you initialized with
  • Ability to leave type parameters from a general method call if they can be inferred from parameters
  • Ability to leave types from arguments of lambda expression if they can be deduced

And to answer your questions:

1) This saves a lot of input, especially when using the so-called "LINQ methods". Compare for example

List<string> myList = new List<string>();
// ...
IEnumerable<string> result = myList.Where<string>((string s) => s.Length > 0)
    .Select<string, string>((string s) => s.ToLower());

against

var myList = new List<string>();
// ...
var result = myList.Where(s => s.Length > 0).Select(s => s.ToLower());

2) , "", var , ( object dynamic), .

3) , . . , , , , .

4) , 3) .

+9
  • .
  • , .
  • .
  • Linq.
+2

Source: https://habr.com/ru/post/1789643/


All Articles