How do I check for null or empty string for many arguments? - C#

后端 未结 4 634
-上瘾入骨i
-上瘾入骨i 2021-01-20 05:51

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, s         


        
相关标签:
4条回答
  • 2021-01-20 06:03

    Firstly, you can use simple libraries to do argument validation. Check out this one called Argument Validator, which has handy functions that will reduce your overall code by half.

    Here is an example on how you could do it using the argument validator library:

    public DB Where(string field, string operat, string value, string andOr, string field2, string operat2, string value2)
    {
        var inputs = new string[] {field, operat, value, andOr, field2, operat2, value2};
        foreach(var input in inputs)
        {
            Throw.IfNullOrEmpty(input, nameof(input)));
        }
    }    
    
    0 讨论(0)
  • 2021-01-20 06:13

    You could do this:

    int? GetLength(string s) {
        return s == "" ? -1 : s?.Length;
    }
    
    // s1, s2 and so on are your parameters
    int? lengthSum = GetLength(s1) + GetLength(s2); // and so on
    int wholeLength = (s1 + s2).Length; // and so on
    if(lengthSum == wholeLength) {
        // No parameter is null or empty
    }
    
    0 讨论(0)
  • 2021-01-20 06:16

    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

    0 讨论(0)
  • 2021-01-20 06:22

    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
    }
    
    0 讨论(0)
提交回复
热议问题