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
I think what you’re trying to do is to turn this:
Into this:
Edit: This shorthand is called Expression Body Definition
You are probably wanting primary constructors:
They are only available at C# 12