Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is nullable type in c#?

Tags:

c#

when we have to use nullable type in C#.net? could any one please explain with example.

like image 495
tgranjith Avatar asked Nov 05 '12 18:11

tgranjith


People also ask

What do you mean by nullable type?

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.

What is difference between null and nullable?

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.

How do you use Nullable types?

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.

What is nullable and non-nullable?

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.


1 Answers

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
like image 68
codingbiz Avatar answered Oct 05 '22 12:10

codingbiz