Houssem
Houssem

Reputation: 57

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

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

Upvotes: 3

Views: 567

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460208

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.

Upvotes: 4

David Watts
David Watts

Reputation: 2289

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() {...}    
}

Upvotes: 2

Related Questions