Assign null to decimal using ternary operator - c#

I am using conversion to decimal of a byte array, such that it contains either null or any other number, stored in byte. The problem here is, when I try to convert a null to Nullable decimal, it converts it to zero. I want it to remain null...
Convert.ToDecimal(obj.sal== null ? null : System.Text.Encoding.ASCII.GetString(obj.sal))

If you want the result to potentially be null, then you shouldn't be calling Convert.ToDecimal - which always returns decimal. Instead, you should use:
x = obj.sal == null ? (decimal?) null
: Convert.ToDecimal(Encoding.ASCII.GetString(obj.sal));
Note that you have to cast the null literal to decimal? - or use some other form like default(decimal?) so that the type of the second operand is decimal? - otherwise the compiler won't be able to infer the type of the conditional expression. See this question for more details on that.

Because null is of type object (effectively untyped) and you need to assign it to a typed object.
x = obj.sal == null ? (decimal?) null
: Convert.ToDecimal(Encoding.ASCII.GetString(obj.sal));

Related

Checking if a List is Null before getting Count results in -> Cannot implicitly convert type 'int?' to 'int

I'm trying to find the number of items present in a list.In order to prevent the null exception.I'm using the ? operator to check whether myBenchmarkMappings is null before getting its count.
int benchmarkAccountCount =portfolioWrapper.myBenchmarkMappings?.Count;
But this results in Cannot implicitly convert type 'int?' to 'int'. exception
What am i doing wrong ?
This is because the ? operator will return the value or null. And you can't assign null to int.
You have two options. First is to mark the int as nullable.
But in this case latter you will need to check if the int is null.
int? benchmarkAccountCount = portfolioWrapper.myBenchmarkMappings?.Count;
if (benchmarkAccountCount == null)
{
// null handling
}
The second option, which I think is better, you can user the null-coalescing operator ?? and give the benchmarkAccountCount a default value in case the list is null.
int benchmarkAccountCount = portfolioWrapper.myBenchmarkMappings?.Count ?? 0;
When .myBenchmarkMappings is null, then .myBenchmarkMappings?.Count is also null. This means this code could possibly assign a null to an int, but an int can't store a null. Change the type to int? if you want to accommodate an int or null.
int? benchmarkAccountCount = portfolioWrapper.myBenchmarkMappings?.Count;
You can try to use ?: operator to check if list is null:
int benchmarkAccountCount =portfolioWrapper.myBenchmarkMappings!=null ? portfolioWrapper.myBenchmarkMappings.Count:0;

How to send in "NULL/DbNull" into a table-column with the datatype: nullable int

I got a table in sql-server 2012 with a column that is the datatype int but also nullable.
I've a textbox that when left empty should insert NULL into the nullable int cell. But I'm having trouble with what type to send in to be translated as null. What I want is a datatype of int but also null (int?) to send into the database.
var tbl_row = db.table.Where(n => n.key.Equals(key)).SingleOrDefault();
tbl_row.nullable_int = this.tb.Text == "" ? [null int value] : int.Parse(this.tb.Text);
You should write:
tbl_row.nullable_int = this.tb.Text == "" ? (int?)null : int.Parse(this.tb.Text);
for the conditional operator expression to be valid.
According to 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.
In your case, null and an expression evaluated as an int confused the compiler. By explicitly casting the first expression to int?, there is now a way for it to figure out how to evaluate the conditional expression.
There is a singleton instance of a DBNull class. Try assingning DBNull.Value

Check if decimal value is null

I would like to check if the decimal number is NULL or it has some value, since the value is assigned from database in class object:
public decimal myDecimal{ get; set; }
and then I have
myDecimal = Convert.ToDecimal(rdrSelect[23].ToString());
I am trying:
if (rdrSelect[23] != DBNull.Value)
{
myDecimal = Convert.ToDecimal(rdrSelect[23].ToString());
}
But I am getting this:
the result of the expression is always 'true' since a value of type
'decimal' is never equal to null
How can I check if that decimal number has some value?
A decimal will always have some default value. If you need to have a nullable type decimal, you can use decimal?. Then you can do myDecimal.HasValue
you can use this code
if (DecimalVariable.Equals(null))
{
//something statements
}
decimal is a value type in .NET. And value types can't be null. But if you use nullable type for your decimal, then you can check your decimal is null or not. Like myDecimal?
Nullable types are instances of the System.Nullable struct. A nullable
type can represent the normal range of values for its underlying value
type, plus an additional null value.
if (myDecimal.HasValue)
But I think in your database, if this column contains nullable values, then it shouldn't be type of decimal.
I've ran across this problem recently while trying to retrieve a null decimal from a DataTable object from db and I haven't seen this answer here. I find this easier and shorter:
var value = rdrSelect.Field<decimal?>("ColumnName") ?? 0;
This was useful in my case since i didn't have a nullable decimal in the model, but needed a quick check against one. If the db value happens to be null, it'll just assign the default value.
Assuming you are reading from a data row, what you want is:
if ( !rdrSelect.IsNull(23) )
{
//handle parsing
}
Decimal is a value type, so if you wish to check whether it has a value other than the value it was initialised with (zero) you can use the condition myDecimal != default(decimal).
Otherwise you should possibly consider the use of a nullable (decimal?) type and the use a condition such as myNullableDecimal.HasValue
If you're pulling this value directly from a SQL Database and the value is null in there, it will actually be the DBNull object rather than null. Either place a check prior to your conversion & use a default value in the event of DBNull, or replace your null check afterwards with a check on rdrSelect[23] for DBNull.
You can also create a handy utility functions to handle values from DB in cases like these.
Ex. Below is the function which gives you Nullable Decimal from object type.
public static decimal? ToNullableDecimal(object val)
{
if (val is DBNull ||
val == null)
{
return null;
}
if (val is string &&
((string)val).Length == 0)
{
return null;
}
return Convert.ToDecimal(val);
}

Why doesn't attempting to add to a null value throw an InvalidOperationException?

int? x = null;
x = x + 1; // Works, but x remains null
I would expect the compiler to attempt to cast x as an int, but apparently it does not.
Edit by 280Z28: Changed NullReferenceException to InvalidOperationException, which is what Nullable<T>.Value throws when HasValue is false.
This is per the specification for lifted binary operators. From §7.2.7:
For the binary operators
+ - * / % & | ^ << >>
a lifted form of an operator exists if the operand and result types are all non-nullable value types. The lifted form is constructed by adding a single ? modifier to each operand and result type. The lifted operator produces a null value if one or both operands are null (an exception being the & and | operators of the bool? type, as described in §7.10.3). Otherwise, the lifted operator unwraps the operands, applies the underlying operator, and wraps the result.
The reasoning is this: you are to think of null for a nullable type as meaning "I do not know what the value is." What is the result of "I don't know" plus one? "I don't know." Thus, the result should be null.
Nullables are never actually null references. They are always object references. Their internal classes override the == and = operators. If they are being compared to null, they'll return the value of the HasValue property.
Why would you expect the compiler to cast it as int when you've declared it as Nullable? The compiler is doing what you've told it to do and null +1 = null.
You'll have to cast explicitly or check x.HasValue before attempting to add an int.
The reason for this is that the compiler creates a 'lifted' operator for nullable types - in this case it is something like:
public static int? operator +(int? a, int? b)
{
return (a == null || b == null) ? (int?)null : a.Value + b.Value
}
I think if you try to assign the result to a non-nullable value, the compiler will be forced to use the non-nullable overload and convert x to an int.
e.g. int i = x + 1; //throws runtime exception
Unfortunately it doesn't. The X in x = X + 1 is null as in the first line so you're adding 1 to null, which equals null.
As it's a nullable int, you can use x.HasValue to check if it has a value, and then x.Value to get the actual int value out
Regardless of whether x is actually never null, that's not even the point.
The point is, when have you ever seen a NullReferenceException when trying to perform an addition?
The following example doesn't throw a NullReferenceException either and is perfectly valid.
string hello = null;
string world = "world";
string hw = hello+world;
You would only get a NullReferenceException if you try to access a member on an object that is null.
int? can never be null because it is a struct. Structs live on the stack and the stack does not handle null well.
See What is a NullPointerException, and how do I fix it?
Also, the nullable types have 2 very useful properties : HasValue, Value
This code:
if (x != null)
{
return (int) x;
}
Should be refactored to this:
if (x.HasValue)
{
return x.Value;
}

Casting with conditional/ternary ("?:") operator

I have this extract of C# source code:
object valueFromDatabase;
decimal result;
valueFromDatabase = DBNull.Value;
result = (decimal)(valueFromDatabase != DBNull.Value ? valueFromDatabase : 0);
result = (valueFromDatabase != DBNull.Value ? (decimal)valueFromDatabase : (decimal)0);
The first result evaluation throws an InvalidCastException whereas the second one does not.
What is the difference between these two?
UPDATE: This question was the subject of my blog on May 27th 2010. Thanks for the great question!
There are a great many very confusing answers here. Let me try to precisely answer your question. Let's simplify this down:
object value = whatever;
bool condition = something;
decimal result = (decimal)(condition ? value : 0);
How does the compiler interpret the last line? The problem faced by the compiler is that the type of the conditional expression must be consistent for both branches; the language rules do not allow you to return object on one branch and int on the other. The choices are object and int. Every int is convertible to object but not every object is convertible to int, so the compiler chooses object. Therefore this is the same as
decimal result = (decimal)(condition ? (object)value : (object)0);
Therefore the zero returned is a boxed int.
You then unbox the int to decimal. It is illegal to unbox a boxed int to decimal. For the reasons why, see my blog article on that subject:
Representation and Identity
Basically, your problem is that you're acting as though the cast to decimal were distributed, like this:
decimal result = condition ? (decimal)value : (decimal)0;
But as we've seen, that is not what
decimal result = (decimal)(condition ? value : 0);
means. That means "make both alternatives into objects and then unbox the resulting object".
The difference is that the compiler can not determine a data type that is a good match between Object and Int32.
You can explicitly cast the int value to object to get the same data type in the second and third operand so that it compiles, but that of couse means that you are boxing and unboxing the value:
result = (decimal)(valueFromDatabase != DBNull.value ? valueFromDatabase : (object)0);
That will compile, but not run. You have to box a decimal value to unbox as a decimal value:
result = (decimal)(valueFromDatabase != DBNull.value ? valueFromDatabase : (object)0M);
The type of the operator will be object and in case the result must be 0 it will be implicitly boxed. But 0 literal is by default has int type so you box int. But with explicit cast to decimal you try to unbox it which is not permitted (boxed type must much with the one you cast back to). That is why you can get exception.
Here is an excerpt from C# Specification:
The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,
If X and Y are the same type, then this is the type of the conditional expression.
Otherwise, if an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the
conditional expression.
Otherwise, if an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the
conditional expression.
Otherwise, no expression type can be determined, and a compile-time error occurs.
Your line should be:
result = valueFromDatabase != DBNull.value ? (decimal)valueFromDatabase : 0m;
0m is the decimal constant for zero
Both parts of a conditional operator should evaluate to the same data type
The x : y part need a common type, the database's value is likely some kind of float and 0 is an int. This happens before the cast to decimal. Try ": 0.0" or ": 0D".
Unless I'm mistaken (which is very possible) its actually the 0 that's causing the exception, and this is down to .NET (crazily) assuming the type of a literal so you need to specify 0m rather than just 0.
See MSDN for more info.
There are two different types for the compiler to decide (at compile time) which one to cast to decimal. This it can't do.
Your answer would work if you combined both:
result = (decimal)(valueFromDatabase != DBNull.Value ? (decimal)valueFromDatabase : (decimal)0);
At least, a similar situation casting into a parameter for me.

Categories

Resources