Home > Enterprise >  How to create an Iterface for a Class that is in a DLL C#
How to create an Iterface for a Class that is in a DLL C#

Time:03-07

Lib:

class SomeLibraryIHaveNoControlOver {
    public int ID { get; set; }

    public void Update()
    {
        Console.WriteLine("Updated");
    }
}

Usage:

class Program
{
    static void Main(string[] args)
    {
        Apple apple = new Apple();
        apple.FruitLib.Update();

        Console.ReadKey();
    }
}

I started like this:

class Apple 
{
    public SomeLibraryIHaveNoControlOver FruitLib { get; set; } = new SomeLibraryIHaveNoControlOver();
}

And then I did this:

interface IFruit
{
    SomeLibraryIHaveNoControlOver FruitLib { get; set; }
}
class Apple : IFruit
{
    public SomeLibraryIHaveNoControlOver FruitLib { get; set; } = new SomeLibraryIHaveNoControlOver();
}

Hoping for :

class Apple : IFruit
{
    public IFruitLib  FruitLib { get; set; } = new SomeLibraryIHaveNoControlOver(); //To support both the library I dont have control over and the new one
}

Instead of using just SomeLibraryIHaveNoControlOver in the Apple class I would like to create my own Library that does exactly the same functionality(its done in a different way) how can I modifiy apple to support both libraries even though SomeLibraryIHaveNoControlOver does not comes with an iterface that I can use to create my own.

CodePudding user response:

how can I modifiy apple to support both libraries even though SomeLibraryIHaveNoControlOver does not comes with an iterface that I can use to create my own.

You can use "encapsulation". Just wrap it in a class you have full control over. eg

class Pear : IFruitLib
{
    private SomeLibraryIHaveNoControlOver foo;
    public Pear(SomeLibraryIHaveNoControlOver foo)
    {
       this.foo = foo;
    }

    public void SomeFruitLibMethod()
    {
        foo.Update();
    }
}
  •  Tags:  
  • c#
  • Related