Click here to Skip to main content
16,004,653 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Method 1 :

public void ClearControlValues()
{
txtHolidayDate.Text = string.Empty;
txtHolidayName.Text = string.Empty;
txtHolidayDescription.Text = string.Empty;
}

Method2:

public void ClearControlValues()
{
txtHolidayDate.Text = txtHolidayName.Text = txtHolidayDescription.Text = string.Empty;
}

What I have tried:

Which method is best way to clear the textbox values
Posted
Updated 19-Apr-18 10:10am

It's a matter of style. If your employer doesn't have a published coding style:

0) If you're editing an existing file, use the style that is used in that file.

1) If it's a new file that you're creating, do it the way that you prefer.

Personally, I prefer one assignment per line, but that's me.
 
Share this answer
 
I agree with John. Both versions compile to roughly the same IL, so it's just a matter of preference.

Looking at method two, you might expect it to do something like:
C#
txtHolidayDescription.Text = string.Empty;
txtHolidayName.Text = txtHolidayDescription.Text;
txtHolidayDate.Text = txtHolidayName.Text;

But if you examine the compiled IL, you'll see that the property get accessor is never called. Instead, you simply get:
C#
txtHolidayDescription.Text = string.Empty;
txtHolidayName.Text = string.Empty;
txtHolidayDate.Text = string.Empty;

You can demonstrate this with a simple class:
C#
public class Foo
{
    public string Text
    {
        get { throw new InvalidOperationException("Boo!"); }
        set { }
    }
}

static class Program
{
    static void Main()
    {
        Foo x = new Foo();
        Foo y = new Foo();
        Foo z = new Foo();
        
        x.Text = y.Text = z.Text = "Hello";
        Console.WriteLine("Hooray!");
    }
}
Running that code, no exception is thrown, which demonstrates that the get accessor is not called.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900