Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is that kind of instance name being omitted? [duplicate]

Tags:

c#

I have a question about this "shortcut" found in the ASP.NET 5 template:

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
    {          
        var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
            .AddJsonFile("config.json")
            .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);

The last two lines are only method calls, obviously of a builder. I think this is 100% the same:

var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath);
builder.AddJsonFile("config.json");
builder.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);

What do you call this syntax where the object name is omitted? Is it only possible when calling NEW/ctor? Can someone point me to that part of C# language definition?

I've googled this, but cannot find the answer.

Edit: this question obviously is very similar to other method-chaining questions, if you already know the term, but my question wasn't meant to implement that, only to use it correctly and get the correct documentation of it. may be this question is nice for being googled, as I used well known source code from VS templates.

like image 905
Falco Alexander Avatar asked Mar 15 '23 10:03

Falco Alexander


1 Answers

I've heard this concept referred to as "method chaining" or "fluent syntax" (depending on the semantics of the methods). You see it a lot in things like jQuery, for example. The idea is simply that a method on an object will modify that object and return the modified version. So another method can be immediately called on the return value, and so on.

The code isn't "omitting" the builder variable. It's just that new ConfigurationBuilder(appEnv.ApplicationBasePath) returns a ConfigurationBuilder object. And when you call .AddJsonFile() on a ConfigurationBuilder, it modifies the object and then returns it again. So you can chain as many calls to that as you like and still end up with the object.

Technically that first example is all one line of code. The carriage returns are for readability. (Note there is no semicolon until the end.) C# simply ignores whitespace and continues to process the code until the end of the statement (a semicolon) is reached. Contrast this with languages like VB where a carriage return is part of the language and itself terminates a statement.

like image 99
David Avatar answered Mar 30 '23 00:03

David