Sealer_05
Sealer_05

Reputation: 5576

Complex C# object

I am used to making JavaScript objects like below but what would be the fastest way of doing the same with C#? It is just static data that will be serialized for a post that will not change. In the past with C# I would create classes and lists for everything but in this scenario I just need to send some practice data. Any help would be appreciated

            var data = {
                "dealer": {
                    "keyId": "vfase32sd",  
                     "name": "mark"
                },
                "seller": [
                    {
                        "email": "[email protected]",
                        "active":false
                    }
                ],
                "state": [
                    "TN",
                    "TX"
                ]};

Upvotes: 2

Views: 210

Answers (2)

Reza Aghaei
Reza Aghaei

Reputation: 125312

See Object and Collection Initializers

Object initializer with Anonymous types

Although object initializers can be used in any context, they are especially useful in LINQ query expressions. Query expressions make frequent use of anonymous types, which can only be initialized by using an object initializer, as shown in the following declaration.

var pet = new { Age = 10, Name = "Fluffy" };

For example:

var data = new
{
    dealer = new
    {
        keyId = "vfase32sd",
        name = "mark"
    },
    seller = new[] {
        new {
            email= "[email protected]",
            active= false
        }
    },
    state = new[]{
        "TN",
        "TX"
    }
};

The rule for converting that js object to c# object is simple:

  • "x": will be x=
  • {} will be new {}
  • [] will be new []{}
  • Values remain untouched

Upvotes: 9

Vova
Vova

Reputation: 1416

You can use dynamic typing feature of C#

var data = new 
{
    dealer = new 
    {
        keyId = "vfase32sd", 
        name =  "mark",
    },
    seller = new[] 
    {
        new 
        {
            email = "[email protected]",
            active = false
        }
    },
    state = new [] 
    {
        "TN",
        "TX"
    }
};

Upvotes: 2

Related Questions