Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# When a class instance is created to execute a method within the class

Tags:

c#

winforms

public class TestClass
{
    private void Method1() {...}
}

Is it possible to execute method1 as soons as i initialize the class? If so, How do I do it?

I didn't know how to phrase my question, so my apologies if there is already a similar question

like image 328
Houssem Avatar asked Dec 11 '25 16:12

Houssem


2 Answers

Yes, from the constructor:

public class TestClass
{
    public TestClass()
    {
        // initialize here...
        // then call your method:
        Method1();
    }

    private void Method1() {...}
}

If this method takes a long time to execute, it is not appropriate for the constructor because the caller might not expect this. Then you should make your method public(with a meaningful name) and let it be called afterwards. Constructors are supposed to initialize objects not use them.

like image 110
Tim Schmelter Avatar answered Dec 13 '25 05:12

Tim Schmelter


So to create the class you will be using code similar to this right?

var testClassInstance = new TestClass()

That being the case, all you need to do is put the call to the method in the constructor of TestClass Like So:

public class TestClass
{
    public TestClass(){
        Method1();
    }

    private void Method1() {...}    
}
like image 31
David Watts Avatar answered Dec 13 '25 04:12

David Watts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!