skip to Main Content

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

Answers


  1. I think what you’re trying to do is to turn this:

    class MyClass
    {
        private readonly IMyDependency _thingy;
    
        public MyClass(IMyDependency thingy)
        {
            _thingy = thingy;
        }
    }
    

    Into this:

    class MyClass
    {
        private readonly IMyDependency _thingy;
        public MyClass(IMyDependency thingy) => _thingy = thingy;
    }
    

    Edit: This shorthand is called Expression Body Definition

    Login or Signup to reply.
  2. You are probably wanting primary constructors:

    Primary constructor refactor

    They are only available at C# 12

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search