String to Int32?

F

Fred Chateau

How can I convert a string into a nullable integer?

If string is empty, convert to nullable integer. Set value to null. Else, convert string value to
nullable integer value.

In other words, I want to be able to do the following:

Int32? ID = String.IsNullOrEmpty(value.ID) ? null : Convert.ToInt32?(value.ID)
 
N

Nicholas Paldino [.NET/C# MVP]

Fred,

You have an error in your code, but it's minor:

Int32? ID = String.IsNullOrEmpty(value.ID) ? (int?) null :
Convert.ToInt32(value.ID);

But beyond that, that's exactly how I would do it.
 
P

Peter Morris

Int32? ID = String.IsNullOrEmpty(value.ID) ? null :
Convert.ToInt32?(value.ID)

What about

int? ID = string.IsNullOrEmpty(value.ID) ? null : int.parse(value.ID);
 
F

Fred Chateau

ReSharper displays error "No implicit conversion between null and int". Same error as my code.
 
F

Fred Chateau

Thank you for your help with it.

--
Regards,

Fred Chateau
fchateauAtComcastDotNet


Nicholas Paldino said:
Fred,

You have an error in your code, but it's minor:

Int32? ID = String.IsNullOrEmpty(value.ID) ? (int?) null : Convert.ToInt32(value.ID);

But beyond that, that's exactly how I would do it.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Fred Chateau said:
How can I convert a string into a nullable integer?

If string is empty, convert to nullable integer. Set value to null. Else, convert string value to
nullable integer value.

In other words, I want to be able to do the following:

Int32? ID = String.IsNullOrEmpty(value.ID) ? null : Convert.ToInt32?(value.ID)

--
Regards,

Fred Chateau
fchateauAtComcastDotNet
 
P

Peter Morris

ReSharper displays error "No implicit conversion between null and int".
Same error as my code.

Then you need to cast it

int? ID = string.IsNullOrEmpty(value.ID) ? null : (int?)int.parse(value.ID);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top