I am trying to create an object that is created inline but i want to acces the properties i create inside like the folowing:
object x = new { text = "one", text2 = "two" };
if (x.text == "one") //can not acces this item in the object
{
//do somthing
}
I know i can make this work by creating a dynamic
object but then i need to realy make sure i spell the property correct and i dont want that.
What happend with this code is that i cant acces the properties inside, how can i do this without using a dynamic object and having the chance to misstype the property name?
Use var
as the type of your variable instead:
var x = new { text = "one", text2 = "two" };
Console.WriteLine(x.text); // Fine, and suggested by Intellisense
Console.WriteLine(x.text1); // Compile-time error
Note that this isn't really a "dynamic object" in that the property names and types are known at compile-time. All that's happening is that the C# compiler is creating a type for you automatically with the relevant properties (and constructors, and overrides of Equals
, GetHashCode
and ToString
). The name of that type is unspeakable in C#, but var
lets you declare a local variable of that type, allowing compile-time checking etc.
The var
feature is known as implicitly-typed local variables.
The new { ... }
feature is known as anonymous types.
See more on this question at Stackoverflow