#566 – Implicit Conversions to Nullable Types

A nullable type represents a type whose value can be either a particular value type or can be the null value.

int i = 12;   // regular int, can't be null

int? j = 22;  // Nullable int, can store an int value
j = null;     // Can also store null value

You can implicitly convert from the corresponding value type to its matching nullable type.  For example, you can convert from an object of type int to an object of type int?

int i = 12;
int? j = i;   // Implicit conversion from int to int?

float f1 = i;   // Implicit conversion from int to float
float? f2 = i;  // Implicit conversion from int -> float -> float?

You can also implicitly convert from the null value to any nullable type.

int? i = null;
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #566 – Implicit Conversions to Nullable Types

  1. Pingback: #1,045 – Implicit Conversions When Assigning from a Nullable Type | 2,000 Things You Should Know About C#

  2. Pingback: #1,050 – Implicit Conversions between Nullable Types | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: