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?
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With