3

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

2
  • 12
    It's possible, but it's probably not what you're looking for. What are you trying to do? Commented 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. Commented Nov 10, 2010 at 17:34

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

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.
@Steve: True - but once people understand CodeDom, they can usually find Emit if required...
5

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

1

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.

http://msdn.microsoft.com/en-us/library/dd264741.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.