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)

Ian GM
  • 779
  • 3
  • 9
  • 18
  • 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. – Tim Schmelter Oct 15 '15 at 07:28
  • @Nikita can you provide an example please? Thanks. – Ian GM Oct 15 '15 at 07: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. – Ian GM Oct 15 '15 at 07:31
  • 2
    You might as well just go with `List` because that's what you're going to have to treat that list as in the rest of the code anyway. – Lasse V. Karlsen Oct 15 '15 at 07: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<>`) – Nameless One Oct 15 '15 at 07:32
  • Here's another duplicate http://stackoverflow.com/questions/19565018/how-to-create-a-list-of-classes-where-the-class-name-is-taken-from-the-string-in?lq=1 – Tim Schmelter Oct 15 '15 at 07:38
  • Thanks Tim. It looks like I should now ask a separate but similar question as I need to know if it is possible to reference an Entity Framework dbContext in the same way. I.e. by using a string variable. See my updated question above. Thank you. :o) – Ian GM Oct 15 '15 at 07:48

2 Answers2

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);
Pawel Maga
  • 5,428
  • 3
  • 38
  • 62
1

You can use:

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

Related: other question

Community
  • 1
  • 1
Dietz
  • 578
  • 5
  • 14