Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a non-static class call another non-static class's method?

Tags:

c#

non-static

I have 2 classes both non-static. I need to access a method on one class to return an object for processing. But since both classes is non-static, I cant just call the method in a static manner. Neither can I call the method in a non-static way because the program doesnt know the identifier of the object.

Before anything, if possible, i would wish both objects to remain non-static if possible. Otherwise it would require much restructuring of the rest of the code.

Heres the example in code

class Foo
{
    Bar b1 = new Bar();

    public object MethodToCall(){ /*Method body here*/ }
}

Class Bar
{
    public Bar() { /*Constructor here*/ }

    public void MethodCaller()
    {
        //How can i call MethodToCall() from here?
    }
}
like image 366
DarkDestry Avatar asked Dec 15 '14 15:12

DarkDestry


1 Answers

class Bar
{
    /*...*/

    public void MethodCaller()
    {
        var x = new Foo();
        object y = x.MethodToCall();
    }
}

BTW, in general, objects don't have names.

like image 85
John Saunders Avatar answered Nov 10 '22 00:11

John Saunders