Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert.TryToInt64 instead of Convert.ToInt64?

I have this function I have to implement:

protected override ValidationResult IsValid(
    Object value,
    ValidationContext validationContext
)
{
  //Here is where I wanna test whether the following conversion is applicable
  var x = Convert.ToInt64(value);
}

I could wrap that line in a try-catch block, or with other ways to perform that test, here is one of them:

var convertible = value as IConvertible;
if (convertible != null)
  var x = convertible.ToInt64(null);

What's the most efficient way to do this?

like image 775
Shimmy Weitzhandler Avatar asked Feb 19 '12 02:02

Shimmy Weitzhandler


2 Answers

here you can define a default value, if the parse (conversion) is applicable it will return the converted int64 otherwise the default value will be returned:

Int64 DefaultValue = 0;
Int64.TryParse(MyVar , out DefaultValue);

ie:

Int64 DefaultValue = 0;
Int64.TryParse("1234" , out DefaultValue);

DefaultValue will be 1234

Int64 DefaultValue = 0;
 Int64.TryParse("test" , out DefaultValue);

DefaultValue will be 0

You can also make it even shrorter by declaring the variable like this:

 Int64.TryParse("123" , out Int64 DefaultValue);
like image 62
Ashkan Mobayen Khiabani Avatar answered Sep 30 '22 10:09

Ashkan Mobayen Khiabani


Using IConvertible worked best for me.

I've made a short test and this way was WAY (6 times) quicker, using IConvertible, the code also looks cleaner and less verbose to my taste.

static void Main(string[] args)
{
  var sw = new Stopwatch();

  sw.Start();
  for (short i = 0; i < short.MaxValue; i++)
  {
    var foo = IsValid1(i);
  }
  sw.Stop();
  var result1 = sw.Elapsed;
  Console.WriteLine(result1);

  sw.Start();
  for (short i = 0; i < short.MaxValue; i++)
  {
    var foo = IsValid2(i);
  }
  sw.Stop();
  var result2 = sw.Elapsed;

  Console.WriteLine(result2);
  Console.ReadKey();
}

static bool IsValid1(object value)
{
  var convertible = value as IConvertible;
  if (convertible != null)
    return convertible.ToInt64(null) != 0;
  return true;
}
static bool IsValid2(object value)
{
  if (value != null)
  {
    long amount;
    if (long.TryParse(value.ToString(), out amount))
      return amount != 0;
  }
  return true;
}

OUTPUT:

00:00:00.0031987
00:00:00.0186700
like image 25
Shimmy Weitzhandler Avatar answered Sep 30 '22 10:09

Shimmy Weitzhandler