I have the below method, which I need to check for whether the arguments are empty or null.
public DB Where(string field, string operat, string value, string andOr, string field2, string operat2, string value2)
{
_Where = " WHERE " + field + " " + operat + " @" + field + "1 " + andOr + " " + field2 + " " + operat2 + " @" + field2 + "2 ";
_Params.Add(field + "1", value);
_Params.Add(field2 + "2", value2);
return this;
}
I have found the string.IsNullOrWhiteSpace method however this would require this much code:
if (string.IsNullOrWhiteSpace(field))
throw new ArgumentException("field Cannot be null or be empty");
if (string.IsNullOrWhiteSpace(operat))
throw new ArgumentException("operat Cannot be null or be empty");
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException("value Cannot be null or be empty");
if (string.IsNullOrWhiteSpace(andOr))
throw new ArgumentException("andOr Cannot be null or be empty");
if (string.IsNullOrWhiteSpace(field2))
throw new ArgumentException("field2 Cannot be null or be empty");
if (string.IsNullOrWhiteSpace(operat2))
throw new ArgumentException("operat2 Cannot be null or be empty");
if (string.IsNullOrWhiteSpace(value2))
throw new ArgumentException("value2 Cannot be null or be empty");
Is there any way of shortening this?
Also, I have tried creating a custom method for this task, however it throws an exception in the custom method instead of the Where() method which makes it tricky to debug.
You could check the value one by one or creating intermediate function to do that.
Alternatively, my suggestion is: you could put all the inputs in an array and use LINQ Any to check all of them at once:
public DB Where(string field, string operat, string value, string andOr, string field2, string operat2, string value2)
{
string[] inputs = {field, operat, value, andOr, field2, operat2, value2}
if (inputs.Any(x => string.IsNullOrWhiteSpace(x))){
//throw exception
}
//continue with your method, all inputs are OK
}
What I can suggest is this:
private string _nullChecker(string _value){
if (string.IsNullOrWhiteSpace(_value))
throw new ArgumentException(_value + "Cannot be null or be empty");
return _value;
}
then, in your Where string statement
_Where = " WHERE " + _nullChecker(field) + " " + __nullChecker(operat) + " @" + _nullChecker(field) + "1 " + _nullChecker(andOr) + " " + _nullChecker(field2) + " " + _nullChecker(operat2) + " @" + _nullChecker(field2) + "2 ";
Not sure with this though. Haven't checked it with actual code. :) Hope this helps
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