Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can this code be simplified?

Tags:

c#

This piece of code is a lot if/else and I want to know if it can be simplified to a handful of lines. The code works perfectly fine, but I prefer to have a more efficient and cleaner way.

if (textBox_naam.Text.Length < 3)
{
   textBox_naam.BackColor = Color.FromArgb(205, 92, 92);
}
else
{
   textBox_naam.BackColor = Color.White;
}

if (textBox_email.Text.Length < 5)
{
   textBox_email.BackColor = Color.FromArgb(205, 92, 92);
}
else
{
   textBox_email.BackColor = Color.White;
}

if (textBox_body.Text.Length < 20)
{
   textBox_body.BackColor = Color.FromArgb(205, 92, 92);
}
else
{
   textBox_body.BackColor = Color.White;
}
like image 756
Devator Avatar asked Nov 29 '22 02:11

Devator


2 Answers

Your easiest bet (no tricks involved!) would be:

SetBackColor(textBox_naam, 3, GOOD_COLOR, BAD_COLOR);
SetBackColor(textBox_email, 5, GOOD_COLOR, BAD_COLOR);
SetBackColor(textBox_body, 20, GOOD_COLOR, BAD_COLOR);

with a method SetBackColor defined like this:

public void SetBackColor(TextBox tb, int minLength, Color goodColor, Color badColor)
{
    tb.BackColor = tb.Text.Length < minLength ? badColor : goodColor;
}
like image 151
Daren Thomas Avatar answered Dec 13 '22 02:12

Daren Thomas


You can use the ternary if then else operator

textBox_naam.BackColor = textBox_naam.Text.Length < 3 ? Color.FromArgb(205, 92, 92) : Color.White;

This isn't any more efficient, but will use less lines of code.

like image 34
Phil Avatar answered Dec 13 '22 02:12

Phil