Is there C# syntactic sugar for declaring and assigning a field in the constructor arguments of a class?

I’m trying to remember a C# Language feature, but I haven’t touched C# in a bit. I can’t remember the exact syntax or find any documentation on it.

The feature I’m trying to remember was shorthand to declare a field or property in the arguments of a constructor and assign the constructor argument to that field all in one statement.

If it helps, the context I remember using it in was a .NET Core Azure Function with dependency injection. I’m not sure if it’s possible that this feature was specific to .NET Core, Azure, or the dependency injection framework.

It was something like this:

class MyClass
{
  public MyClass(private IMyDependency thingy = null)
  {
    ...
  }
}

where the code written above was equivalent to:

class MyClass
{
  private readonly IMyDependency _thingy;

  public MyClass(IMyDependency thingy)
  {
    this.thingy = thingy;
  }
}

Is this feature real? Was it removed? Am I imagining it?

If it is real, what is the syntax, and what is it called?

  • 2

    Are you talking about primary constructors?

    – 




  • Are you thinking of a feature from TypeScript (maybe also JavaScript)?

    – 

  • 1

    I am not aware of any such thing. Closest would be above mentioned primary ctor. Or maybe do you mistake it for a record?

    – 




  • The (typed) “class” is no longer a (typed) class, if you can add random properties at run time. It would be the equivalent of a “bag” then; a different class intended to support “random properties”; e.g. ConcurrentBag.

    – 

  • 1

    I’m pretty sure you’re thinking of a TypeScript feature for constructor argument assignment. That doesn’t exist in C#.

    – 

Leave a Comment