views:

524

answers:

10

I have been repeatedly asked these question in many interviews.... But still can't able to explain them with a simple example...

What is nullable types in c#?When should one use nullable types in c#?Any simple ex?

Any suggestion....

+11  A: 

Null means "no value" or "no data". You use nullable types when "no value" is a valid value in the context of whatever system you are desining/using.

int? weightOfCargo = TryGetTruckCargoWeight()

In this case, the nullable type indicates that TryGetTruckCargoWeight() may return null. The meaning of this would genereally be that the data is unavailable (maybe there's no truck, maybe it hasn't been weighed, etc).

Sander
+15  A: 

From Using Nullable Types (C# Programming Guide)

For an example of when you might use a nullable type, consider how an ordinary Boolean variable can have two values: true and false. There is no value that signifies "undefined". In many programming applications, most notably database interactions, variables can exist in an undefined state. For example, a field in a database may contain the values true or false, but it may also contain no value at all. Similarly, reference types can be set to null to indicate that they are not initialized.

astander
+6  A: 

Consider following example:

A tool has settings specified via the UI. However, the tool can also be run from the command-line and the settings specified in the UI can be overridden via the commandline. So the code is as follows :

bool? setting1;

...Process command line, if setting specified do:

setting1.Value = setting;

...later

if(setting1.HasValue)
  ui.setting1 = setting1.Value
logicnp
+2  A: 

Whenever you are using designated values to represent a null value:
* A DateTime minimumvalue to represent a value of nothing
* -1 to represent an unset value for an integer
then a nullable type would be a better choice.

Kb
+1  A: 
// to replace   
// if(foo.Id > 0)
if(foo.Id.HasValue)
{
    Update(foo);
}
else
{
    Insert(foo);
}
Mika Kolari
+1  A: 

Hi Mr Pandiya Chendur,

AS we all know there are two different types in C#

•Refrence type
•Value type
Reference type can be represent as non existent value (NULL) but Vaue type , however cannot represent NULL value.
For e.g

Since String is value type you can declare it as null

 String s=null;  //ok

But if you try to declare value type such as Int32 to null it produceses compiler error

Int32 i=null;    // compiler error

To represent null in a value type, you must use a special construct called a nullable type. It is represented using ? symbol.

Int32? I=null; //now its ok

Now scenario when nullable types commanly used is in database programming where calss is map to table with nullable columns.
• If the columns are reference type that is String such as (email address and customer address), there is not a problem as you can defined it as null in C#
• But if the columns are value type that is double such as (customer account balance), you cannot map it to C# without using nullable types.
For e.g
// maps to a Customer table in a database


public class Customer
{
  ...
  public decimal? AccountBalance;
}
vijay shiyani
@Vijay: string is a reference type. Not a value type
Jehof
+1  A: 

C# has two type of data types. Value type and reference types. String is reference type and int is value type. A reference type can be assigned with a null value like string s = null; But you can not assign a null value direcly to a inteer. like int a = null // So to make the value type accept a null value, nullable types are used. To make it nullable, a ? is added . in ? a = null;//ok.

Shetty
A: 

See this answers.

May be you can get some idea.

JMSA
A: 

I think if we talk about real world scenario when your Database table contains nullable columns in it and you need to create DTOs(Data Transfer Objects) as Db Entity mapping. In such scenarios you need to get exact same datatype mapping in you Entity classes, To achieve such requirement nullable types are really very useful to create exactly same mapping and allow user to easily work in this senario.

Regards.

Shoaib Shaikh
+1  A: 

One more example:

imagine, you need to create a GetArticles method in your BLL. This method should take such arguments as date period (from and to arguments), search string (search argument) and document category (categoryId argument). All these arguments are optional. So in one case you want to define only from and search argument, in other only categoryId argument.

To do this you may create a lot of overloads for GetArticles method with necessary arguments combination. The other way is to define the only one method GetArticles(DateTime? from, DateTime? to, string search, int? categoryId) for this. In this case if argument is null it will be skipped.

Of cause I know about a new feature in .NET 4.0 called optional parameters and named arguments but before this it was a nice workaround for me.

Alex