user1662812
user1662812

Reputation: 2601

Passing the Object Type dynamically

I have this code that has the [Ent] inside the using

 public static void Retion()
        {

            using (Ent entitiesContext = new Ent())
                {...}
         {

I need to pass the [Ent] dynamically, like this:

 public static void Retion(Type ds)
            {

                using (ds entitiesContext = new ds())
                    {...}
             {

This of course does not work. How to I change this so that I can pass it dynamically?

Upvotes: 3

Views: 106

Answers (4)

Justin Harvey
Justin Harvey

Reputation: 14672

How about

   public static void Retion<T>() where T : IDisposable, new()
   { 

            using (T entitiesContext = new T()) 
                {...} 
   }

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062580

Perhaps via generics:

public static void Retion<T>() where T : IDisposable, new()
{
    using (T entitiesContext = new T())
    {...}

then Retion<Ent>()

Note that to do anything useful with entitiesContext, you'll probably also need some base--class constraint, i.e.

public static void Retion<T>() where T : DataContext, new()
{
    using (T entitiesContext = new T())
    {...}

Of course, that then isn't hugely different to:

public static void Retion(Type type)
{
    using (DataContext entitiesContext = 
        (DataContext)Activator.CreateInstance(type))
    {...}

Upvotes: 3

burning_LEGION
burning_LEGION

Reputation: 13450

you can call constructor from type by reflection

Upvotes: 0

Mahmoud Alam
Mahmoud Alam

Reputation: 430

public static void Retion< T >(T ds) where T :new() {

            using (T entitiesContext = new T())
                {...}
         {

Upvotes: 0

Related Questions