As in:
public class MyClass {
private static var MyProp = new {item1 = \"a\", item2 = \"b\"};
}
Note: The above doesn\'t compile nor wo
In C# 7 you can finally do this:
private (string Login, string Password) _credentials = (Login: "123", Password: "123");
No, anonymous types cannot be exposed outside of their declaring function as anything other than object
. While the anonymous type is just syntactical sugar and does, in fact, create a concrete type, this type is never known (nor available) to the developer, and thus can't be used.
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
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"};
}
If this is C# 4, look into the dynamic keyword.
public class MyClass
{
private static dynamic MyProp = new {item1 = "a", item2 = "b"};
}
However, as soon as you do this you lose any sort of type-safety and handy compiler checks.
How about using Tuple<string, string> instead?
public class MyClass {
private static Tuple<string, string> MyProp = Tuple.Create("a", "b");
}
An property (or field) of a named class can't have an anonymous type, because such a type can't be referred to in code. However, an anonymous type can contain properties of anonymous type:
var myObj = new
{
Foo = new { Name = "Joe", Age = 20 }
};
But such a construct has no practical use outside the local scope...