I would like to know if there is a better more efficient way to use if statements rather than just long lines of
if(){
//code
}else if(){
//code
} else{
//code
}
I've done some research on the site and I found this:
If you have only 2 values, I strongly suggest to use the code you posted, because is likely the most readable, elegant and fast code possible (IMHO).
But if you have more cases like that and more complicated, you could think to use a switch statement:
switch (el.type)
{
case ElementType.Type1:
case ElementType.Type2:
case ElementType.Type3:
//code here
break;
case ElementType.Type4:
case ElementType.Type5:
//code here
break;
case ElementType.Type6:
//code here
break;
}
that translated in if statements would be:
if (el.type == ElementType.Type1 ||
el.type == ElementType.Type2 ||
el.type == ElementType.Type3 )
{
// code here
}else if(el.type == ElementType.Type4 ||
el.type == ElementType.Type5)
{
// code here
}else if(el.type == ElementType.Type6)
{
// code here
}
They're perfectly equal to me, but the switch seems more readable/clearer, and you need to type less (i.e. it's "shorter" in term of code length) :)
Although I don't quite understand what it is telling me, is it saying that a switch statement is a better use for long if statements or?
To have some context surrounding my problem, I have a Windows Forms application with some radio buttons - A questionnaire if you will - I want to know if there is more efficient ways that reduces repetitive unnecessary lines of code and replaces them with short code that does the same job.
Aucun commentaire:
Enregistrer un commentaire