C# data validation using Parse() for any T that has Parse implementation
I am simplifying my code (I like to write the least amount of lines per function performed) and I often come across the lengthy process of data validation. So decided to write a Validate function, in pseudocode:
public static bool Validate(string input, out object output){
// try to parse data
try {
(TypeOf(object)) output = new (TypeOf(object));
output = (TypeOf(object)).Parse(input);
return true;
} catch {
return false;
}
}
So if I use in my code to validate several text boxes, it looks nice and very开发者_如何转开发 readable:
double var1;
Int32 var2;
byte var3;
if (!Validate(txtDouble.text, var1)) return "Error validating a Double";
if (!Validate(txtInt32.text, var2)) return "Error validating a Int32";
if (!Validate(txtByte.text, var3)) return "Error validating a byte";
// else all data is valid, continue
Process(var1, var2, var3)
I could create a static class Validate and overload for each type, but since I am planning on using on types that include the Parse method, it seems to me that there should be a way of implementing the above function... I just don't know what I am looking for. An interface keeps coming to my mind, but failing at implementing.
Thanks!
The framework providers already wrote your function for you, it's called TryParse
. There is no generic nature to it, but it's called the exact same way you're calling Validate
. Might as well use what's already there.
double var1;
if (!double.TryParse(input, out var1)) return "Invalid input";
The method is available for your double, int, float, char, DateTime, etc.
You're better off creating a static class with overloads (that call TryParse
instead of Parse
for the various types involved. The list is fairly short and your only other options will be convoluted.
Or you could just call the appropriate version of TryParse
directly in your code. If you aren't inserting any additional validation (hence the need for your own validation class), then it won't be any more verbose than your pseudocode.
You could use something like this (it uses reflection):
private static void Test()
{
var r1 = TryParse("23", typeof(int));
var r2 = TryParse("true", typeof(bool));
}
private static bool TryParse(string valueToParse, Type type)
{
//there are more then one TryParse method and we need the one with 2 parameters
var method = type.GetMethods().Where(m => m.Name == "TryParse" && m.GetParameters().Count() == 2).Single();
var instance = Activator.CreateInstance(type); //create instance of the type
var result = method.Invoke(null, new object[] { valueToParse, instance });
return (bool)result;
}
but it's really fancy code (maybe there is a chance to write it a bit better;) ) and I would never use it.
As Anthony Pegram suggested you should create few overloads methods with TryParse - it's much cleaner and better solution.
精彩评论