Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a class property/field be of anonymous type in C# 4.0?

As in:

public class MyClass {

  private static var MyProp = new {item1 = "a", item2 = "b"};

}

Note: The above doesn't compile nor work (the var cannot be used there), it's only to show my point.

Update: Just to clarify the question, I had already tried using

private static dynamic MyProp = new {item1 = "a", item2 = "b"};

and this works, but it doesn't generate intellisense because of the dynamic typing. I am aware that anonymous typing is just a compiler trick, so I hoped I could use this trick to my advantage by declaring a structured field without having to declare a class beforehand (mainly because there's only going to be one instance of this particular kind of field). I can see now that it's not possible, but I'm not sure why that is. If the compiler is simply generating an implicit type for an anonymous object, it should be fairly simply to have the compiler generate this implicit type for a field.

like image 842
Diego Avatar asked Oct 20 '10 20:10

Diego


2 Answers

It sounds like you could be asking one or two questions so I'll try and address them both.

Can a class field be strongly typed to an anonymous type

No. Anonymous type names cannot be stated in C# code (hence anonymous). The only way to statically type them is

  1. Generic type inferencee
  2. Use of the var keyword

Neither of these are applicable to the field of a type.

Can a class field be initialized with an anonymous type expression?

Yes. The field just needs to be declared to a type compatible with anonymous types: object for example

public class MyClass { 
  private static object MyProp = new {item1 = "a", item2 = "b"}; 
} 
like image 149
JaredPar Avatar answered Sep 29 '22 15:09

JaredPar


How about using Tuple<string, string> instead?

public class MyClass {

  private static Tuple<string, string> MyProp = Tuple.Create("a", "b");

}
like image 26
Dr. Wily's Apprentice Avatar answered Sep 29 '22 13:09

Dr. Wily's Apprentice