Shorter Construction Syntax

Did you ever notice the redundancy that’s forced by C#’s syntax for invoking and defining constructors?

using System.Collections.Generic;

class Thing
{
  Thing(int x, int y)
    { ... }

  public static void Main()
  {
     Thing a = new Thing(3,2);
     Dictionary<string,double> b
       = new Dictionary<string,double>();
  }
}

It might be nice if C# added a less redundant syntax.

using System.Collections.Generic;

class Thing2
{
  new(int x, int y)
    { ... }

  public static void Main()
  {
     Thing2 a = new(3,2);
     Dictionary<string,double> b = new();
  }
}

The short form is clearer and less cluttered. Adding it to C# would not require changes to the runtime. (In fact, the ILdAsm disassembler displays at least constructor references as .ctor. This short form does not include the type’s name.)

The long form would still be necessary when an invoked constructor’s including type differs from the type of the object being assigned, or when no type can be inferred from context:

class BaseClass { ... }
class Derived : BaseClass { ... }

class SideEffectConstructorClass
{
  public new()
    { System.Console.WriteLine("hello"); }

  public static void Main()
  {
    BaseClass p = new Derived();
    new SideEffectConstructorClass();
  }
}

3 Responses to “Shorter Construction Syntax”

  1. Type inference in C# 3.0 makes it much more concise (though it only works for local variables). So rather than your proposed shorthand
    Dictionary = new();
    you can instead do
    var dict = new Dictionary();
    (where “var” is still strongly typed, not to be confused with the loose typing “var” in javascript)

  2. Good point Radu! This is a nice syntax to use in some cases.

    I think that this point leaves the argument largely unchanged, in that it seems helpful to have a concise notation such as new() that could be used consistently for local and non-local variables.

  3. I agree with you completely. The lack of a more concise syntax in C# is all the more puzzling considering that VB allows a syntax very similar to what you propose:
    Dim a As New Thing2(3,2)