PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, December 10, 2022

[FIXED] What is this type of C# coding syntax called and what is it doing?

 December 10, 2022     c#, new-operator, syntax     No comments   

Issue

For the below code, specifically the {} that don't seem connected to anything, what is the syntax called and what is it doing?

And when/why can I omit the () when using this syntax?

var a = new OpenApiSecurityRequirement() // Can I omit () and when/why?
{
    { // What is this doing?
        new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference
            {
                Type = ReferenceType.SecurityScheme,
                Id="Bearer"
            }
        },
        new string[]{}
    } // What is this doing?
};

Solution

The outermost curly bracket is just a collection initialiser.

The inner curly bracket that "don't seem to be connected to anything" exists because the Add method of OpenApiSecurityRequirement takes two parameters.

Surely you have seen this syntax with Dictionarys:

new Dictionary<string, string>() {
    { "key1", "value1" },
    { "key2", "value2" },
    { "key3", "value3" }
};

Assuming this OpenApiSecurityRequirement, which is also an IDictionary, your code is just that, but the inner curly brackets are written on multiple lines. The dictionary has one entry. The key is the OpenApiSecurityScheme, and the value is the empty string array.

And yes, the parentheses can be omitted.

Desugared:

var a = new OpenApiSecurityRequirement();
a.Add(
    new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference
            {
                Type = ReferenceType.SecurityScheme,
                Id="Bearer"
            }
        }, 
    new string[]{}
);


Answered By - Sweeper
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing