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;
Related
I am trying to use TryGetValue on a Dictionary as usual, like this code below:
Response.Context.Skills[MAIN_SKILL].UserDefined.TryGetValue("action", out var actionObj)
My problem is the dictionary itself might be null. I could simply use a "?." before UserDefined but then I receive the error:
"cannot implicitly convert type 'bool?' to 'bool'"
What is the best way I can handle this situation? Do I have to check if UserDefined is null before using TryGetValue? Because if I had to use Response.Context.Skills[MAIN_SKILL].UserDefined twice my code could look a little messy:
if (watsonResponse.Context.Skills[MAIN_SKILL].UserDefined != null &&
watsonResponse.Context.Skills[MAIN_SKILL].UserDefined.TryGetValue("action", out var actionObj))
{
var actionName = (string)actionObj;
}
Add a null check (?? operator) after the bool? expression:
var dictionary = watsonResponse.Context.Skills[MAIN_SKILL].UserDefined;
if (dictionary?.TryGetValue("action", out var actionObj)??false)
{
var actionName = (string)actionObj;
}
Another option is to compare to true.
It looks slightly weird, but it works with three-valued logic and says: is this value true but not false or null
if (watsonResponse.Context.Skills[MAIN_SKILL]
.UserDefined?.TryGetValue("action", out var actionObj) == true)
{
var actionName = (string)actionObj;
}
You can do the opposite logic with != true: is this value not true, so either false or null
if (watsonResponse.Context.Skills[MAIN_SKILL]
.UserDefined?.TryGetValue("action", out var actionObj) != true)
{
var actionName = (string)actionObj;
}
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";
I'm just looping and appending my properties to a big string:
output.Append(property.GetValue(this).ToString()));
When app breaks in that moment property represent a ProductNumber which is a string, value of this is Product object which has value of ProductNumber = null, so I've tried something like this:
output.Append(property.GetValue(this)?.ToString()));
But anyway it breaks..
How could I improve this code to avoid breaking there?
Thanks
Cheers
It seems that output.Append complains on null values. There are 2 possible sources of pesky nulls here:
property.GetValue(this) returns null and thus ?. in ?.ToString() propagates null
ToString() itself returns null (hardly a case, but still possible)
We can solve both possibilities with ?? operator: let's return an empty string whatever the source of null is:
property.GetValue(this)?.ToString() ?? ""
Final code is
output.Append(property.GetValue(this)?.ToString() ?? "");
This code:
output.Append(property.GetValue(this)?.ToString()));
Is the same as:
object propValue = property.GetValue(this);
string propString = null;
if (propValue != null)
{
propString = propValue.ToString();
}
output.Append(propString); // propString can be null
This can be simplyfied like so:
string propString = property.GetValue(this)?.ToString(); // This performs a ToString if property.GetValue() is not null, otherwise propString will be null as well
output.Append(propValue); // propValue can be null
If you want to prevent calling Append with a null value you can do:
string propString = property.GetValue(this)?.ToString(); // This performs a ToString if property.GetValue() is not null, otherwise propString will be null as well
if (propString == null)
{
propString = string.Empty;
}
output.Append(propValue); // propString is not null
This can be simplified with the null-coalescing operator:
string propString = property.GetValue(this)?.ToString() ?? string.Empty
output.Append(propValue); // propString is not null
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"
How can I check if any key from json object have null value
JsonObject itemObject = itemValue.GetObject();
string id = itemObject["id"].GetString() == null ? "" : itemObject["id"].GetString();
this is my code but app crashes on it if null value for key "id"
IJsonValue idValue = itemObject.GetNamedValue("id");
if ( idValue.ValueType == JsonValueType.Null)
{
// is Null
}
else if (idValue.ValueType == JsonValueType.String)
{
string id = idValue.GetString();
}
If you do this too much, consider adding extension methods.
To do the opposite use:
IJsonValue value = JsonValue.CreateNullValue();
Read here more about null values.
http://msdn.microsoft.com/en-us/library/ms173224.aspx
The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.
if itemObject["id"] is null then the method null.GetString() doesn't exist and you'll get the error specified (null object never has any methods/fields/properties).
string id = itemObject["id"] == null ? (string)null : itemObject["id"].GetString(); // (string)null is an alternative to "", both are valid null representations for a string, but you should use whichever is your preference consistently to avoid errors further down the line
the above avoids calling .GetString() until you've asserted that the ID isn't null (check here for more in-depth), if you're using C#6 you should be able to use the new shorthand:
string id = itemObject["id"]?.GetString();
Here is solution for the issue
string id = itemObject["id"].ValueType == JsonValueType.Null ? "" : itemObject["id"].GetString();