When should one use nullable types in c#?
Asked Answered
B

10

41

I have been repeatedly asked the following questions in many interviews.... But still can't explain them with a simple example...

  1. What are nullable types in c#?
  2. When should one use nullable types in c#?
  3. Can you give a simple example?

Any suggestions?

Biplane answered 13/4, 2010 at 5:2 Comment(1)
possible duplicate of #1551409Theomorphic
B
36

From Using Nullable Types (C# Programming Guide) (Link updated circa 2018)

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.

Bricebriceno answered 13/4, 2010 at 5:6 Comment(1)
but any references (object for instance) can be null. so, instead boxing a bool in Nullable why don't box it in Boolean it still make me wonder why..Spoonfeed
W
26

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).

Whim answered 13/4, 2010 at 5:5 Comment(0)
F
11

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
Filia answered 13/4, 2010 at 5:11 Comment(1)
Good example of a tool in UI vs CLI!Cosh
B
5

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.

Bodice answered 13/4, 2010 at 5:16 Comment(0)
H
5

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 reference 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;
}
Hairpin answered 13/4, 2010 at 5:26 Comment(2)
@Vijay: string is a reference type. Not a value typeIsmaelisman
Small correction: there's actually three different types. What about Pointer Types? :) msdn.microsoft.com/en-us/library/y31yhkeb.aspxStumer
C
4

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 directly to a integer. 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

int? a = null;//ok.
Celebrant answered 13/4, 2010 at 5:34 Comment(0)
H
4

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.

Hieroglyphic answered 15/4, 2010 at 8:29 Comment(0)
T
1
// to replace   
// if(foo.Id > 0)
if(foo.Id.HasValue)
{
    Update(foo);
}
else
{
    Insert(foo);
}
Tympany answered 13/4, 2010 at 5:18 Comment(0)
S
1

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.

Showery answered 13/4, 2010 at 7:0 Comment(0)
W
0

Nullable types are used to hold variables whose values are null at runtime. Its important because some table fields during insert operations are not initially determined. Nullable types come in handy here.

Worcestershire answered 2/1, 2023 at 7:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.