Home > Net >  how to parse "" to long("0") in dotnet
how to parse "" to long("0") in dotnet

Time:10-04

given the following code:

string example = "1234";
long parsed_example = long.Parse(example);
Console.Writeline(parsed_example);
# => 1234

Works great.

the following example does not:

string example = "";
long parsed_example = long.Parse(example);
# [System.FormatException: Input string was not in a correct format.]

However the goal is:

string example = "";
if (example == "")
{
    example = "0";
}
long parsed_example = long.Parse(example);
Console.Writeline(parsed_example);
# => 0

is there a shorter, apropriate solution? The above code would almost justify a tiny function, Id preferable have a inline solution. Maybe something such as (pseudo code):

string example = "";
long parsed_example = example ?? 0, long.Parse(example);

CodePudding user response:

long parsed_example = example == "" ? 0 : long.Parse(example);

However: don't be obsessed with single-line solutions; a multi-line solution is often more readable and correct. There are no prizes for creating complex code. You may also wish to look at string.IsNullOrWhiteSpace, long.TryParse, etc. For example:

long value;
if (string.IsNullOrWhiteSpace(example))
{
    // what you want to do with blank/empty values
    value = 42;
}
else if (!long.TryParse(example, out value))
{
    // what you want to do with non-integer values 
   value = 84;
}

CodePudding user response:

Use:

long parsed_example = long.Parse(example.ToString("0"));

This uses the String.Format() call which is more elegant but not faster than your long parsed_example = example ?? 0, long.Parse(example);

  • Related