user2925656 user2925656 - 1 month ago 8
C# Question

Avoid nested if for null and parameter condition

Is it possible to avoid nested if statements while I want to check if variable/object is null and if variable/object meet some condition eg.

var obj = "test";
if(obj!=null){
if(obj.equals("test"){
do something;
}
}


Is it possible to do oneliner of this statement without defining own method which handle this ?

Answer

You can also try (in Java)

"test".equals(obj)

this way, you don't have to do an explicit null check,