Check if decimal value is null - c#

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

Related

What is the best way of getting default value from Type

I have Type and I want to get the default value. For example, if Type is class or nullable I should get null. But if it is integer, DateTime. decimal, ... I should get 0. What is the best way of doing this?
From your description you can just use a default expression or literal.
int a = default(int);
int a = default;
Default values of C# types (C# reference)
Type
Default value
Any reference type
null
Anybuilt-in integral numeric type
0 (zero)
Any built-in floating-point numeric type
0 (zero)
bool
false
char
'\0' (U+0000)
enum
The value produced by the expression (E)0, where E is the enum identifier.
struct
The value produced by setting all value-type fields to their default values and all reference-type fields to null.
Any nullable value type
An instance for which the HasValue property is false and the Value property is undefined. That default value is also known as the null value of a nullable value type.
I expect you can use something like this:
public static object GetDefaultValue(Type type)
{
return type.IsClass ? null : Activator.CreateInstance(type);
}
Try it online
You could use Activator.CreateInstance to generate an empty variable of the type and then check the value of it :)

Object cannot be cast from DBNull to other types error shown?

My code is this
private MyCatch _catch = new MyCatch("Description");
decimal getTotalValue(GridView view, int listSourceRowIndex)
{
decimal unitPrice = Convert.ToDecimal(view.GetListSourceRowCellValue(listSourceRowIndex, "Each")); //Object cannot be cast from DBNull to other types
decimal quantity = Convert.ToDecimal(view.GetListSourceRowCellValue(listSourceRowIndex, "Quantity"));
decimal discount = Convert.ToDecimal(view.GetListSourceRowCellValue(listSourceRowIndex, "TaxPercentage"));
return unitPrice * quantity * (1 - discount);
}
private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
{
GridView view = sender as GridView;
if (e.Column.FieldName == "Totalototal" && e.IsGetData) e.Value =
getTotalValue(view, e.ListSourceRowIndex);
}
Here I assume, in case of Null it set the unitPrice to 0.
decimal unitPrice = view.GetListSourceRowCellValue(listSourceRowIndex, "Each") == DBNull.Value
? 0
: Convert.ToDecimal(view.GetListSourceRowCellValue(listSourceRowIndex, "Each"));
If there can be null value try using nullable types.
decimal? unitPrice = ...
A nullable type is a value type that accepts null as a value. You can then check value
if (unitPrice.HasValue) // is there a value or null?
unitPrice.Value // do something with the value
More about nullables on MSDN.
But I assume that null should not be received, it would make the calculation impossible. Therefore I would advise to encapsulate fetching values in a try/catch block instead and return from method if some of the calls throws an exception.
The Problem is beacuse , the data values that are being fetched from may contain DBNull values which means that value does not exists.
So, it makes not sense in changing the type of the value that has not existed.
The solution to allow null is , declare the variable as nullable types that means they are capable of accepting null values.
The synatax is:
datatype? variablename
Hopw this helps..
you can use TryParse method to identify whether cast is possible from given value to decimal or not.if not possible assign the DBNull.Value
Syntax: decimal.TryParse(value,out parameter)
the above function return true if the value can be castable to decimal
return false when casting is not possible
when you need to insert Null into table column you should insert DBNull.Value from the code.
so you can send DBNull.Value when the casting is not possible.
Note: here i have used ternary ?: operator to write the whole thing in single line
Solution:
decimal result;
decimal unitPrice =(decimal.TryParse(view.GetListSourceRowCellValue(listSourceRowIndex, "Each"),out result))?result:DBNull.Value;
I am programming ASP.net VB using GridView with RowDataBound event, in some rows I have nulls from database:
If e.Row.RowType = DataControlRowType.DataRow Then
If (DataBinder.Eval(e.Row.DataItem, "MyField") IsNot DBNull.Value) Then
myTotal += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "MyField"))
End If
End If

How can someone handle default datetime

I have DAL where I convert database null value to their equivalent representation in C#. For example:
NULL for Numeric = 0
NULL for String = String.Empty
NULL for DateTime = "1/1/0001" (i.e. DateTime.MinValue)
The problem, for date, lies in the presentation layer, especially in GridViews. You cannot show 1/1/01 to users.
What I used to do is check if myDate.Year=1 or myDate.Year < AcceptedDate and display empty string, but seems to be extra effort unlike other types
Please am open to better approach. Thanks.
Use Nullable datatype to store null value.
DateTime? value = null;
int? myNullableInt = 1;
value = DateTime.Now;
How to check whether variable has value or null
if (value!=null)
String value can store null, so there is no diffrent datatype for string to store null.
string var;
if (var == null)
or
if (String.IsNullOrEmpty(var))
You can also use DateTime.MinValue constant.
http://msdn.microsoft.com/en-us/library/system.datetime.minvalue.aspx
Your conditions would be:
if (myDate == DateTime.MinValue)
You can use Nullable DateTime, so you will return DateTime? instead of DateTime from your DAL. This way you can check if returned value is null.
DateTime? dateTime = null;
As the others mention, you could use a System::Nullable<DateTime>.
The other approach I've seen is to use a standard DateTime and just use a special value such as DateTime.MinValue. This is useful if you need to honor an existing interface's types and can't change the DateTime to a Nullable<DateTime>.
You can either use a Nullable DateTime as the others suggested, or use this trick:
(To prevent non valid defaults.)
// If dateTime has not been initialize, initialize to Now
// (or to any other legal inital values)
dateTime = ((dateTime != new DateTime()) ? dateTime : DateTime.Now);
This trick is useful if you have to use a non-nullable DateTime and want to provide a default if none. (E.g. you have a non-nullable DateTime column in a DB and want to set the value only if row is new.)
I don't think you have much choice but to make the check like you have been and display accordingly. A nullable type might make things easier for you. Depending on your data, even the numeric should be treated this way. DBNull != 0.

What is 'long?' data type?

I am going over some code written by another developer and am not sure what long? means:
protected string AccountToLogin(long? id)
{
string loginName = "";
if (id.HasValue)
{
try
{....
long is the same as Int64
long data type
The ? means it is nullable
A nullable type can represent the
normal range of values for its
underlying value type, plus an
additional null value
Nullable Types
Nullable example:
int? num = null;
if (num.HasValue == true)
{
System.Console.WriteLine("num = " + num.Value);
}
else
{
System.Console.WriteLine("num = Null");
}
This allows you to actually check for a null value instead of trying to assign an arbitrary value to something to check to see if something failed.
I actually wrote a blog post about this here.
long is an Int64, the ? makes it nullable.
"long?" is a nullable 64-bit signed integer. It's equivalent to Nullable<Int64>.
long? is a 64-bit, nullable integer.
To clarify, nullable means it can be null or an integer number ( 0, 1, etc.).
long? is a nullable type. This means that the id parameter can have a long value or be set to null. Have a look at the HasValue and Value properties of this parameter.
It's a nullable type declaration.

What is the purpose of a question mark after a value type (for example: int? myVariable)?

Typically the main use of the question mark is for the conditional, x ? "yes" : "no".
But I have seen another use for it but can't find an explanation of this use of the ? operator, for example.
public int? myProperty
{
get;
set;
}
It means that the value type in question is a nullable type
Nullable types are instances of the System.Nullable struct. A
nullable type can represent the correct range of values for its
underlying value type, plus an additional null value. For example, a
Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any
value from -2147483648 to 2147483647, or it can be assigned the null
value. A Nullable<bool> can be assigned the values true, false, or
null. The ability to assign null to numeric and Boolean types is
especially useful when you are dealing with databases and other data
types that contain elements that may not be assigned a value. For
example, a Boolean field in a database can store the values true or
false, or it may be undefined.
class NullableExample
{
static void Main()
{
int? num = null;
// Is the HasValue property true?
if (num.HasValue)
{
System.Console.WriteLine("num = " + num.Value);
}
else
{
System.Console.WriteLine("num = Null");
}
// y is set to zero
int y = num.GetValueOrDefault();
// num.Value throws an InvalidOperationException if num.HasValue is false
try
{
y = num.Value;
}
catch (System.InvalidOperationException e)
{
System.Console.WriteLine(e.Message);
}
}
}
It is a shorthand for Nullable<int>. Nullable<T> is used to allow a value type to be set to null. Value types usually cannot be null.
In
x ? "yes" : "no"
the ? declares an if sentence. Here: x represents the boolean condition; The part before the : is the then sentence and the part after is the else sentence.
In, for example,
int?
the ? declares a nullable type, and means that the type before it may have a null value.
it declares that the type is nullable.
practical usage:
public string someFunctionThatMayBeCalledWithNullAndReturnsString(int? value)
{
if (value == null)
{
return "bad value";
}
return someFunctionThatHandlesIntAndReturnsString(value);
}
int? is shorthand for Nullable<int>. The two forms are interchangeable.
Nullable<T> is an operator that you can use with a value type T to make it accept null.
In case you don't know it: value types are types that accepts values as int, bool, char etc...
They can't accept references to values: they would generate a compile-time error if you assign them a null, as opposed to reference types, which can obviously accept it.
Why would you need that?
Because sometimes your value type variables could receive null references returned by something that didn't work very well, like a missing or undefined variable returned from a database.
I suggest you to read the Microsoft Documentation because it covers the subject quite well.
Means that the variable declared with (int?) is nullable
int i1=1; //ok
int i2=null; //not ok
int? i3=1; //ok
int? i4=null; //ok
To add on to the answers above, here is a code sample
struct Test
{
int something;
}
struct NullableTest
{
int something;
}
class Example
{
public void Demo()
{
Test t = new Test();
t = null;
NullableTest? t2 = new NullableTest();
t2 = null;
}
}
This would give a compilation error:
Error 12 Cannot convert null to 'Test' because it is a non-nullable
value type
Notice that there is no compilation error for NullableTest. (note the ? in the declaration of t2)
To add on to the other answers:
Starting in C# 8.0, Nullable<> and ? are NOT always interchangeable. Nullable<> only works with Value types, whereas ? works with both Reference and Value types.
These can be seen here in the documentation
"A nullable reference type is noted using the same syntax as nullable
value types: a ? is appended to the type of the variable."
And here
public struct Nullable<T> where T : struct

Categories

Resources