2

Hi I was wondering if something like this was possible or not, I'm sure my title question wasn't clear.

Say I have a function that returns a JSON representation of an object. Note: This is more pseudocode than anything don't correct me on the function.

public static json function(object){

}

Is it possible to define an object like this (I'm working with c#)

var exampleObject = { Name: "x" , PhoneNum: "123456789" }

I was hoping there would be a way to create a object with object attributes just like that on the fly without having to make a class like:

class exampleObject{
string name;
string phoneNum;
}

Does something like this exist? Thanks.

STLDev
  • 5,950
  • 25
  • 36
asdf
  • 657
  • 1
  • 13
  • 30
  • What you're asking for breaks the strong statically-typed nature of C#. If you *really* want to do this, you can [de-serialize the JSON into a `dynamic` object](http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object). However, it's much better to use either a `Dictionary`, or your own strongly-typed class which is much safer. See [How to decode a JSON string using C#?](http://stackoverflow.com/questions/7699972/how-to-decode-a-json-string-using-c?lq=1) – Jonathon Reinhart May 27 '14 at 23:05
  • You were close. Check out documentation on anonymous types: http://msdn.microsoft.com/en-us/library/bb397696.aspx – itsme86 May 27 '14 at 23:05

2 Answers2

5

Yes. These are called anonymous types (although format and usage is a little different than what you have there). You can find much more about anonymous types in C# on MSDN: http://msdn.microsoft.com/en-us/library/bb397696.aspx.

An example usage using info from your question would be:

var exampleObject = new { Name = "x", PhoneNum = "123456789" };
STLDev
  • 5,950
  • 25
  • 36
2

Take a look at ExpandoObject

dynamic exampleObject = new ExpandoObject();      
exampleObject.Name= "X";
exampleObject.PhoneNum= "123456789";
Justin Lessard
  • 10,804
  • 5
  • 49
  • 61