C# 8 – Introducing Target-typed new expressions

So far we have talked about how quite a few new features of C# 8. We have talked about how C# 8 fixing interpolated verbatim strings (here), we have talked about the languages new Index Struct and the usage of the Hat operator (here) and we have talked about default interface methods (here). In this article we will talk about another feature that some people might call small and minor, but still very very useful as it can clean up code and remove lots of noise.

Target-typed new expressions

You know how us Software Engineers hate writing too much code? Also when there is too much unneeded code then we hate reading it? We try to simplify things as much as possible.
Long time ago C# introduced the var keyword to help us with that. So in cases like the following

SomeNameSpace.SomeClass instanceName = new SomeNameSpace.SomeClass(argument1, argument2, ....);

it could be simplified to

var instanceName = new SomeNameSpace.SomeClass(argument1, argument2, ....);

In the above case, it is obvious for the reader what the type of instanceName object is, so no need to clearly define it. Newcomers to the language sometimes feel like var is to Javascript’s var, but no. We still have strong typing here and it is simply syntactical sugar. The compiler will replace the var keyword with the proper type.

Well, C# 8 is introducing a new way to perform this by reducing the amount of code you write. Now, what you are trying to instantiate can be omitted if it can be inferred from the usage.
One example of this is when initializing a field inside a class or a struck.

internal class Something 
     private readonly static object s_syncObj = new();
     public Something()
         Console.WriteLine("Ctor called");

So for example, if we have something really large like

private static readonly ConcurrentDictionary _myConcDict = new ConcurrentDictionary();

It can be simplified and cleaned up and we would have the following result

private static readonly ConcurrentDictionary _myConcDict = new ();

We can also omit the type duplication when we want to perform field initialization, but also inside field initialization when we are doing another field initialization and more.
For example:

Dictionary> myDict = new() 
    { "item1", new() { "1", "2", "3" } }

We can also use it method calls etc, where the target type can be inferred.
For example:

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

Another simplification and code noise reduction.

Please follow and like us:
One Comment

    C# 8 is introducing target typed new expression - How to Code .NET

    […] on March 23, 2019by admin submitted by /u/macrian [link] [comments] No comments […]

Leave a Reply