EBAG
EBAG

Reputation: 22561

ERROR: 'object' does not contain a definition for 'methodName'

I need to pass different objects instantiated from different classes which they have a function with same name, and I would like to call that function.

For example:

Class1 object1;
Class2 object2;
Class3 object3;

Object object = object1;
object1->functionname();

Object object = object2;
object2->functionname();

Object object = object3;
object3->functionname();

this is not possible in c#...

In php it's pretty simple you can just do it with object like the sample above but in c# i get this error: ERROR: 'object' does not contain a definition for 'methodName'

I though it's legal to call any method name on a object object! since it doesn't know what is really inside.

How can I do that?

Upvotes: 1

Views: 2090

Answers (3)

Brian R. Bondy
Brian R. Bondy

Reputation: 347216

Create an interface that both classes implement.
Then pass the object via the type of your interface to your function:

interface IAnimal
{
    void Speak();
}

class Cat : IAnimal
{
    public void Speak()
    {
        MessageBox.Show("Meow!");
    }
}

class Dog : IAnimal
{
    public void Speak()
    {
        MessageBox.Show("Woof!");
    }
}


static class Program
{

    static void SpeakPlease(IAnimal animal)
    {
        animal.Speak();
    }
 //...
 }

Upvotes: 3

Karl Knechtel
Karl Knechtel

Reputation: 61508

c# is statically typed: it looks up method names when the code is compiled, not when it is run. object doesn't have that method name, so you can't expect to call that function.

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838116

I though it's legal to call any method name on a object object! since it doesn't know what is really inside.

No, it's illegal to call any method apart from the ones defined on Object itself. Perhaps you are thinking of dynamic?

But instead I think you should create a common interface.

interface IProcessable
{
    void Process();
}

Upvotes: 3

Related Questions