when we have to use nullable type in C#.net? could any one please explain with example.
Nullable types are a feature of some programming languages which allow a value to be set to the special value NULL instead of the usual possible values of the data type.
A type is said to be nullable if it can be assigned a value or can be assigned null, which means the type has no value whatsoever.
You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.
Nullable variables may either contain a valid value or they may not — in the latter case they are considered to be nil . Non-nullable variables must always contain a value and cannot be nil . In Oxygene (as in C# and Java), the default nullability of a variable is determined by its type.
Nullable types (When to use nullable types) are value types that can take null as value. Its default is null
meaning you did not assign value to it. Example of value types are int, float, double, DateTime, etc. These types have these defaults
int x = 0;
DateTime d = DateTime.MinValue;
float y = 0;
For Nullable alternatives, the defualt of any of the above is null
int? x = null; //no value
DateTime? d = null; //no value
This makes them behave like reference types e.g. object, string
string s = null;
object o = null;
They are very useful when dealing with values from database, when values returned from your table is NULL
. Imagine an integer value in your database table that could be NULL, such can only be represented with 0
if the c# variable is not nullable - regular integer.
Also, imagine an EndDate
column whose value is not determined until an actual time in future. That could be set to NULL in the DB but you'll need a nullable type to store that in C#
DateTime StartDate = DateTime.Today;
DateTime EndDate? = null; //we don't know yet
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With