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?
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
.
See more on this question at Stackoverflow