This question already has answers here:
Why do I have to typecast an int in a ternary expression? [duplicate]
(4 answers)
Closed 5 years ago.
I have following field in my class:
public bool? EitherObject1OrObject2Exists => ((Object1 != null || Object2 != null) && !(Object1 != null && Object2 != null)) ? true : null;
But in Visual Studio I get an IntelliSense error that there cannot be a conversion between "bool" and "NULL" even though the field is nullable.
What do I do wrong?
And is there a cleaner way to check if either one of two objects is not null but one of them must be null?
try
? (bool?) true : null;
the problem is that default bool (true) is not nullable so the case statement are returning different types as far as the compiler is concerned
And you can remove the redundancy as pointed out by Servy
Object1 != null ^ Object2 != null
Related
This question already has answers here:
Nullable type issue with ?: Conditional Operator
(5 answers)
Closed 5 years ago.
I can sometimes assign null to int? but not inside a ? : , why?
example
int? a; // good
int? b; // good
a = null; // why is this allowed?
b = (a != null) ? 1 : null /* and this not allowed? */;
b = (a != null) ? 1 : (int?)null /* this is a fix */;
From the documentation:
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the
other.
So, in b = (a != null) ? 1 : null type of first argument is int, and second argument is null, which violates the above rule.
In the second case, int can be implicitly converted to (int?)null, that's why it works.
This question already has answers here:
Deep null checking, is there a better way?
(16 answers)
Closed 5 years ago.
Can anyone tell me how do I optimize below code.
if (report != null &&
report.Breakdown != null &&
report.Breakdown.ContainsKey(reportName.ToString()) &&
report.Breakdown[reportName.ToString()].Result != null
)
As others have mentioned, you can use the ?. operator to combine some of your null checks. However, if you're after optimizing for performance, you should avoid the double dictionary lookup (ContainsKey and index access), going for a TryGetValue instead:
MyType match = null; // adjust type
if (report?.Breakdown?.TryGetValue(reportName.ToString(), out match) == true &&
match?.Result != null)
{
// ...
}
Ayman's answer is probably the best you can do for C# 6, for before that what you have there is pretty much the best you can do if all those objects are nullable.
The only way to optimize this further is to be checking if those objects are null before even calling the code, or better yet proofing your platform so this particular function shouldn't even be called in the first place if the values are null.
If you are just getting the value from from the dictionary however you can also simplify with the null coalescing operater '??'
Example:
MyDictionary['Key'] ?? "Default Value";
Thus if the Value at that entry is null you'll get the default instead.
So if this is just a fetch I'd just go
var foo =
report != null &&
report.Breakdown != null &&
report.Breakdown.ContainsKey(reportName.ToString()) ?
report.Breakdown[reportName.ToString()].Result ?? "Default" :
"Default";
But if you are actually doing things in the loop, then yeah you're pretty much at the best you can get there.
For C# 6 and newer, you can do it this way:
if (report?.Breakdown?.ContainsKey(reportName.ToString()) == true &&
report.Breakdown[reportName.ToString()].Result != null)
You can use null conditional operator but only on C# 6
if ( report?.Breakdown?.ContainsKey(reportName.ToString()) == true &&
report.Breakdown[reportName.ToString()].Result != null )
Can you try below? Also probably better to ship it to a method.
// unless report name is already a string
string reportNameString = reportName.ToString();
if ( report?.Breakdown?.ContainsKey(reportNameString) &&
report.Breakdown[reportNameString].Result != null )
{
// rest of the code
}
This question already has answers here:
Nullable types: better way to check for null or zero in c#
(13 answers)
Closed 5 years ago.
Our application requires int? variables. I'm often checking both to make sure not null and not 0 and it does get lengthy.
Is there an out of the box version of String.IsNullOrWhiteSpace() or String.IsNullOrEmpty() for int?
Maybe this would require an extension method?
If there even was or when someone makes one, would something like this considered bad practice?
I don't think so but it's easy to write your own:
[Pure]
public static bool IsNullOrDefault<T>(this T? pValue)
where T : struct {
return pValue == null || pValue.Value.Equals(default(T));
// or as suggested in comments (tested)
return pValue == null || EqualityComparer<T?>.Default.Equals(pValue, default(T));
}
This question already has answers here:
C# elegant way to check if a property's property is null
(20 answers)
Closed 7 years ago.
I have the following C# problem.
Consider the function:
private String getStringFromNullabel()
{
var nullable = getClass(); // returns some object that could be null
if( nullable != null)
{
return nullable.Text;
}
return null;
}
This works but it is verbose and I would rather write something like:
private String getStringFromNullabel()
{
return NotThrowWrapper(getClass()).Text;
}
This will throw if getClass() returns null.
So I am looking for some syntax that is short enough that this stays a one-liner but rather returns null instead of throwing an exception.
Is there such a thing in C#?
Pre C#6
private String GetStringFromNullabel()
{
var nullable = getClass(); // returns some object that could be null
return nullable != null ? nullable .Text : null;
}
Post C# 6
private String GetStringFromNullabel()
{
return getClass()?.Text;
}
Note that you should follow the .NET naming conventions
This question already has answers here:
Conditional operator assignment with Nullable<value> types?
(6 answers)
Nullable types and the ternary operator: why is `? 10 : null` forbidden? [duplicate]
(9 answers)
Closed 9 years ago.
Explain why a nullable int can't be assigned the value of null e.g
int? accom = (accomStr == "noval" ? null : Convert.ToInt32(accomStr));
What's wrong with that code?
The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this instead:
int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));
What Harry S says is exactly right, but
int? accom = (accomStr == "noval" ? null : (int?)Convert.ToInt32(accomStr));
would also do the trick. (We Resharper users can always spot each other in crowds...)
Another option is to use
int? accom = (accomStr == "noval" ? Convert.DBNull : Convert.ToInt32(accomStr);
I like this one most.
Similarly I did for long:
myLongVariable = (!string.IsNullOrEmpty(cbLong.SelectedItem.Value)) ? Convert.ToInt64(cbLong.SelectedItem.Value) : (long?)null;