Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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

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

like image 732
dexter Avatar asked Sep 01 '25 22:09

dexter


1 Answers

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.

like image 162
Matti Virkkunen Avatar answered Sep 03 '25 15:09

Matti Virkkunen