Shortest null check in C #
Is there a shorter way to write this in C # :
if(myobject!=null){
}
In JavaScript, we can do this:
if(myobject){
}
Disclaimer: I know this will match true and JavaScript. This will only be used for variables that must be a specific type of object.
I found several similar questions, but they ask slightly different things:
C # Shortest way to check for null and assign a different value if not
source to share
You can get the same syntax in C # with the operator:
public class MyClass {
...
// True if instance is not null, false otherwise
public static implicit operator Boolean(MyClass value) {
return !Object.ReferenceEquals(null, value);
}
}
....
MyClass myobject = new MyClass();
...
if (myobject) { // <- Same as in JavaScript
...
}
source to share
The philosophy of C # is not at all like JavaScript. C # tends to force you to be more explicit about certain cases in order to prevent some common programming mistakes (and I'm sure it makes compiler development and testing easier as well).
If C # allows such an implicit conversion to boolean, you are more likely to run into programming errors like this:
if(myobject = otherObject)
{
...
}
where you did the job instead of checking equality. Usually C # prevents such errors (so although Dmitry's answers are smarter, I would recommend that).
source to share
used ?? Operator https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operator
var myobject = notNullValue ?? nullValue;
source to share