Home > Net >  Conditional null check code lines is not being considered by code coverage
Conditional null check code lines is not being considered by code coverage

Time:03-26

If i write code line like

string employeeName= objEmp?.EmployeeName;

then this line is not being considered by code coverage because of ?.. What i will have to do to consider this line by code coverage in .net core.

CodePudding user response:

string employeeName = objEmp?.EmployeeName ?? string.Empty;

CodePudding user response:

What you're looking for is called the null-coalescing operator and has two common forms: ?? and ??= (assignment) which can be used as shown:

var employeeName = objEmp.EmployeeName ?? Value

This will set employeeName to Value if objEmp.Employee is null

var employeeName ??= obj.EmployeeName

This will set employeeName to obj.EmployeeName if employeeName is null (which will always be the case in this instance since employeeName is just declared)

The first option seems to make most sense for your case but doesn't hurt to know both.

Some useful documentation: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator

  • Related