Why does DBNull.Value not work here? - c#

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);

Related

C# System.InvalidCastException: Specified Cast is not valid

I've been struggling with one problem these past few hours.
I keep getting an error and it tells me that the specified cast is not valid. I'm able to change the values on the database using the stored procedure. However, when I try doing it with the executable I get that error.
This is the error
System.InvalidCastException: Specified cast is not valid.
at Administrator_Panel.DB.ReadAccountInfo(String UserID, In32& Count)
This is the code.
public static Account ReadAccountInfo(string UserID, out int Count)
if (Reader.Read())
ReturnValue = new Account((int)Reader["UserUID"],
(string)Reader["Pw"],
(bool)Reader["Admin"],
(bool)Reader["Staff"],
(short)Reader["Status"],
(int)Reader["Point"],
(int)Reader["DaemonPoints"]);
Any help would be appreciated. :) Thank you
See this answer: How to (efficiently) convert (cast?) a SqlDataReader field to its corresponding c# type?
You can't just cast SqlDataReader fields to their corresponding value types because of the possibility of nulls. You can use nullable types but it's likely your Account object isn't setup to take nullable types.
One way you can try to handle this is to add null checking:
ReturnValue = new Account(Reader["UserUID"] == DBNull.Value ? 0 : (int)Reader["UserUID"] ,
Reader["Pw"] == DBNull.Value ? "" : Reader["Pw"].ToString(),
Reader["Admin"] == DBNull.Value ? false : (bool)Reader["Admin"],
Reader["Staff"] == DBNull.Value ? false : (bool)Reader["Staff"],
Reader["Status"] == DBNull.Value ? (short) 0 : (short)Reader["Status"],
Reader["Point"] == DBNull.Value ? 0 : (int)Reader["Point"],
Reader["DaemonPoints"] == DBNull.Value ? 0 : (int)Reader["DaemonPoints"]);

how to check JsonObject has null value(windows.data.json)

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();

How to return a null value from a database

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

Assigning `null` value to Nullable<DateTime> with single line 'if'

I have a Class like this
public class MyClass
{
public int Id { get; set; }
public Nullable<DateTime> ApplicationDate { get; set; }
....
}
Now I'm trying to fill an object of MyClass like this
DataTable dt = DBHelper.GetDataTable(sql, conn);
DataRow dr = dt.Rows[0];
MyClass oMyClass = new MyClass();
oMyClass.Id = (int)dr["Id"];
oMyClass.ApplicationDate = dr["ApplDate"] == DBNull.Value ? null : Convert.ToDateTime(dr["AppDate"]);
//Above line gives an error
....
Assigning of Application Date value gives an error
Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'System.DateTime'
What am I missing here?
You need to cast null to DateTime?:
oMyClass.ApplicationDate = dr["ApplDate"] == DBNull.Value
? (DateTime?)null
: Convert.ToDateTime(dr["AppDate"]);
This is because of the way the compiler determines the resulting type of the conditional operator; the behavior is by design:
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.
Since null by itself is of null type and thus there is no conversion from or to it, you need to help the compiler by casting.
oMyClass.ApplicationDate =
dr["ApplDate"] == DBNull.Value ?
(DateTime?)null :
Convert.ToDateTime(dr["AppDate"]);
All the compiler knows is that one thing evaluates to a null and the other evaluates to a DateTime. The compiler complains because it can't convert from one to the other so it's up to you to cast them to something that can be both values.
Note that DateTime? is short for Nullable<DateTime>.
Also note that you only need to cast the null value as there is an implicit conversion between DateTime? and DateTime so the compiler can do that conversion its self.
try this:
oMyClass.ApplicationDate =
dr["ApplDate"] == DBNull.Value ? (DateTime?)null :
Convert.ToDateTime(dr["AppDate"]);
You can also apply the cast to the last expression.
You can use default which will assign the default value of an uninitialized Type.
oMyClass.ApplicationDate = dr["ApplDate"] == DBNull.Value ? default(Nullable<DateTime>) : Convert.ToDateTime(dr["AppDate"]);
More examples
bool isHappy = default(bool); //isHappy = false
int number = default(int); //number = zero
string text = default(text); // text = null
MyObject myObject = default(MyObject); // myObject = null
DateTime? date = default(DateTime?); //date = null
You will need to convert "null" into Nullable
Try this code:
oMyClass.ApplicationDate = dr["ApplDate"] == DBNull.Value ? (DateTime?)null : Convert.ToDateTime(dr["AppDate"]);
DateTime? dt = (DateTime?)null;
or
Nullable<DateTime> dt = (Nullable<DateTime>)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;

Categories

Resources