Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class method that is not in the interface

I have a simple c# question (so I believe). I'm a beginner with the language and I ran into a problem regarding interfaces and classes that implement them. The problem is

I have the Interface iA

interface iA
{
  bool method1
  bool method2
  bool method3
}

and 3 classes that implement the interface: class B, C and D

class B : iA
{
  public bool method1
  public bool method2
  public bool method3
}

if class B had another method that is not in the interface, let's say method4() and I have the following:

iA element = new B();

and then I would use :

element.method4();

I would get an error saying that I don't have a method4() that takes a first argument of type iA.

The question is: Can I have an object of interface type and instantiated with a class and have that object call a method from the class, a method that is not in the interface ?

A solution I came up with was to use an abstract class between the interface and the derived classes, but IMO that would put the interface out of scope. In my design I would like to use only the interface and the derived classes.

like image 820
Alin Argintaru Avatar asked Jul 29 '13 07:07

Alin Argintaru


1 Answers

Yes, that is possible. You just need to cast the Interface type to the class type like this:

iA element = new B();
((B)element).method4();

As suggested by wudzik, you should check if elemnt is of the correct type:

if(element is B)
{
    ((B)element).method4();
}
like image 103
Romano Zumbé Avatar answered Oct 03 '22 08:10

Romano Zumbé