I using C# 12. In C# 12 I can use primary constructor:
public class UserService(IUnitOfWork uow) : IUserService
{
}
Before C# 12 I used null checking for items that I inject in constructor:
public class UserService : IUserService
{
private readonly IUnitOfWork _uow;
public UserService(IUnitOfWork uow)
{
ArgumentNullException.ThrowIfNull(uow);
_uow = uow;
}
}
Now how can I do null checking in C# 12 ?
Is it need to use fail fast with primary constructor ?
As far as I know if you want to switch to primary constructors one of the easiest options would be to introduce field/property:
Note that you can also name the field the same as your constructor parameter (
_uow
->uow
), if you don't want to clutter your class with an extra name (as suggested by Heinzi) which has additional benefit of shadowing the mutable primary ctor parameter by an immutable field.You can also encapsulate the logic into helper method. Something along these lines: