0

Suppose we have the following code:

var variable = "key";
var @object = new { variable = "value" };
System.Console.WriteLine(@object);

This creates the object:

{ variable = value }

Can we instead have it create the following object?

{ key = value }
Kim Visscher
  • 121
  • 1
  • 6
  • 1
    It's not common to do that, if you give more information why you want it, maybe there are alternatives – Jeroen van Langen Apr 29 '20 at 14:07
  • 1
    Why do you want to do that? Having a runtime property name in an anonymous class doesn't sound very useful. – juharr Apr 29 '20 at 14:08
  • 1
    @KimVisscher But what do you plan to use this object for once it is created? – juharr Apr 29 '20 at 14:14
  • 2
    Why cant you just use a Dictionary? – maccettura Apr 29 '20 at 14:15
  • 1
    Also, this seems like an XY Problem – maccettura Apr 29 '20 at 14:15
  • @JeroenvanLangen I don't care about reusing the anonymous class, it's in a fire and forget use case. I like the declarative nature of object initializer syntax more, than having a dynamic object and individually assigning the properties [like so](https://stackoverflow.com/questions/7478048/why-cant-i-do-this-dynamic-x-new-expandoobject-foo-12-bar-twelve) – Kim Visscher Apr 29 '20 at 14:18
  • Why don't you use a [ValueTuple](https://docs.microsoft.com/en-us/dotnet/csharp/tuples)? – mm8 Apr 29 '20 at 14:26

0 Answers0