Updating a Bit Field with Null - c#

am getting this error once i try to update a bit field with null. please note that technically the bit is set to 'allow null'.
am getting this error :
'Object of type 'System.DBNull' cannot be converted to type 'System.Nullable`
When I do this :
e.NewValues.Add("IdleBlock", DBNull.Value);

Try using an actual null instead of DBNull.Value. As you can see in the error message it's trying to convert the latter into a null, so I'm guessing EF wants a proper null value and handle conversion on it's own.
Edit: Err, actually I think I'm wrong here. It wants a System.Nullable not a null. Try passing it a new System.Nullable with Value set to null?

Related

C# Error converting null value to type double during deserialization

Receiving this error message:
Error converting value {null} to type 'System.Double'. Path 'rings[0][0][3]', line 1, position 79.
The code producing the error:
string polygonGeom = geometry.ToJson();
GeoJSONClass.PolygonGeometry polygonGeometry = JsonConvert.DeserializeObject<GeoJSONClass.PolygonGeometry>(polygonGeom);
why can it not Deserialize the JSON produced?
As mentioned in the comment it is hard to answer without specific Type details. From the error it seems you are trying to map a value that can be null to a field declared as double.
Value types cannot be null. But if you need it to be null (maybe for optional fields) then use a nullable value type.
But since you are using an external type, make sure you handle the null values before passing it to sonConvert.DeserializeObject<GeoJSONClass.PolygonGeometry>(polygonGeom);

ASP.NET : EF 5.X - Conversion Error

I am trying to pull information out of a database and then add the values together. I have no issue when pulling the information out of the database however, there seems to be a conversion error when I am adding the values.
Cannot implicitly convert type 'double?' to 'double'. An explicit conversion exists (are you missing a cast?)
Outside where I am querying I have this:
var addition = 0.0;
When I pull the data out the Database, I try to add the value to this:
addition = addition + clear;
Both addition and clear are the same datatype which is why I am confused why it would need to do any conversion? (both Double's).
Extra information: clear comes from :
var clear = tbl_detail[a].AmountCleared;
and tbl_detail is an array of the queried data.
Could anyone possibly reference why I am receiving this error? Or possibly point me in the right direction because I am not understand why:
It needs to convert anything since they're the same datatype and
What a cast actually is because Google isn't really helping me when I am searching any of this.
It looks like AmountCleared is a nullable double (double?). You could do this:
addition += clear.Value
This will throw a InvalidOperationException if the Clear is null.
[Edit] You could also use addition += clear ?? 0.0 if you would like to use a default value for nulls.
You could change AmoutCleared into a double. I suspect that you created this through a designer or database first and used 'allow nulls' on the database column, which is why your are getting a nullable type. So you would have to change the database type to not 'allow nulls'. But without seeing the definition of the data type tbl_detail[a] or knowing how you generated it, I cannot help you much further.
AmountCleared is actually a Nullable type (Nullable) which allows C# value types to represent SQL server Nulls (Value types can never be assigned the value of null)
You can get the underlying value of the nullable type by simply calling .Value property, however this will throw a InvalidOperationException if the value is null, you can check if it has a value by calling .HasValue
Try this:
addition += clear.HasValue ? clear.Value : 0;
clear is a nullable value
to safely manipulate nullables use:
if(clear.hasValue)
{
addition += clear.Value;
}
You can also use the null coalescing operator ?? to fallback to a default value if the provided value is null
addition += clear ?? 0.0;

Valid ObservableCollection cast throws InvalidCastException

I am receiving an InvalidCastException for setting two types equal to each other. Thoughts on the particular behavior that might cause this?
Defining this.governanceTemplateList with the field definition does not change the exception.
Defining this.governanceTemplateList as a new ObservableCollection in the constructor throws the exact same exception.
The following code is in a WCF service library, using .NET 4.0.
Screenshots of Editor, Exception, Watch, and References.
SOLUTION:
Daniel Hilgarth is correct, it was the line of code above that was throwing the exception. I was casting a null value as a nullable value (DateTime?), but implicit casts cannot convert null values. In order to cast properly, you must use the AS keyword.
governanceTemplateTimestamp = (DateTime?)dr["GovernanceTemplateTimestamp"]; //Invalid
governanceTemplateTimestamp = dr["GovernanceTemplateTimestamp"] as DateTime?; //Valid
The exception is most likely happening at the line above. The line that is marked as the offending one isn't executing any cast.
I guess that GovernanceTemplateTimestamp is DBNull in your DataRow. DBNull can't be cast to DateTime?.

Is there a reason to cast to a type then to its nullable type?

So I just saw this line of code:
Item = (int?)(int)row["Item"];
Is there a reason it cant just be:
Item = (int?)row["Item"];
See Boxing Nullable Types (C#); an object can be directly cast to a nullable int (but it will cause an InvalidCastException if the object isn't actually an int). The one thing that the two casts will do that a direct cast to int? will not is perform an implicit check for null.
When casting to an int and then to a nullable int, an ICE will be thrown if the value of the object variable is null. When casting directly to a nullable int, null is handled just fine, but an InvalidOperationException will be thrown if code then attempts to retrieve the Value property without checking that there actually is one.
This looks like a half-assed attempt to "fail fast", and I would not recommend it as "good code". Simply cast directly to nullable, and then test the HasValue property and go from there.
I believe the proper way to write this line of code is this:
int val;
var success = int.TryParse(Convert.ToString(row["Item"]), out val);
Item = success ? (int?)val : (int?)null;
Item = (int?)(int)row["Item"];
this line throws exception in case row["Item"] is null. This bad idea, dont do it.
You can do use the as keyword.
Item = row["Item"] as int?;
You can actually cast null as the nullable type
Item = sdr.IsDBNull(sdr.GetOrdinal("Item")) ? (int?)null : (int)row["Item"];
Not really sure what exceptions this may cause, but I've used it without issue.

C# null - is it an object

When I was writing C# code a few days ago I noticed that the compiler complained that I had to cast null to a specific object.
Does this mean that null is simply an uninstantiated version of the type? Or is it a singleton value of a Null class like Java (even though it has special privileges)?
EDIT: an example of the code giving the error would be:
public String duplicate(String toDuplicate)
{
return toDuplicate + toDuplicate;
}
public String duplicate(int? toDuplicate)
{
String asString = toDuplicate.toString();
return asString + asString;
}
public static int Main(string[] args)
{
//This needs to be cast:
duplicate(null);
//To:
duplicate((string)null);
}
The reason I commented on null in Java was after reading this:
There is also a special null type, the
type of the expression null, which has
no name. Because the null type has no
name, it is impossible to declare a
variable of the null type or to cast
to the null type. The null reference
is the only possible value of an
expression of null type. The null
reference can always be cast to any
reference type. In practice, the
programmer can ignore the null type
and just pretend that null is merely a
special literal that can be of any
reference type.
Found here: Is null an Object?
I get the error you refer when i have overloaded methods and the compiler can't resolve which method to call at compile time. Is that it?
According to the MSDN description:
The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables. Ordinary value types cannot be null. However, C# 2.0 introduced nullable value types.
null is the "uninstanciated reference" for any type. It is not a value. null has no defined type.
No - the null is just a literal for the null reference.
The reason you need to "cast" it in this way (I put the word cast in quotes because you are not really casting an instance of anything), is purely to help the compiler resolve which overload of a method you are calling, or the method you are calling even exists.
In your example, you need to specify that you are calling the method "duplicate" that takes a single string argument. If you omit the cast, then the compiler only knows that the method you intended to call is called "duplicate" and has a single argument, but can't tell what type the argument is - did you mean to call duplicate(string) or did you mean to call duplicate(some other type)? Should it compile, or should it error telling you the method you are trying to call does not exist?
You will also get the same issue if you had a duplicate(byte[]) defined, because now your call is ambiguous without the explicit cast.
No its not an object. null is the default value of reference-type variables. Ordinary value types cannot be null. but there is another set called nullable types.
You are probably referring to the fact that the following leads to a compiler error:
int? nullableInt = (somecondition) ? value : null;
Indeed you need to add a cast here:
int? nullableInt = (somecondition) ? value : (int?)null;
Even though I'm not able to explain this in detail, I'd suspect the following:
int? is actually a short form for Nullable<int>, so it is basically an object instance. When assigning an int value to nullableInt, a property of Nullable<int> will be set internally. Directly assigning null would also be ok.
The conditional assignment however, would return two different types: int in case somecondition is true and object (null) otherwise.
Now the compiler doesn't know how to handle this, as the ternary operator needs to return values of the same type. So you need to specify the desired "type for the null value".
Sorry if this is not a very deep technical explanation - I'm sure there's somebody who can elaborate this better, but it might help understand this better.

Categories

Resources