Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert nullable string to nullable int in c#

Tags:

c#

c#-9.0

I have variable with below

  int? a=null ;
    
  string? b= null;

I need to assign a=b ;

What is best way to assign in c# 9

a= Convert.ToInt32(b);

It is assigning 0 ..hw to assign null if string also null.. i need to know in c# 9

EDIT: Thanks to @john.. i ended up with below code

  if(b is not null) 
     a = Convert.ToInt32(b); 
like image 423
Ajt Avatar asked Dec 18 '22 12:12

Ajt


1 Answers

I would just be very explicit about it:

int? a = b is null ? null : Convert.ToInt32(b);
like image 88
Jon Skeet Avatar answered Dec 24 '22 01:12

Jon Skeet