C# ?? operator in property, how it works? - c#

I can't understand how it works.
private Person _user;
private Person User
{
get
{
return _user ?? ( _user = GetUser() );
}
}
The first time I refer to User property, _user is null so it returns ( _user = GetUser() )????
What am I missing?

First, it is null-coalescing operator and it returns the left hand operand if the that is not null, otherwise it returns the right hand operand.
return _user ?? ( _user = GetUser() );
In case of _user being null, it returns what is returned by GetUser method and set the private field to it as well.
So it works like:
GetUser returns value which is assigned to _user
Assignment expression (_user = GetUser()) returns the value.
See: How assignment expression returns value.

That code is essentially the same as this:
private Person _user;
private Person User
{
get
{
if (_user == null) _user = GetUser();
return _user;
}
}
How it works
The null coalescing operator (??) returns the object if it's not null, otherwise it returns whatever is on the other side of the operator. So the statement:
return _user ?? ( _user = GetUser() );
Says, "return _user, unless it's null, in which case return the result of the assignment ( _user = GetUser() )". This is a clever way of assigning a value to _user and returning that assigned value in the same line.
That being said, some developers will argue that the first method I wrote above, which uses two lines instead of one, is more readable (the intent is clearer) and easier to maintain.

It's called the Null Coalescing operator. If the object on the left hand side of it is null, it'll perform the expression on the right hand side.
Here, the operator on the right hand side sets the _user object, so next time User is referenced, it will no longer perform the right-hand side, and return _user

The assingment expression = both does the assignment to _user and returns the value that was assigned, so it can be used like an expression.

So after Habibs tip I found this in MSDN.
= Operator (C# Reference)
where is clear...
"The assignment operator (=) stores the value of its right-hand operand in the storage location, property, or indexer denoted by its left-hand operand and returns the value as its result."
I still can't believe that I didn't know that.

?? is syntax sugar for the following:
if(_user != null)
return _user; // first part before ??
else
return (_user = GetUser() ); //Second part after ??
Edit:
As #Rufus L pointed out:
The (_user = GetUser() ); part assigns the return value of GetUser to _user and then returns the value of _user. If we simplify the previous code:
if(_user != null)
return _user;
else
{
_user = GetUser();
return _user;
}
Extra info: you can chain assignments, as long as the type is the same, or implicit casting are implemented:
int x, y, z;
x = y = z = 4;

It basically checks if _user is not null first. If is not null returns it. Otherwise, it sets _user to whatever GetUser() returns.
Pseudocode
_user != null
return _user
otherwise
_user = GetUser()
Here is a post that talks about the "Null Coalescing operator"

Related

Excel IsError equivalent function in C#

Is there a function in c# that can help to check if the statement is going to return error.
I am aware about try{} catch{} but we can't use it in condition checking. For example:
var opertionResult = SomeRestFunction.Trigger();
string ServerResponse = if(operationResult != null)
{
if(operationResult.Response != null)
{
operationResult.Response.ResponseText;
}
Else
{
"Null";
}
}
Else
{ "Null"; }
In the example above, I need to perform multiple checks to validate the operationResult object properties at multiple levels due to nested objects in it, to determine the final value I want to read and consume as server response value.
If we have some thing like IsError() function in Excel, we can simply try to read the final object property i.e. operationResult.Response.ResponseText; inside of that function and if any of the parent object is null and it has to throw an error it will return false and we can return the value from the else block as shown in the hypothetical example below:
var opertionResult = SomeRestFunction.Trigger();
string ServerResponse = IsError(operationResult.Response.ResponseText)? "Null": operationResult.Response.ResponseText;
So, do we have something like this in C#? Hope this makes sense?
If you're using c# 6 or newer version then you can use null-conditional & null-coalescing-operator operator like below.
Here you need to place ? to check if object is null or not. If object is null then it will not perform any further check and return null. And null-coalescing-operator (??) will be used to check if value is null then it will return value provided afer ??.
string ServerResponse = SomeRestFunction.Trigger()?.Response?.ResponseText ?? "Null";

How to read such construction?

I've jumped into such a thing in my code and I don't really know how to read this. Would be nice if somebody could help me with this :)
return Company?.Call?.SingleOrDefault(cf => cf.Name == Client?.CallID)
?? Company?.Call?.SingleOrDefault(cf => cf.IsDefault)
?? new CallData();
The ?. operator is called a Null-conditional operator and is a new feature from C# 6, and was announced in October 2014. https://msdn.microsoft.com/en-us/library/dn986595.aspx
The first part: Company?.Call?.SingleOrDefault can be seen as similar to this:
if (Company == null)
{
return null;
}
else if (Company.Call == null)
{
return null;
}
else
{
return Company.Call.SingleOrDefault(....
}
But then the original coder uses the ?? Null-coalesce operator, which has been a part of C# since at least 2007. It means that if whatever is left of the ?? is null, evaluate what is right of the ?? and return that instead.
So the code basically means:
If Company is null, return new CallData()
If Company.Call is null, return new CallData()
If the first call to Company.Call.SingleOrDefault returns a CallData instance (having a certain value for the Name property) , return that instance
If the first call returns null, but the second call returns a CallData instance (being the default one) , return that instance
If both calls to SingleOrDefault return null, return new CallData()
This piece of code has some issues.
First of all, it is unreadable and should be refactored into something that is easier to understand. New language features are nice, but only when used responsibly.
Second: If there are more than one CallData instances with the same Name, the SingleOrDefault will throw an exception, but there might be a unique index in the database the prevents this. The same goes for IsDefault property - if there are more than one records with IsDefault = true, the SingleOrDefault call will throw an exception.
Split it to 3 expressions first, separated by the ??:
Company?.Call?.SingleOrDefault(cf => cf.Name == Client?.CallID)
??
Company?.Call?.SingleOrDefault(cf=>cf.IsDefault)
??
new CallData();
The returned value of the entire expression would be the first expression that is returning a non-null value.
Within each segment, once any of the properties accessed using ?. is null, the entire expression will be evaluated to null.
See Null-conditional Operators

Check for null before select on linq

I have just installed ReSharper, and it has altered
if(dto != null)
{
return new test{
obj1 = "",
obj2 = "",
}
}
into
return dto?.Select(item => new test
{
return new test{
obj1 = "",
obj2 = "",
}
I have not seen before
dto?.Select
tried to google the meaning with no luck.. could someone please explain , or point me in the right direction to the deffination
I gather its simply checking for null?
Null propagation operator is newly introduced in C# 6. return dto?.Select... means, if dto is null then this statement will return null else will execute the remaining part.
Another example, just making it up, assume you have Employee object with Address property which inturn has Lane (string), Pincode etc.
So if you need to get the address lane value you could do:
var lane = employee?.Address?.Lane;
Which will return null if employee or address is null; otherwise returns lane value.
This could be combined in many ways and is really handy.
For eg,
int someIntegerValue = someObject?.SomeIntValue ?? 0;
Basically you could avoid many null checks with this feature.
The question-mark operator acts on nullable values and
x?<operation>
translates to
x.HasValue ? x.Value.<operation> : null
It's basically saying "do this if I'm not null; otherwise keep me as null".
Do you have a
return null
statement later in your original code? I am surprised ReSharper would assume a return null in its transformation.

'?' in middle of LINQ statement

I cam across this line while going through some not that old code and don't understand why anyone would ever do it:
return dbStudents.MethodToReturnAllStudents()?.Select(x => new dtoStudent(x));
MethodToReturnAllStudents returns an IEnumerable<SQLDomain.Student> (dtoStudent) is in a different namespace -- all the SQLDomain.Student has been mapped from an IDataRecord.
Why would there be a ? in the middle of this statement. Will the LINQ Select try to do anything if MethodToReturnAllStudents returns null?
Is this just terrible code all around?
Side note: Either way, I am refactoring it to follow some alternative standards and to be much more readable.
This is not "old code", since this is a C#6 feature, the Null Conditional Operator. When used, it checks if the immediately preceding value is null before allowing property/method usage on that instance. If it is null, it returns null.
In this scenario, you can translate this code to:
var students = dbStudents.MethodToReturnAllStudents();
if (students == null) return null;
return students.Select(x => new dtoStudent(x));
However, there is actually a larger potential issue with this code than the unfamiliar operator.
The general consensus is that IEnumerable<T> should never return null and, as such, should never need to be null checked. It should always return a sequence that is either hydrated or empty.
That said, if this were in fact List<T> (or a null IEnumerable, although less common), this could be a real scenario (although I would still advocate for never returning null but rather an empty list).
You will have to decide as a development team if the Null Conditional Operator is more succinct and readable. Personally, I'm a fan of it, just not in this context since it is indicative of a larger design smell.
It's not "terrible" code, but it's non-intuitive if you're not familiar with the syntax. I personally enjoy the less-verbose options. LINQ will stop if MethodToReturnAllStudents() returns null and just return that null. It's basically saying
var retVal = dbstudents.MethodToReturnAllStudents();
if(retVal == null) {
return retVal;
} else {
return retVal.Select(x => new dtoStudent(x));
}
Now as users have pointed out, it shouldn't return null as the caller is expecting an IEnumerable.
var retVal = dbstudents.MethodToReturnAllStudents();
if(retVal == null) {
return new List<student>();
} else {
return retVal.Select(x => new dtoStudent(x));
}
Using a null coalescing operator makes the code even more concise and still properly handles return types so it doesn't return null:
return dbStudents.MethodToReturnAllStudents()?.Select(x => new dtoStudent(x)) ?? new List<student>();
It is the Null Conditional Operator
MSDN Documentation
If dbStudents.MethodToReturnAllStudents() is null, it will return null instead of executing .Select(x => new dtoStudent(x)) which would result in a NullReferenceException.

Shorthand to cast a string value

I'm not talking about javascript, but in javascript, I can declare a string like this:
var identity = {
getUserId: function () {
return 'userid';
}
};
var userid = identity.getUserId() || '';
That means: if identity.getUserId() is null or undefined, the value '' will be casted to userid automatically.
Now, in C#:
public static void AddOnlineUser(this IIdentity identity)
{
string userid = identity.GetUserId();
// long way to check userid is null or not:
if (string.IsNullOrEmpty(userid))
{
userid = "";
}
// invalid C# syntax:
// Operator || cannot be applied to operands of type 'string' and 'string'
// string userid = idenity.GetUserId() || "";
// Only assignment, call, increment, decrement, and new object expressions can be used as a statement
// string.IsNullOrEmpty(userid) ? "" : userid;
}
I don't mean: want to create a C# variable same as javascript syntax. But in this case, is there a way to cast value "" to userid if it's null or empty in 1 line?
The Null Coalescing Operator ??
C# has it's own null-coalescing operator ?? to do this to handle null values :
// This will use the available GetUserId() value if available, otherwise the empty string
var userid = identity.GetUserId() ?? "";
Keep in mind this operator will only work as expected if the first value in your statement is null, otherwise it will use that value. If there is a chance that this isn't the case (and you might encounter a non-null invalid value), then you should consider using a ternary operator instead.
The Ternary Operator ?:
Otherwise, you could use a ternary operator ?: (i.e. an inline if-statement) to perform this check as well. This is similar to the example you provided, however it's worth noting that you need to actually set userid to the result :
// This will set it to empty string if null or empty, otherwise it will use the returned id
userid = String.IsNullOrEmpty(userid) ? "" : userid;

Categories

Resources