methods in constructors, bad?

Spooks picture Spooks · Jan 5, 2011 · Viewed 26.9k times · Source

I have a windows form, and I have a class that checks a text file to make sure it has certain aspect. Now I have methods in a constructor and it seems a little weird. Should I just leave the constructor blank, and implement a start() type method and call that? So far my code looks like this

public class Seating
{
    private int segments = 0;
    public Seating()
    {
        checkInvoice();
        getSegmentCount();          
    }
}

Answer

Konrad Rudolph picture Konrad Rudolph · Jan 5, 2011

I have methods in a constructor and it seems a little weird

Well, why else would a constructor exist? It’s entirely legitimate to have methods in a constructor, even methods that could fail (thus interrupting the object creation). It’s hard to say whether this is appropriate in your particular case.

In general it’s fine though.