I have multiple variables which I set prior to creating an object, I want to check if any of those variables in null, if any variable then display an error. Is there a way to incorporate this in a foreach loop?
For eg.
Var Var1 = blah1;
Var Var2 = blah2;
Var Var3 = blah3;
Var Var4 = blah4;
Var Var5 = blah5;
foreach(var above, if any is null)
Errmessage
Thanks in advance
I, personally, would have separate checks for each variable. On "error message" for multiple validation checks is a bad idea.
The main reason for this is that your "error message" should likely be an ArgumentNullException
, which should provide the proper parameter name. This will be different per variable. Even if you use a custom exception, providing information about which variable was improperly specified is worth the extra coding effort.
That being said, if you want to do this, you can use:
var Var1 = blah1;
var Var2 = blah2;
var Var3 = blah3;
var Var4 = blah4;
var Var5 = blah5;
if ( (new object[] {Var1, Var2, Var3, Var4, Var5}).Any(v => v==null))
throw new Exception("Your error here");
Put them in an IEnumerable such as an array
foreach(var v in new object[] { var1, var2, .... }){
if(v == null) {
Errmessage...
}
}
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