Alin Argintaru
Alin Argintaru

Reputation: 155

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.

Upvotes: 12

Views: 489

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186698

You have to cast the interface type to the class type; usually we do it by means of as:

  B b = element as B; // <- try cast element as B

  if (!Object.RefernceEquals(null, b)) { // <- element is B or can be legaly interpreted as B
    b.method4(); 
  }

The advantage of "as" is that there's only one cast operation, while "is" and (B) have to do two casts.

Upvotes: 2

Romano Zumb&#233;
Romano Zumb&#233;

Reputation: 8079

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();
}

Upvotes: 4

Sam Leach
Sam Leach

Reputation: 12956

Without casting you could do this.

interface iA
{
  bool method1();
  bool method2();
  bool method3();
}

interface IFoo : iA
{
  bool method4();
}

class B : IFoo
{
  public bool method1() {}
  public bool method2() {}
  public bool method3() {}
  public bool method4() {}
}

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

NB: Try to use capital I prefix for C# interfaces.

Upvotes: 2

Related Questions