简体   繁体   中英

Type inference in C#

I know msdn should probably be the first place to go and it will be after I get the scoop here. What the msdn would not really provide as part of the technical specification is what I am about to ask now:

  1. How exactly the subject is useful in day to day development process?
  2. Does it have a correlation in any shape or form with anonymous types inside clr?
  3. What does it allow for what otherwise could not have been done without it?
  4. Which .net features are dependent upon the subject and could not have exist without as part of the framework?

I am looking to see the compiler logical flow on how to locate that type.

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

  1. The var keyword, which tells the compiler to infer (deduce) the correct type for the variable from what you initialize it with
  2. The ability to leave type parameters out of a generic method call as long as they can be deduced from the parameters
  3. The ability to leave out types from lambda expression arguments, as long as they can be deduced

And to answer your questions:

1) It saves a lot of typing, 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());

versus

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

2) I don't know what you mean by "correlation", but without the var keyword you couldn't have variables refer to anonymous types in a type-safe way (you could always use object or dynamic ), which makes it pretty important when using anonymous types.

3) Nothing as far as I can think of. It's only a convenience feature. Of course its absence would make, for instance, the aforementioned anonymous types less useful, but they're mostly a convenience feature as well.

4) I think 3) answers this as well.

  1. It is syntactic sugar.
  2. Not that I know about.
  3. It greatly simplifies the programmers job.
  4. Linq.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM