I like to keep things separate when programming. That is one of the reasons why inheritance is important I believe.
I am using a dll file that consists of a class that I cannot modify. the dll file contains ClassA to illustrate my example.
class Program
{
static void Main(string[] args)
{
ClassA object1 = new ClassA();
SomeMethod<ClassA>(object1 ); // error because " a does not implement ITemp"
}
static T SomeMethod<T>(T input)
where T:ITemp // make sure input has a method MyCustomMethod
{
input.MyCustomMethod();
return input;
}
// create this interface so that compiler does not complain when
// calling MyCustomMethod in method above
interface ITemp
{
void MyCustomMethod();
}
}
// classA is a sealed class in a dll file that I cannot modify
public class ClassA
{
public void MyCustomMethod()
{
}
}
why is there an error if object1 does implement ITemp inteface! object1 has the method MyCustomMethod()
I know I can use reflection to solve this but I like to keep my code clean. also I want to avoid using the dynamic type.
ClassA doesn’t implement the ITemp interface. Just because it has a method with the same name and signature as the method in the ITemp interface doesn’t mean it implements that interface. The class would need to be declared to implement it explicitly.
Since you can’t extend ClassA, the best thing I can think of would be to wrap it with an adapter type class:
Then in your main method: