Lijo Varghese
Lijo Varghese

Reputation: 3

Accessing implemented class method without creating object through Interface?

I have two classes Say A and B which has method set().

   public Class A : I<string>
   {
      void Set(string str)
      {
         //do something
      }
   }

   public Class B : I<int>
   {
      void Set(int str)
      {
         //do something
      }
   }

And an interface as follows...

interface I<T>
{
    void Set(T param);
}

I would like to access this method without instantiating the classes, through interface (Is it possible or is there any other way like dependency injection?).

From another Class

Class D
{
    I.Set(<T> str); //something like this
}

So based on data type I need to redirect the call from either interface or some where, so that if tomorrow I added a class say C which implements same interface, I should not end up with changing code in D.

Thanks in Advance...

Upvotes: 0

Views: 1727

Answers (2)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

An interface is sort of like a template of methods an implementing class provides. You can not "do anything" with an interface. You always need an instance of a class implementing the interface.

So what you want does not work. However, a simple extension method will help you here:

public static class MyExtensionMethods
{
    public static void SetValue<T>(this I<T> intf, T value)
    {
        intf.Set(value);
    }
}

Using this, you can write:

A a = new A();
B b = new B();

b.SetValue("Hello");
a.SetValue(1);

And it will work for any other classes that implement I<T> without having to change the extension method:

public class D : I<double>
{
    public void Set(double d) { ... }
}

D d = new D();
d.SetValue(42.0);

Upvotes: 4

Matthew Abbott
Matthew Abbott

Reputation: 61589

You need to pass in something, so at the moment, my best guess would be

class D
{
  public void Set<T>(object target, T value) 
  {
    var instance = target as I<T>;
    if (instance != null)
    {
      instance.Set(value);
    }
  }
}

Called like:

var theD = new D();
var theA = new A();
var theB = new B();
theD.Set<string>(theA, "hello");
theD.Set<int>(theB, 1);

Upvotes: 0

Related Questions