BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News C# 8: Type Inference for the New Keyword

C# 8: Type Inference for the New Keyword

This item in japanese

Bookmarks

In many situations, there is only one possible type allowed in a given place. And yet C# still requires you to explicitly list the type. If the Target-typed `new` expression proposal is adopted, such boilerplate code will no longer be necessary.

Superficially, this feature looks like the reverse of the var keyword. But instead of inferring the variables type from an expression, it infers the expression’s type from a variable. Here is an example from the proposal using the current and proposed syntax.

Dictionary<string, List<int>> field = new Dictionary<string, List<int>>();
Dictionary<string, List<int>> field = new();

As you can see, it simply removes the need to specify the type when it can be inferred from the context. With local variables this isn’t too interesting, but where it can come in handy is short-lived arguments.

XmlReader.Create(reader, new XmlReaderSettings() { IgnoreWhitespace = true });
XmlReader.Create(reader, new() { IgnoreWhitespace = true });

In the above code, the XmlReaderSettings class isn’t very interesting. It is merely a holder for options values to be passed to the XmlReader. One could even argue the type name XmlReaderSettings distracts from the important information.

Another place where this feature is useful is fields and properties where the var keyword is not an option. For example,

private readonly static object s_syncObj = new();

According to the proposal, there are four exceptions to its use.

  • Enum types: not all enum types contain the constant zero, so it should be desirable to use the explicit enum member.
  • Interface types: this is a niche feature and it should be preferable to explicitly mention the type.
  • Array types: arrays need a special syntax to provide the length.
  • Struct default constructor: this rules out all primitive types and most value types. If you wanted to use the default value of such types you could write default instead.

Status

Currently type inference for the new keyword is listed on the C# 8 roadmap with the status “Prototype”. The feature test plan is available on GitHub.

Rate this Article

Adoption
Style

BT