简体   繁体   中英

What is the purpose of Type Inference in c#

I don't see exactly what is the purpose of type inference, what is the benefit from adding that to the language, is there any special use like the in C++11 auto keyword?

I see it just like an add since I don't know really situation where the resulting type is not necessarily known in advance

(I mean the use of keyword var)

Thank you

Type inference saves an incredible amount of typing when dealing with complex signatures. For instance,

var itemCreator = _interface.GetItemCreator();

is so much more compact and readable than

Func<int, string, double, decimal, 
    Dictionary<int, KeyValuePair<int, string>>, 
    Action<string, string, string>> itemCreator = _interface.GetItemCreator();

This is obviously an incredibly contrived example designed to prove a point...that code gets messy and the type declarations that go with it are also often messy. Type Inference saves us a bit of pain on that front.

In addition, Type Inference gives us the ability to use anonymous methods which are used heavily in LINQ and serialization libraries.

Anonymous methods generate a type at compile time. As a result, there is no way for you to declare the type appropriately ahead of time.

As far as your comparison to the auto operator in C++ 11, at first glance it appears to have the same/similar functionality.

public class Class1
{
    public string Method1() 
    {
        return "string";
    }
}

// Calling code
Class1 cls1 = new Class1();
var result = cls1.Method1(); // result is string type.

Now some time later you decide you needed to return int from your Method1. You can do so without having to worry about the calling code.

Apart from this var is also heavily used in LINQ.

Another use would be to make your code cleaner, for example:

Dictionary<int, string> dictionary = new Dictionary<int, string>();

vs.

var dictionary = new Dictionary<int, string>();

You can see which one is cleaner to read.

Type inference helps with at least three aspects of C# development:

  1. Writing code

    var requires fewer keystrokes, and less time worrying about the exact types returned from methods, etc.

  2. Understanding code

    var produces more concise, readable code than explicitly specifying types.

  3. Maintaining code

    Fewer code changes are needed in fewer places when the types in your application change (and they will).

var has many benefits and few drawbacks. I use it everywhere unless I have a compelling reason not to.

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