Devator
Devator

Reputation: 3904

Can this code be simplified?

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;
}

Upvotes: 4

Views: 5591

Answers (4)

Daren Thomas
Daren Thomas

Reputation: 70314

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;
}

Upvotes: 18

olatunjee
olatunjee

Reputation: 9

Do you have Reshaper installed? I think you will find a great (future) assistance by using JetBrain's Reshaper extension for VS. Depend on it, it is great must-have tool for .NET developers.

Upvotes: 0

Rudu
Rudu

Reputation: 15892

Well you could use shorthand if statements...

Color other=Color.FromArgb(205,92,92);
textBox_naam.BackColor=(textBox_naam.Text.Length<3?other:Color.White);
textBox_email.BackColor=(textBox_email.Text.Length<5?other:Color.White);
textBox_body.BackColor=(textBox_body.Text.Length<20?other:Color.White);

Upvotes: 2

Phil
Phil

Reputation: 42991

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.

Upvotes: 2

Related Questions