If null.Equals(null) why do I get a NullReferenceException - c#

I have the following line of code:
var selectedDomainID = lkuDomainType.EditValue.Equals(null)
? string.Empty
: lkuDomainType.EditValue;
Sometimes this generates a NullReferenceException. What I don't understand is why. Isn't the whole point of my code to check for null and if so assign string.empty? When I check in DEBUG it is stating that EditValue == null so what am I missing?

Use lkuDomainType.EditValue == null, otherwise you are trying to call an instance method on a null object. But the better option might be lkuDomainType.EditValue ?? String.Empty. Also watch out for lkuDomainType being null, unless it is a class not an object.

When you use Object.Property and Object is undefined, you are dereferencing a null pointer and that's why you get the exception. Instead, use:
var selectedDomainID = lkuDomainType.EditValue == null ? string.Empty : lkuDomainType.EditValue;

If EditValue is null then you can't call Equals. In this cas you would have to do:
var selectedDomainID = lkuDomainType.EditValue == null ? string.Empty : lkuDomainType.EditValue;
Or you can simplify it by doing:
var selectedDomainID = lkuDomainType.EditValue ?? string.Empty;

you are trying to call the Equals method on a null object - do it like this instead:
lkuDomainType.EditValue == null

The problem is that you are using the object before checking if it's null. You are calling the Equals method of the object, which fails if the reference is null.
You have to exchange your lkuDomainType.EditValue.Equals(null) for lkuDomainType.EditValue == null.

EditValue == null. That means that there is no object there. You cannot call functions on null objects, even if the function is .Equals().
You're better off just saying "(lkuDomainType.EditValue == null)" in this case.

You should use String.IsNullOrEmpty here. Like this:
var selectedDomainID = String.IsNullOrEmpty(lkuDomainType.EditValue) ? string.Empty : lkuDomainType.EditValue;
Equals is a method, you're trying to call a method on a null object which is throwing an exception.

when EditValue is null you cannot call the Equals method on it so the best way to check is to use
lkuDomainType.EditValue == null ? string.Empty : lkuDomainType.EditValue;

If lkuDomainType.EditValue is null, then "lkuDomainType.EditValue.Equals(someObject)" is the same as coding "null.Equals(someObject)". Well, obviously "null" doesn't have any members or methods (it wouldn't be null if it did). That's why you get a NullReferenceException.
Most of the examples from the other posts will work, including String.IsNullOrEmpty, which is a method that returns a boolean value.

All current answers fail to address a critical point: the difference between calling Equals on a Nullable type (which is a struct) vs. class type.
Calling Equals on a Nullable typed object whose value is null will not issue an exception, while doing the same on a class typed object will.
Consider the following code:
int? num = null; // int? is Nullable<int>
String s = null; // String is a class
var equalsNullable = num.Equals(null); // works
var equalsClass = s.Equals(null); // throws
The reason is that Nullable's HasValue method is called in such case, see Jon Skeet's answer for more info.
As other people said, the way to go in the OP's case is to use == or ??.

Related

If an object is of specified Type, can it still be null?

If you check an object for its type and find out it is of the type you checked for, and you convert it to this type, can this type still be null after conversion ?
The code quality scanning app I'm running is complaining about the following:
if (tx.Tag is ExtendedNodeInfo && ty.Tag is ExtendedNodeInfo)
{
var tagX = tx.Tag as ExtendedNodeInfo;
var tagY = ty.Tag as ExtendedNodeInfo;
// HP Fortify scan says the below line's use of tagX/Y can be null.
// If I add null checks below for taX/Y, Resharper says
// its redundant as its always not null
return tagX.Ordinal.CompareTo(tagY.Ordinal);
}
If tx.Tag doesn't change its value, that's fine - but presumably the code quality scanner doesn't know that. It's generally better to use as for this, so that you only evaluate the property once, only perform the type test once, and then just check the references:
var tagX = tx.Tag as ExtendedNodeInfo;
var tagY = ty.Tag as ExtendedNodeInfo;
if (tagX != null && tagY != null)
{
return tagX.Ordinal.CompareTo(tagY.Ordinal);
}
if (tx.Tag is ExtendedNodeInfo && ty.Tag is ExtendedNodeInfo)
After this line, you have the following guarantees:
tx and ty are not null (otherwise, a NullReferenceException would have been thrown)
both tx.Tag and ty.Tag are of type ExtendedNodeInfo, so you can safely cast them to that type, so in your example both tagX and tagY are guarantueed to be not null
If the warning is about the use of txTag or tyTag, then this is wrong, IMO. But possibly, the warning is about the unchecked dereferencing of Ordinal?

Object type null value check

I am using bellow code to get date value from ListviewDataItem control
object HyperWalletPayoutDate =
DataBinder.Eval(dataItem.DataItem, "HyperWalletPayoutDate");
some time HyperWalletPayoutDate value come null. How can i check this null value ?
I have tried this way but not working
if (HyperWalletPayoutDate.Any() == null || HyperWalletPayoutDate == ""
|| HyperWalletPayoutDate ==null)
Please give me suggestion to solve this problem. Thanks in advance ..
The behaviour you are seeing (the value is {} rather than null) is a result of Boxing. Assuming you are expecting a string value you should use the correct check for that particular type i.e.
if (String.IsNullOrEmpty((string)HyperWalletPayoutDate)) {
...
}
This will internally unbox the value and determine whether it has a value.
The problem with your code is that the first condition
if (HyperWalletPayoutDate.Any() == null || ...
already requires an instance. You have to perform the null check on HyperWalletPayoutDate first:
if (HyperWalletPayoutDate == null || HyperWalletPayoutDate == "" || HyperWalletPayoutDate.Any() == null)
when HyperWalletPayoutDate is null, the other conditions are not evaluated, so no exception is thrown anymore.
I think it works like this:
if(HyperWallenteretPayoutDate.Any(d => d)){
//it does not equal null
}

Why ?: operator does not work with nullable<int> assignation?

I'm creating an object for my database and I found a weird thing, which I don't understand:
I've an object which should reference a "language" by an ID, but this can be null, so my property is a int?(Nullable<int>)
so firstly I tried to use the object initializer:
myObject = new MyObject()
{
myNullableProperty = language == null ? null : language.id;
}
but it doesn't work! It tell me that null cannot be converted to int
But if I it in a if/else structure, I can put null in a var and then assign it to my properties.
Why is this acting like this?
You may try casting the null to int? as the ?: operator requires both operands to return the same type:
myNullableProperty = language == null ? (int?)null : language.id
This is because of a type mismatch. You must cast your null value to the int type.
The reason is, when using the ? operator the left and the right side of the : are required to be from the same type and typeof(null)!=typeof(int) so:
myNullableProperty = language == null ? (int?)null : language.id;
Most likely null is interpreted as object which obviously can't be assigned to int. You might want to use myNullableProperty = language == null ? (int?)null : language.id;

Object reference not set to an instance of an object

When I try to open the page from my IDE in VS 2008 using "VIEW IN BROWSER" option I get "Object reference not set to an instance of an object" error.
The piece of code I get this error :
XResult = Request.QueryString["res"];
TextBox1.Text = XResult.ToString();
The problem here is that XResult is null and when you call ToString on it the code produces a NullReferenceException. You need to account for this by doing an explicit null check
TextBox1.Text = XResult == null ? String.empty : XResult.ToString();
If you are opening the page without the "res" query string then you need to include a check for null before you do anything with it.
if (Request.QueryString["res"] != null)
{
XResult = Request.QueryString["res"];
TextBox1.Text = XResult.ToString();
}
That error could be Because the REquest.QueryString method did not find a value for "res" in the url so when you try to do the "toString" to a null object whrow that exeption.
Your code is expecting a query string http://localhost:xxxx/yourapp?res=yourval. It's not present in the address supplied to the browser. In the web section of your project properties, you can supply an appropriate URL. Of course, shoring up your code to allow for this would be advisable.
XResult is already a string, so calling ToString isn't necessary. That should also fix your problem.
The problem here is that XResult is null, and when you call ToString
on it the code produces a NullReferenceException. You need to account for this by doing an explicit null check:
if (Request.QueryString["res"] != null)
{
XResult = Request.QueryString["res"];
TextBox1.Text = XResult.ToString();
}

How to avoid a NullReferenceException

if (alMethSign[z].ToString().Contains(aClass.Namespace))
Here, I load an exe or dll and check its namespace. In some dlls, there is no namespace, so aclass.namespace is not present and it's throwing a NullReferenceException.
I have to just avoid it and it should continue with rest of the code. If I use try-catch, it executes the catch part; I want it to continue with the rest of the code.
Don't catch the exception. Instead, defend against it:
string nmspace = aClass.Namespace;
if (nmspace != null && alMethSign[z].ToString().Contains(nmspace))
{
...
}
Is aClass a Type instance? If so - just check it for null:
if (aClass != null && alMethSign[z].ToString().Contains(aClass.Namespace))
Add the test for null in the if statement.
if(aClass.NameSpace != null && alMethSign[z].ToString().Contains(aClass.Namespace))
Or use an extension method to that checks for any nulls and either returns an empty string or the string value of the object:
public static string ToSafeString(this object o)
{
return o == null ? string.Empty : o.ToString();
}

Categories

Resources