Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check for null variables

Tags:

c#

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

like image 377
user793468 Avatar asked Dec 19 '11 18:12

user793468


2 Answers

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");
like image 78
Reed Copsey Avatar answered Oct 14 '22 09:10

Reed Copsey


Put them in an IEnumerable such as an array

foreach(var v in new object[] { var1, var2, .... }){
 if(v == null) {
   Errmessage...
 }
}
like image 37
Preet Sangha Avatar answered Oct 14 '22 09:10

Preet Sangha