Nikos C.
Nikos C.

Reputation: 51840

Is it possible to have class members of an anonymous class?

I'm trying to create a class that has fields in it that are of an anonymous type. (This is for Json deserialization.)

I can't find a syntax that the compiler will accept. I'm trying:

class Foo {
    var Bar = new {
        int num;
    }
    var Baz = new {
        int[] values;
    }
}

This is supposed to represent this example Json object:

{
    "Bar": { "num": 0 }
    "Baz": { "values": [0, 1, 2] }
}

Is this even possible, or must I declare each class normally with a full class identifier?

Upvotes: 0

Views: 123

Answers (3)

Baximilian
Baximilian

Reputation: 885

Yes it is possible, here is EXAMPLE

var Bar = new {num = 0};

var Baz = new {values = new List<int>()};

var Foo = new {Bar, Baz};

Console.WriteLine(JsonConvert.SerializeObject(Foo));

Of Course you can type it in one line

var Foo = {Bar = new {num = 0}, Baz = new {values = new List<int>()}};

Edit updated .Net fiddle with using Foo as class

Upvotes: 2

Tim S.
Tim S.

Reputation: 56536

No, this is not possible. The most straightforward way to do this is to simply create classes like you said. This is what I'd recommend.

void Main()
{
    Console.WriteLine(JsonConvert.SerializeObject(new Foo { Bar = new Bar {
        num = 0
    },
    Baz = new Baz { values = new[] { 0, 1, 2 } }
    })); // {"Bar":{"num":0},"Baz":{"values":[0,1,2]}}

}
public class Foo {
    public Bar Bar { get; set; }
    public Baz Baz { get; set; }
}
public class Bar {
    public int num { get; set; }
}
public class Baz {
    public int[] values { get; set; }
}

Another approach, which loses static type checking, is typing it as object or dynamic:

void Main()
{
    JsonConvert.SerializeObject(new Foo { Bar = new {
        num = 0
    },
    Baz = new { values = new[] { 0, 1, 2 } }
    }); // {"Bar":{"num":0},"Baz":{"values":[0,1,2]}}

}
class Foo {
    public object Bar { get; set; }
    public object Baz { get; set; }
}

It would probably be possible to write a custom JsonConverter to serialize a class like this as you wish (since each anonymous type in your example only has one real value inside it; if your real types are more complex, this won't work for those).

[JsonConverter(typeof(MyFooConverter))]
class Foo {
    public int Bar { get; set; }
    public int[] Baz { get; set; }
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500495

You can declare a field using an anonymous type initializer... you can't use implicit typing (var). So this works:

using System;

class Test
{
    static object x = new { Name = "jon" };

    public static void Main(string[] args)
    {
        Console.WriteLine(x);
    }
}

... but you can't change the type of x to var.

Upvotes: 4

Related Questions