1

Here is what I need to do;

string className = "Customer";
List<className> myList = new List<className>();

className can be any of my Entity Framework classes. I have used Customer just as an example.

I hope this is possible. If so, how?

UPDATE:

I also need to use this approach for retrieving data from an Entity Framework dbContext. For example...

        string className = "Customer";
        var myData = db.Set<className>();

Sorry. Not sure if I should have created another question here or updated this one. Be gentle with me. I'm new here. :o)

7
  • 5
    Why do you need that at all? If you have such a requirement you know in 99.999% of all cases that you are using the wrong approach. Commented Oct 15, 2015 at 7:28
  • @Nikita can you provide an example please? Thanks. Commented Oct 15, 2015 at 7:28
  • @Tim, I have a generic method for wrapping JSON results and I don't want to duplicate my code for all the entities in the solution. If I can do what I have asked help for it would prevent a lot of redundant code. If that is 99.999% wrong then so be it. Commented Oct 15, 2015 at 7:31
  • 2
    You might as well just go with List<object> because that's what you're going to have to treat that list as in the rest of the code anyway. Commented Oct 15, 2015 at 7:31
  • What do you plan to use for the type of the reference? object or some other base class? Generics gets you the closest to a solution for the problem (try to use a covariant parameter, but then you can't use List<>) Commented Oct 15, 2015 at 7:32

2 Answers 2

4

If you want you can use reflection in this case, but I would think over another solution.

Type type = Type.GetType("Namespace.ClassName");
Type listType = typeof(List<>).MakeGenericType(new [] { type } );
IList list = (IList)Activator.CreateInstance(listType);
Sign up to request clarification or add additional context in comments.

1 Comment

check this answer! thats how you can use reflection.
1

You can use:

Type customerType = Type.GetType("this.is.a.namespace.Customer");

Related: other question

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.