is there any possibility to declare a class dynamically? is there any possibility to create generic list with anonymous class in C#? any code snippets will help. thanks
-
12It's possible, but it's probably not what you're looking for. What are you trying to do?SLaks– SLaks2010-11-02 16:31:32 +00:00Commented Nov 2, 2010 at 16:31
-
sorry I was not clear enough. the thing i don't know which properties my class will have. I get the needed properties list dynamically.danyloid– danyloid2010-11-10 17:34:16 +00:00Commented Nov 10, 2010 at 17:34
3 Answers
Declaring a class dynamically requires CodeDom.
is there any possibility to create generic list with anonymous class in C#?
Yes, but it's, in general, not recommended for use outside of the immediate context. For example, this creates a generic list of an anonymous type:
var range = Enumerable.Range(0, 100);
var genericList = range.Select(value => new { Value = value }).ToList();
In the above code, genericList is a List<T> containing an anonymous type.
2 Comments
CodeDom is great, but there tends to be a feature disconnect between language features and what CodeDom supports (e.g. readonly fields). System.Reflection.Emit is the way to go for full control, albeit a more complicated route.As SLaks mentioned in the comments, it is possible. But it is non-trivial. I'm not sure what you are trying to do, but you can easily add anonymous types to a generic list of objects.
List<object> list = new List<object>();
for(int i = 0; i < 10; i++){
list.Add(new { SomeProperty = i, OtherProperty = "foobar" });
}
Comments
Microsoft made C# dynamic in version 4.0. You can use the new 'dynamic' keyword. The following link has some good examples of how to use the new dynamic type.