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;
Related
How can I check if any key from json object have null value
JsonObject itemObject = itemValue.GetObject();
string id = itemObject["id"].GetString() == null ? "" : itemObject["id"].GetString();
this is my code but app crashes on it if null value for key "id"
IJsonValue idValue = itemObject.GetNamedValue("id");
if ( idValue.ValueType == JsonValueType.Null)
{
// is Null
}
else if (idValue.ValueType == JsonValueType.String)
{
string id = idValue.GetString();
}
If you do this too much, consider adding extension methods.
To do the opposite use:
IJsonValue value = JsonValue.CreateNullValue();
Read here more about null values.
http://msdn.microsoft.com/en-us/library/ms173224.aspx
The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.
if itemObject["id"] is null then the method null.GetString() doesn't exist and you'll get the error specified (null object never has any methods/fields/properties).
string id = itemObject["id"] == null ? (string)null : itemObject["id"].GetString(); // (string)null is an alternative to "", both are valid null representations for a string, but you should use whichever is your preference consistently to avoid errors further down the line
the above avoids calling .GetString() until you've asserted that the ID isn't null (check here for more in-depth), if you're using C#6 you should be able to use the new shorthand:
string id = itemObject["id"]?.GetString();
Here is solution for the issue
string id = itemObject["id"].ValueType == JsonValueType.Null ? "" : itemObject["id"].GetString();
I am trying to populate a combobox with a list my query returns. When I execute my program it gives me a specified cast is not valid error ( I have it execute on page load event). Every field in the database I have to work with can be null except the primary key. So I tried using DBNull.Value but it can't get my (int)reader fields to work. I have supplied my code below for a better understanding. How can I get my (int)reader's to work with my statements, so they can read when there is a null value?
CustData cd = new CustData();
cd.CustomerID = (int)reader["CustomerID"];
cd.Name = reader["Name"] != DBNull.Value ? reader["Name"].ToString() : string.Empty;
cd.ShippingAddress = reader["ShippingAddress"] != DBNull.Value ? reader["ShippingAddress"].ToString() : string.Empty;
cd.ShippingCity = reader["ShippingCity"] != DBNull.Value ? reader["ShippingCity"].ToString() : string.Empty;
cd.ShippingState = reader["ShippingState"] != DBNull.Value ? reader["ShippingState"].ToString() : string.Empty;
cd.ShippingZip = (int)reader["ShippingZip"];
cd.BillingAddress = reader["BillingAddress"] != DBNull.Value ? reader["BillingAddress"].ToString() : string.Empty;
cd.BillingCity = reader["BillingCity"] != DBNull.Value ? reader["BillingCity"].ToString() : string.Empty;
cd.BillingState = reader["BillingState"] != DBNull.Value ? reader["BillingState"].ToString() : string.Empty;
cd.BillingZip = (int)reader["BillingZip"];
cd.Territory = reader["Territory"] != DBNull.Value ? reader["Territory"].ToString() : string.Empty;
cd.Category = reader["Category"] != DBNull.Value ? reader["Category"].ToString() : string.Emptyy
That is because int is not nullable. You need to use int? or nullable<int> (long hand) to allow it to be an int OR a null value.
You can then use the usual .HasValue and .Value etc to get the value from the item.
EDIT: To enhance the visibility of my comment to this answer. I would advise against checking for NULL and storing Zero into your property because then when you save back you are changing a Null to a Zero even though nothing has been changed by the system. Now, reports etc may distinguish between NULL and Zero (very often) and could start doing strange things!
Null does NOT equal zero!! If you assume it does as a work around... What happens if I truly do want to record zero? How do you differentiate between a real zero and a "was null now zero" trick? Do it right, save yourself the pain!
Use nullable int, or just make your control for your int's too
reader["ShippingZip"] != DBNull.Value ? (int)reader["ShippingZip"] : default(int);
You should use a nullable int for your variable and cast it, like (int?). Int can only have a value; nullable types can also be null. When you use a nullable type, you can look at the property .HasValue. Here is the MSDN page: http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx
This is my code:
DateTime? test;
test = ((objectParsed.birthday != null) ? DateTime.Parse((string)objectParsed.birthday : null));
Why can I not set that variable to null?
Aside from anything to do with Nullable<T> (in this case, DateTime?), the error is happening specifically here:
((objectParsed.birthday != null) ? DateTime.Parse((string)objectParsed.birthday : null))
Note that there's no mention of a nullable DateTime in this code. And before the result of this code is assigned to a nullable DateTime, this code by itself needs to be evaluated. It can't be, because of the error you're seeing.
The operator being used (: ?) needs to be able to infer types from all arguments to the operation, and those types need to be able to match. Here you're passing it a DateTime and null which can't be matched. Try casting one of the arguments:
((objectParsed.birthday != null) ? (DateTime?)DateTime.Parse((string)objectParsed.birthday : null))
You can't set null in this case because ternary operator must return values same types
try this:
test = (objectParsed.birthday != null) ? (DateTime?)DateTime.Parse((string)objectParsed.birthday): null;
Try with
test = ((objectParsed.birthday != null) ? DateTime.Parse((string)objectParsed.birthday): null;
Explanation: the structure of a ternary operator is:
variable = (condition)?(value if yes):(value if no);
EnumType = reader["EnumTypeId"] == DBNull.Value ? EnumType.None : (EnumType)(int)reader["EnumTypeId"];
I thought if reader["EnumTypeId"] is null, it should assign the EnumType.None value, but it is still trying to cast the null value to an int which is obviously causing an exception.
I tried the following and it did not work either:
EnumType = reader["EnumTypeId"] == null ? EnumType.None : (EnumType)(int)reader["EnumTypeId"];
Instead of using Enums, I went ahead and decided to use a nullable int, so now my code is slightly different, but it still does not work with DBNull.Value, null, or GetOrdinal...
intType= reader["intType"] == DBNull.Value ? null : (int?)reader["intType"];
Also, why do I have to do a (int?) cast instead of just a (int) cast?
Don't use DBNull, just use plain old null.
EnumType = reader["EnumTypeId"] == null ? EnumType.None : (EnumType)(int)reader["EnumTypeId"];
Edit
The issue could be that the database type of EnumTypeId isn't an int/Int32. If so, then reading as a string and then parsing should fix the problem.
EnumType? enumVal = null;
if (reader["EnumTypeId"] != null)
{
int intVal;
enumVal = (int.TryParse(reader["EnumTypeId"].ToString(), out intVal)) ? (EnumType)intVal : null;
}
EnumType = ? EnumType.None : (EnumType)(int)reader["EnumTypeId"];
Another way you can use is IsDBNull method:
int index = reader.GetOrdinal("EnumTypeId");
EnumType = reader.IsDBNull(index) ? EnumType.None :
(EnumType)reader.GetInt32(index);
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 ??.