How to parse a string into a nullable int
int.TryParse
is probably a tad easier:
public static int? ToNullableInt(this string s)
{
int i;
if (int.TryParse(s, out i)) return i;
return null;
}
Edit @Glenn int.TryParse
is "built into the framework". It and int.Parse
are the way to parse strings to ints.
Using int.TryParse with nullable int
Because the out
has to be int
you need something like:
int temp;
int? nr1 = int.TryParse(str1, out temp) ? temp : default(int?);
Note that I also use default(int?)
instead of null
because the conditional typing won't work otherwise. ? (int?)temp : null
or ? temp : (int?)null
would also solve that.
As of C#7 (VS Studio 2017) you can inline the declaration of temp
int? nr1 = int.TryParse(str1, out int temp) ? temp : default(int?);
C# 8: Linq Select, Parse String into Nullable Int
The syntax requires you to define the variable, if you haven't previously. So use
Int32.TryParse(cpamlt.Manyr, out int tempVal)
But, your code can be shortened, as tempVal
will contain the value you want, you don't need to parse again -
YearManufactured = Int32.TryParse(cpamlt.Manyr, out int tempVal) ? tempVal : (int?)null,
Convert String To Nullable Integer List
You can use following extension method:
public static int? TryGetInt32(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}
Then it's simple:
List<int?> TagIds = data.Split(',')
.Select(s => s.TryGetInt32())
.ToList();
I use that extension method always in LINQ queries if the format can be invalid, it's better than using a local variable and int.TryParse
(E. Lippert gave an example, follow link).
Apart from that it may be better to use data.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries)
instead which omits empty strings in the first place.
Convert nullable string to nullable int in c#
I would just be very explicit about it:
int? a = b is null ? null : Convert.ToInt32(b);
Convert string to nullable type (int, double, etc...)
Another thing to keep in mind is that the string itself might be null.
public static Nullable<T> ToNullable<T>(this string s) where T: struct
{
Nullable<T> result = new Nullable<T>();
try
{
if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0)
{
TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
result = (T)conv.ConvertFrom(s);
}
}
catch { }
return result;
}
Split string and convert to nullable long
Use TryParse
List<long?> result = null;
if (!string.IsNullOrEmpty(baIds))
{
long temp;
result = baIds.Split(',').Select(e => long.TryParse(e, out temp) ? temp : (long?)null).ToList();
}
https://dotnetfiddle.net/uHk99J
How to pass empty string to nullable int
You have two ways to resolve the problem:
Specify
null
(not empty string) and it will be successfully mapped.codigoBanco: null
or remove this property at all from client-side(the default will be the samenull
)Write custom convertaion at backend-side, something like:
CodigoBanco = int.Parse(codigoBanco == "" || codigoBanco.Length = 0 ? null : codigoBanco);
Parsing value into nullable enumeration
The simplest way:
PriorityType tempPriority;
PriorityType? priority;
if (Enum.TryParse<PriorityType>(userInput, out tempPriority))
priority = tempPriority;
This is the best I can come up with:
public static class NullableEnum
{
public static bool TryParse<T>(string value, out T? result) where T :struct, IConvertible
{
if (!typeof(T).IsEnum)
throw new Exception("This method is only for Enums");
T tempResult = default(T);
if (Enum.TryParse<T>(value, out tempResult))
{
result = tempResult;
return true;
}
result = null;
return false;
}
}
Use:
if (NullableEnum.TryParse<PriorityType>(userInput, out priority))
The above class can be used just like Enum.TryParse
except with a nullable input. You could add another overloaded function that takes a non-nullable T
so that you could use it in both instances if you want. Unfortunately extension methods don't work very well on enum types (as far as I could try to manipulate it in the short time I tried).
Related Topics
Creating a PDF from a Rdlc Report in the Background
Better Naming in Tuple Classes Than "Item1", "Item2"
Formatting Text in a Textblock
How Does Wcf Deserialization Instantiate Objects Without Calling a Constructor
How to Make Smtp Authenticated in C#
Environment.Tickcount VS Datetime.Now
Clearing Page Cache in ASP.NET
C# Sha-1 VS. PHP Sha-1...Different Results
What Is the Purpose of Anonymous { } Blocks in C Style Languages
How to Use Elmah to Manually Log Errors
Dbentityvalidationexception - How to Easily Tell What Caused the Error