581

How do I convert a nullable int to an int? Suppose I have 2 type of int as below:

int? v1;  
int v2; 

I want to assign v1's value to v2. v2 = v1; will cause an error. How do I convert v1 to v2?

Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
KentZhou
  • 24,805
  • 41
  • 134
  • 200

20 Answers20

766

The other answers so far are all correct; I just wanted to add one more that's slightly cleaner:

v2 = v1 ?? default(int);

Any Nullable<T> is implicitly convertible to its T, PROVIDED that the entire expression being evaluated can never result in a null assignment to a ValueType. So, the null-coalescing operator ?? is just syntax sugar for the ternary operator:

v2 = v1 == null ? default(int) : v1.Value;

...which is in turn syntax sugar for an if/else:

if(v1==null)
   v2 = default(int);
else
   v2 = v1.Value;

Also, as of .NET 4.0, Nullable<T> has a "GetValueOrDefault()" method, which is a null-safe getter that basically performs the null-coalescing shown above, so this works too:

v2 = v1.GetValueOrDefault();
Medinoc
  • 6,577
  • 20
  • 42
KeithS
  • 70,210
  • 21
  • 112
  • 164
  • 5
    Is `default(int)` really needed? What's wrong with a simple `0`? – Cole Tobin Mar 20 '15 at 23:07
  • 6
    It would work for this example, but in the general case it's recommended to use `default` where appropriate. Zero isn't always valid as a value, much less the default, so if you replace `int` with a generic `T` you'll find my code works while zero doesn't. In some future framework version, `default` may also become overloadable; if and when that happens, code using default will be easily able to take advantage, while explicit null or zero assignments will have to be changed. – KeithS Mar 23 '15 at 14:35
  • 17
    This should rise to the top: .NET 4.0, Nullable has a "GetValueOrDefault()" – RandomHandle Jun 28 '17 at 18:51
  • Thanks for coming back to edit it with GetValueOrDefault! – CindyH May 18 '18 at 23:06
  • You may want to be careful with DateTime when you use default. This might insert the default date instead of empty. – Ranch Camal Jan 31 '19 at 17:29
  • Since .net 4 has been out for so long, It would be nice to edit this post so that GetValueOrDefault is shown as the main answer – Andy May 05 '20 at 09:48
  • 2
    by VS2019 suggestion v2 = v1 ?? default; – wolf354 Jan 20 '21 at 18:14
  • link https://learn.microsoft.com/en-us/dotnet/api/system.nullable-1.getvalueordefault – gawkface Mar 16 '22 at 17:42
208

Like this,

if(v1.HasValue)
   v2=v1.Value
125

You can use the Value property for assignment.

v2 = v1.Value;
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
e36M3
  • 5,952
  • 6
  • 36
  • 47
  • 8
    Also - if you're unsure if v1 contains null - you can use the null-coalescing operator to set a fallback value. E.g. v2 = v1 ?? 0; – Arjen May 13 '11 at 17:02
  • 16
    And be sure to check `v1.HasValue` first. – Yuck May 13 '11 at 17:02
  • 4
    [MSDN](https://msdn.microsoft.com/de-de/library/ydkbatt6(v=vs.110).aspx) says, that this will throw an exception if the `v1` is `null`. In my opinion, this is not a correct answer. – ventiseis Oct 24 '15 at 21:41
  • 7
    @ventiseis I would think that's desirable behavior -- I'm surprised so many of the other answers are ok with silently converting a null to 0. If you're assigning a nullable type to a non-nullable type, you should be sure that the value isn't actually null. OP didn't say "I want to assign v1 to v2, or 0 if v1 is null", but that's what everyone seemed to assume – Michael Mrozek Mar 15 '16 at 06:39
96

All you need is..

v2= v1.GetValueOrDefault();
thestar
  • 4,959
  • 2
  • 28
  • 22
58

You can't do it if v1 is null, but you can check with an operator.

v2 = v1 ?? 0;
Arturo Martinez
  • 3,737
  • 1
  • 22
  • 35
54

If you know that v1 has a value, you can use the Value property:

v2 = v1.Value;

Using the GetValueOrDefault method will assign the value if there is one, otherwise the default for the type, or a default value that you specify:

v2 = v1.GetValueOrDefault(); // assigns zero if v1 has no value

v2 = v1.GetValueOrDefault(-1); // assigns -1 if v1 has no value

You can use the HasValue property to check if v1 has a value:

if (v1.HasValue) {
  v2 = v1.Value;
}

There is also language support for the GetValueOrDefault(T) method:

v2 = v1 ?? -1;
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • You should not use the value without first checking to see if there is a value. Use the ?? operator instead. – Peter Sep 28 '17 at 17:00
31

GetValueOrDefault()

retrieves the value of the object. If it is null, it returns the default value of int , which is 0.

Example:

v2= v1.GetValueOrDefault();

Mamta D
  • 6,310
  • 3
  • 27
  • 41
Aniket Sharma
  • 1,000
  • 10
  • 16
28

If the default value for a given type is an acceptable result:

if (v1.HasValue)
    v2 = v1.GetValueOrDefault();

If you want a different default value when the result is undefined:

v2 = v1.GetValueOrDefault(255);    // or any valid value for int in place of 255

If you just want the value returned (no matter if the method failed or not):

v2 = v1.GetValueOrDefault();


.NET 4.7.2.: GetValueOrDefault() returns the field value without any checking.

GrzegorzF
  • 291
  • 4
  • 6
19

As far as I'm concerned the best solution is using GetValueOrDefault() method.

v2 = v1.GetValueOrDefault();
Masoud Darvishian
  • 3,754
  • 4
  • 33
  • 41
19

Depending on your usage context, you may use C# 7's pattern-matching feature:

int? v1 = 100;
if (v1 is int v2)
{
    Console.WriteLine($"I'm not nullable anymore: {v2}");
}

EDIT:

Since some people are downvoting without leaving an explanation, I'd like to add some details to explain the rationale for including this as a viable solution.

  • C# 7's pattern matching now allows us check the type of a value and cast it implicitly. In the above snippet, the if-condition will only pass when the value stored in v1 is type-compatible to the type for v2, which in this case is int. It follows that when the value for v1 is null, the if-condition will fail since null cannot be assigned to an int. More properly, null is not an int.

  • I'd like to highlight that the that this solution may not always be the optimal choice. As I suggest, I believe this will depend on the developer's exact usage context. If you already have an int? and want to conditionally operate on its value if-and-only-if the assigned value is not null (this is the only time it is safe to convert a nullable int to a regular int without losing information), then pattern matching is perhaps one of the most concise ways to do this.

Nicholas Miller
  • 4,205
  • 2
  • 39
  • 62
  • The necessity of introducing a new variable name is unfortunate, but this is the best (safest) solution if there is no default value, because there is no risk of accidentally refactoring away your `HasValue` checks. – minexew Mar 23 '19 at 18:21
  • I just don't see any advantage to this method over v1.HasValue as the check and then v1.Value to access the underlying value. I wouldn't downvote it, but I think this problem has been solved already and a new technique doesn't add much clarity to the problem. I also benchmarked it as 8-9% slower. – Brandon Barkley Nov 27 '19 at 17:07
  • Thanks for benchmarking it, thats good to know! Either way you look at it, the difference is marginal at best (unless you do this in some time critical area I suppose). I look at this being more "concise" or possibly "idiomatic" since it relies on syntax sugars baked into the language instead of APIs. It's a bit subjective, but perhaps it's "more maintainable". Though truly, I like this approach more than relying on a default value as a lot of other answers suggest. – Nicholas Miller Nov 27 '19 at 21:42
  • the fact that it's slower is unfortunate since this would appear to have the advantage of removing the possibility of duplicate checks, dang (edit: if it uses hard cast as the check itself, i wonder if the reason for the slowness is the underlying use of exceptions...) – bug Aug 18 '22 at 14:16
14

Int nullable to int conversion can be done like so:

v2=(int)v1;
Gareth
  • 5,140
  • 5
  • 42
  • 73
Krishna shidnekoppa
  • 1,011
  • 13
  • 20
13

In C# 7.1 and later, type can be inferred by using the default literal instead of the default operator so it can be written as below:

v2 = v1 ?? default;
akesfeden
  • 480
  • 2
  • 7
  • 12
12

it's possible with v2 = Convert.ToInt32(v1);

Rev
  • 2,269
  • 8
  • 45
  • 75
12

You could do

v2 = v1.HasValue ? v1.Value : v2;
FIre Panda
  • 6,537
  • 2
  • 25
  • 38
11

A simple conversion between v1 and v2 is not possible because v1 has a larger domain of values than v2. It's everything v1 can hold plus the null state. To convert you need to explicitly state what value in int will be used to map the null state. The simplest way to do this is the ?? operator

v2 = v1 ?? 0;  // maps null of v1 to 0

This can also be done in long form

int v2;
if (v1.HasValue) {
  v2 = v1.Value;
} else {
  v2 = 0;
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
4

It will assign value of v1 to v2 if it is not null, else it will take a default value as zero.

v2=v1??0

Or below is the other way to write it.

v2 = v1.HasValue?v1:0
Shaido
  • 27,497
  • 23
  • 70
  • 73
sagar
  • 41
  • 2
2

It can be done using any of the following conversion methods:

v2 = Convert.ToInt32(v1);

v2 = (int)v1;

v2 = v1.GetValueOrDefault();

v2 = v1.HasValue ? v1:0;

Salahuddin Ahmed
  • 4,854
  • 4
  • 14
  • 35
0
 int v2= Int32.Parse(v1.ToString());
  • 5
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – xiawi Mar 10 '20 at 08:48
  • 1
    It's better to use the "best practice" way to unwrap optionals, instead of using underhanded tricks. See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types for reference – lorg Mar 10 '20 at 09:00
  • When answering a eight year old question with fifteen existing answers it is important to explain what new aspect of the question your answer is addressing, and to note if the passage of time has changed the answer. Code only answers can almost always be improved by the addition of some explanation. – Jason Aller Mar 10 '20 at 16:12
  • I guess this is measurably slower than the other answers, with the detour through string. And still fails for a null – Hans Kesting Mar 13 '21 at 08:21
  • I just did a simple test: roundtrip through string it is about 60 times slower than some of the other options. A whopping 100 nanoseconds! – Hans Kesting Mar 13 '21 at 12:13
0

I am working on C# 9 and .NET 5, example

foo is nullable int, I need get int value of foo

var foo = (context as AccountTransfer).TransferSide;
int value2 = 0;
if (foo != null)
{
    value2 = foo.Value;
}

See more at https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types#examination-of-an-instance-of-a-nullable-value-type

Vy Do
  • 46,709
  • 59
  • 215
  • 313
-2

Normal TypeConversion will throw an exception

Eg:

int y = 5;    
int? x = null;    
y = x.value; //It will throw "Nullable object must have a value"   
Console.WriteLine(y);

Use Convert.ToInt32() method

int y = 5;    
int? x = null;    
y = x.Convert.ToInt32(x);    
Console.WriteLine(y);

This will return 0 as output because y is an integer.

Peter Csala
  • 17,736
  • 16
  • 35
  • 75