I want to call constructor of the class only if my object is not null. I can do it with "if else" but I have a lot of assignment like that and want to make it short. How can I write operator like null assignment "??" but it will work reverse.
From
LastMessage = item.LastMessage != null ? new MessageViewModel(item.LastMessage) : null;
To
LastMessage = item.LastMessage !? new MessageViewModel(item.LastMessage);
or (I am not sure this one gonna work but seems nice to me :) )
LastMessage = ? new MessageViewModel(item.LastMessage);
Related
I am getting a Null reference exception when the Jobject is empty.
var subjects = item.SelectToken("$.subjects").ToObject<List<JObject>>()
I am want to set var subjects as empty when Jobject empty without throwing an error.
THanks
var subjects = item.SelectToken("$.subjects")?.ToObject<List<JObject>>() ?? new List<JObject>();
List<...>
List is a collection and you need to define what's in the List. Like List<string>, List<object>, or, for your code, List<JObject>.
SelectToken("$.subjects")?.
This means that if SelectToken returns null, it stops there without doing .ToObject, and returns null.
The issue here is that SelectToken will return null when it can't find any object, and when you do .ToObject on a null you get a NullException. So one'd usually check if an object is null before further using its properties or functions.
The question mark - Null-Conditional Operator (Official documents) is a quick syntactic sugar to achieve that, without having to write conditions like
if (... == null)
{ ...convert to list... }
else
{ ...make empty list...}
?? new List()
Not sure what you mean by empty, if you don't want null, but an empty List, Null-coalescing Operator might come to help.
It means that if the statement before ?? is null, returns the statement after ?? instead.
For example, string a = b ?? c means:
string a = b != null ? b : c
But notice that a still can be null if c is null.
It's also a syntactic sugar to help you avoid writing long statements for these checks are frequently needed.
With C# 6.0 in the VS2015 preview we have a new operator, ?., which can be used like this:
public class A {
string PropertyOfA { get; set; }
}
...
var a = new A();
var foo = "bar";
if(a?.PropertyOfA != foo) {
//somecode
}
What exactly does it do?
It's the null conditional operator. It basically means:
"Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."
In your example, the point is that if a is null, then a?.PropertyOfA will evaluate to null rather than throwing an exception - it will then compare that null reference with foo (using string's == overload), find they're not equal and execution will go into the body of the if statement.
In other words, it's like this:
string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
...
}
... except that a is only evaluated once.
Note that this can change the type of the expression, too. For example, consider FileInfo.Length. That's a property of type long, but if you use it with the null conditional operator, you end up with an expression of type long?:
FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be null
It can be very useful when flattening a hierarchy and/or mapping objects. Instead of:
if (Model.Model2 == null
|| Model.Model2.Model3 == null
|| Model.Model2.Model3.Model4 == null
|| Model.Model2.Model3.Model4.Name == null)
{
mapped.Name = "N/A"
}
else
{
mapped.Name = Model.Model2.Model3.Model4.Name;
}
It can be written like (same logic as above)
mapped.Name = Model.Model2?.Model3?.Model4?.Name ?? "N/A";
DotNetFiddle.Net Working Example.
(the ?? or null-coalescing operator is different than the ? or null conditional operator).
It can also be used out side of assignment operators with Action. Instead of
Action<TValue> myAction = null;
if (myAction != null)
{
myAction(TValue);
}
It can be simplified to:
myAction?.Invoke(TValue);
DotNetFiddle Example:
using System;
public class Program
{
public static void Main()
{
Action<string> consoleWrite = null;
consoleWrite?.Invoke("Test 1");
consoleWrite = (s) => Console.WriteLine(s);
consoleWrite?.Invoke("Test 2");
}
}
Result:
Test 2
Basically, I have applied ?. operator after Model as well. I am trying to know that whether it can be applied directly to the model or does it only work with the navigation properties?
The ? or null conditional operator operators on the left value, regardless of the type of value. And the compiler doesn't care what the value is on the right. It's simple compiler magic (meaning it does something you can already do, just in a simplified why).
For example
var a = model?.Value;
is the same as saying
var a = model == null ? null : model.Value;
In the second case the evaluation of checking for null has no associate with the value returned. The null conditional operator basically just always return null if the left value is null.
The type of member (Method, Field, Property, Constructor) .Value is irrelevant.
The reason your DotNetFiddle example doesn't work is because the compiler being use for the .Net 4.7.2 isn't compatible with the c# version that support the null conditional operator. Changing it to .Net 5, works:
https://dotnetfiddle.net/7EWoO5
This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.
old way to achieve the same thing was:
var functionCaller = this.member;
if (functionCaller!= null)
functionCaller.someFunction(var someParam);
and now it has been made much easier with just:
member?.someFunction(var someParam);
I strongly recommend this doc page.
With C# 6.0 in the VS2015 preview we have a new operator, ?., which can be used like this:
public class A {
string PropertyOfA { get; set; }
}
...
var a = new A();
var foo = "bar";
if(a?.PropertyOfA != foo) {
//somecode
}
What exactly does it do?
It's the null conditional operator. It basically means:
"Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."
In your example, the point is that if a is null, then a?.PropertyOfA will evaluate to null rather than throwing an exception - it will then compare that null reference with foo (using string's == overload), find they're not equal and execution will go into the body of the if statement.
In other words, it's like this:
string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
...
}
... except that a is only evaluated once.
Note that this can change the type of the expression, too. For example, consider FileInfo.Length. That's a property of type long, but if you use it with the null conditional operator, you end up with an expression of type long?:
FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be null
It can be very useful when flattening a hierarchy and/or mapping objects. Instead of:
if (Model.Model2 == null
|| Model.Model2.Model3 == null
|| Model.Model2.Model3.Model4 == null
|| Model.Model2.Model3.Model4.Name == null)
{
mapped.Name = "N/A"
}
else
{
mapped.Name = Model.Model2.Model3.Model4.Name;
}
It can be written like (same logic as above)
mapped.Name = Model.Model2?.Model3?.Model4?.Name ?? "N/A";
DotNetFiddle.Net Working Example.
(the ?? or null-coalescing operator is different than the ? or null conditional operator).
It can also be used out side of assignment operators with Action. Instead of
Action<TValue> myAction = null;
if (myAction != null)
{
myAction(TValue);
}
It can be simplified to:
myAction?.Invoke(TValue);
DotNetFiddle Example:
using System;
public class Program
{
public static void Main()
{
Action<string> consoleWrite = null;
consoleWrite?.Invoke("Test 1");
consoleWrite = (s) => Console.WriteLine(s);
consoleWrite?.Invoke("Test 2");
}
}
Result:
Test 2
Basically, I have applied ?. operator after Model as well. I am trying to know that whether it can be applied directly to the model or does it only work with the navigation properties?
The ? or null conditional operator operators on the left value, regardless of the type of value. And the compiler doesn't care what the value is on the right. It's simple compiler magic (meaning it does something you can already do, just in a simplified why).
For example
var a = model?.Value;
is the same as saying
var a = model == null ? null : model.Value;
In the second case the evaluation of checking for null has no associate with the value returned. The null conditional operator basically just always return null if the left value is null.
The type of member (Method, Field, Property, Constructor) .Value is irrelevant.
The reason your DotNetFiddle example doesn't work is because the compiler being use for the .Net 4.7.2 isn't compatible with the c# version that support the null conditional operator. Changing it to .Net 5, works:
https://dotnetfiddle.net/7EWoO5
This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.
old way to achieve the same thing was:
var functionCaller = this.member;
if (functionCaller!= null)
functionCaller.someFunction(var someParam);
and now it has been made much easier with just:
member?.someFunction(var someParam);
I strongly recommend this doc page.
What does this syntax mean? I'm currently coding c# 4.0, when I came by this piece of code.
_data = (SerializationHelper.Deserialize(Request.Form[_dataKey])
? TempData[_dataKey] ?? new ProfileData ()) as ProfileData;
If I were to write it i IF statements how would it be then?
The compiler gives me an error for not writing a : aswell as more things are needed?
?? means if it's null, use the other value. For example
var name = somevalue ?? "Default Name";
If somevalue is null, it will assign the value "Default Name"
Also the single ? is a ternary operator, basically you use it like this:
var example = (conditional statement here) ? value_if_true : value_if_false;
However your code doesn't seem to follow the right syntax for ternary operators when I look at it properly, as Corey says, you may have missed a ? off a ??.
Looks like you missed a ? there. I suspect it was supposed to read:
_data = (SerializationHelper.Deserialize(Request.Form[_dataKey])
?? TempData[_dataKey]
?? new ProfileData()
) as ProfileData;
In C# the operation A ?? B is directly equivalent to (A == null ? B : A), or if (A == null) return B; return A; if you prefer.
So your statement above is equivalent to:
object tmp = SerializationHelper.Deserialize(Request.Form[_dataKey]);
if (tmp == null)
{
tmp = TempData[_dataKey];
if (tmp == null)
_tmp = new ProfileData();
}
_data = tmp as ProfileData;
var foo = context.FOOTABLE.FirstOrDefault();
var bar = foo != null ? foo.SomeBool : false;
Resharper tells me to Simplify conditional ternary expression. But I feel like a null check is necessary here, since FirstOrDefault() can return null.
So, who's wrong, me or Resharper?
First, a full example:
class Foo
{
public bool SomeBool { get; set; }
}
class Program
{
static void Main(string[] args)
{
var foo = MaybeFoo();
var bar = foo != null && foo.SomeBool;
}
static Foo MaybeFoo()
{
return new Random().Next() < 10 ? null : new Foo();
}
}
Here MaybeFoo is a method that sometimes returns null and sometimes returns a Foo. I've used Random so that R# doesn't automatically work out that it's always null or not-null.
Now, as you say on this line:
var bar = foo != null ? foo.SomeBool : false;
R# offers the inspection Simplify conditional operator. What does it mean by this? Well, as usual, we can Alt+Enter and accept the suggestion and see what it wants to replace it with, which in this case is:
var bar = foo != null && foo.SomeBool;
Now, as to your concern:
But I feel like a null check is necessary here, since FirstOrDefault() can return null.
So, who's wrong, me or Resharper?
Well, to put it shortly, you are. There's still a null check taking place here, and the && operator is short-circuiting, so the second operand (foo.SomeBool) will only be evaluated if the first one is true. So there won't be a NullReferenceException in the case when foo is null; the first check will fail and bar will be assigned false.
So the two lines
var bar = foo != null ? foo.SomeBool : false;
and
var bar = foo != null && foo.SomeBool;
are semantically equivalent, and R# as usual prefers the more concise version (in particular, explicit trues and falses in conditionals are often a mark of redundant code). You may not, in which case you could turn off this inspection.
ReSharper is suggesting to change your code to:
var bar = foo != null && foo.SomeBool;
Which does exactly the same as ternary operation, but looks better. The logic of your code won't change.