Search code examples
c#asp.net.netasp.net-4.0compiler-bug

Why empty assignment compiled with no errors


Here is my snippet:

var country = BLLocations.Instance.GetCountries();
ddlCountry.DataSource = 
ddlCountry.DataTextField = "Country";
ddlCountry.DataValueField = "CountryCode";
ddlCountry.DataBind();

See the second line:

ddlCountry.DataSource = 

And it compiled successfully and published to cloud also. Strange!


Solution

  • It's simply this:

    ddlCountry.DataSource =  ddlCountry.DataTextField = "Country";
    

    The line break doesn't effect, Which is a valid code.

    Just like:

    var x = 2;
    var y = 3;
    x = y = 1000;
    

    (Note this is really not good practice at all! it's confusing and hard to disgust)

    Every code in C# returns a value(though the value can be void) which lets you do this lazy loading:

    return x ?? x = new ExpensiveObject();//
    

    What it does:

    1. If x is not null returns x.
    2. If x is null assigns x new ExpensiveObject() an returns the assignment value - x.

    Helpful feature but be careful with it.