Understanding the meaning of this c# code

1k views Asked by At

I'm trying to understand the following code:

  flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
  {
    DataStore = new FileDataStore("Tasks.ASP.NET.Sample.Store"),
    ClientSecretsStream = stream,
    Scopes = new[] { TasksService.Scope.TasksReadonly }
  });

From my understanding, the code between the first and last {...} is the body of an anonymous function. The new FileDataStore creates a new instance of FileDataStore. What I don't understand is what the comma at the end of it means. The two lines following it also have commas at the end. What kind of construct is this called in C#? I'm not familiar with it.

3

There are 3 answers

2
Simon Whitehead On BEST ANSWER

No, it isn't the body of an anonymous function. It is an initialization list.. and it serves to set the fields of the new object of type GoogleAuthorizationCodeFlow.Initializer all in-line.

It is the "in-line" version of this:

var initializer = new GoogleAuthorizationCodeFlow.Initializer();
initializer.DataStore = new FileDataStore("Tasks.ASP.NET.Sample.Store");
initializer.ClientSecretsStream = stream;
initializer.Scopes = new[] { TasksService.Scope.TasksReadonly };

flow = new GoogleAuthorizationCodeFlow(initializer);

The two are equivalent functionally. It is just more compact.

0
Dan On

It's a constructor initializer. The code is creating a new GoogleAuthorizationCodeFlow.Initializer object, and setting DataStore, ClientSecretsStream and Scopes properties on the object.

This is then being passed to a GoogleAuthorizationCodeFlow constructor as an argument.

2
Sandy On

You have a class Sample.

public class Sample()
{
    public string id { get; set; }
    public int key { get; set; }
}

This can be initialized as

var sample = new Sample {id = 1, key = "one"};

Then pass this sample as argument.

In your example they have done same thing to the parameter. This is called as class initializer.

Hope it helps.