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
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.
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" });
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.