Alexander Galkin
Alexander Galkin

Reputation: 73

How to call a method from another class without creating an object

How can I call method whithout creating class.

Example

public class1 {
    class2 = new class2();
    int size;
    private void method() {
        size = class2.size;
    }
}

public class2 {
    private void method() {
        //call method from class1
    }
}

Upvotes: 0

Views: 766

Answers (2)

Alexander Galkin
Alexander Galkin

Reputation: 73

I mean it:

public Class1 {
    Class2 class2 = new Class2();
    public int size;
    public Class1() {
        class2.handler += method1;
    }
    private void method1() {
        size = class2.size;
    }
}

public Class2 {
    ...
    public int size;
    public delegate void Handler();
    public Handler handler;
    private void method2() {
        size = UpdateSize();
        handler?.Invoke();
    }
    private int UpdateSize() {
        ...
    }
}

Upvotes: 0

Matt
Matt

Reputation: 329

You can do that making the method of class1 static (add the static reserved word before private)

That way you can call the method as class1.method();

Hope this is what you are looking for!

Upvotes: 1

Related Questions