Home > Software design >  Simplify an if statement with a method C#
Simplify an if statement with a method C#

Time:06-15

I was wondering if there is any possible way to simplify this.

if (string != "")
{
   dataGridView1.Rows.Add(string);
}

All I can find is how to shorten if statements which return a value, not execute a method like mine.

CodePudding user response:

There is not much to do from where you are already. I would only suggest inverting the if statement to reduce nesting. You could also remove the braces by using this method like this:

if (string == "") return;
dataGridView1.Rows.Add(string);

CodePudding user response:

If you want to check if a string is not empty and then add it to your dataGridView1.Rows at multiple places in your code, you could declare an Action<string> like

Action<string> AddRowIfInputNotEmpty = new Action<string>(input =>
{
    if (!string.IsNullOrEmpty(input))
        dataGridView1.Rows.Add(input);
});

And then call it like AddRowIfInputNotEmpty.Invoke("MyString"); whenever you need it

CodePudding user response:

Create an extension method AddIfNotEmpty for DataGridViewRowCollection:

public static void AddIfNotEmpty(this DataGridViewRowCollection rows, string value)
{
    if(!string.IsNullOrEmpty(value))
        rows.Add(value);
}

Usage:

dataGridView1.Rows.AddIfNotEmpty(stringValue);

CodePudding user response:

Since Add method returns an int you can simplify (uglify if you ask me) using the discards operator:

_ = yourString != "" ? dataGridView1.Rows.Add(yourString) : 0;

Or as Jeremy Pointed out:

_ = !string.IsNullOrEmpty(yourString) ? Add(list, yourString) : 0;

CodePudding user response:

(As a note, when checking the equality of a string, you should use stringVar.equals() Also, when looking for null or whitespace data, you can use stringVar.IsNullOrWhiteSpace())

Well, you can try

//Note: I haven't tested this and you may need to fiddle it a bit

    if(!String.IsNullOrWhiteSpace(stringVar)) dataGridView1.Rows.Add(stringVar);

//you can also use something like this

    !String.IsNullOrWhiteSpace(stringVar) ? //if true : //if false;

Let me know if this doesn't satisfy your question and I will attempt to amend my statements.

  • Related