Splatbang
Splatbang

Reputation: 776

Cast method parameter to class. Interface related

I have three classes that implement an interface and I need one Method that accepts such an object. The interface for example:

public interface IFoo {
  void DoThis();
}

One of the classes:

public class Bar: IFoo {
  public void DoThis();
}

And the method I would like to have, i.e. on a form:

private void DoStuff(object o){
  o.DoThis();
}

How can I achieve that I can call the DoThis() method in the DoStuff(object o) method?

Upvotes: 0

Views: 99

Answers (4)

Wil P
Wil P

Reputation: 3371

private void DoStuff<T>(T o) where T : IFoo
{
    o.DoThis();
}

OR

private void DoStuff(object o) 
{
    IFoo foo = o as IFoo;
    if (foo != null)
    {
        foo.DoThis();
    }
}

Upvotes: 3

neontapir
neontapir

Reputation: 4736

Another option if the signature can't change:

private void DoStuff(object o){
  IFoo foo = (IFoo) o;    
  foo.DoThis();
}

Upvotes: 0

Michael B
Michael B

Reputation: 7587

Declare your method like so::

    private void DoStuff(IFoo o){
          o.DoThis();
    }

Otherwise you can't use the IFoo interface members.

Upvotes: 4

Polynomial
Polynomial

Reputation: 28346

This should work:

private void DoStuff(IFoo o){
    o.DoThis();
}

Or this:

private void DoStuff(object o){
    IFoo ifoo;
    try
    {
        ifoo = (IFoo)o;
    }
    catch(InvalidCastException ice)
    {
        /* whatever "this isn't IFoo" logic you want here */
        throw; 
    }
    ifoo.DoThis();
}

Upvotes: 0

Related Questions