Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
99 views
in Technique[技术] by (71.8m points)

What is nullable type in c#?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...