Link to home
Start Free TrialLog in
Avatar of kranthi4uonly
kranthi4uonly

asked on

can constructors be overloaded in c# if so how

can constructors be overloaded in c# if so how to do   it
Avatar of hongjun
hongjun
Flag of Singapore image

Something like this

class MyClass
{
    private string _FirstName;

    public MyClass()
    {
        // Default constructor
    }

    private MyClass(string firstName)
    {
        _FirstName = firstName;
    }
}


hongjun
ASKER CERTIFIED SOLUTION
Avatar of hongjun
hongjun
Flag of Singapore image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Another note to throw out there, if you want to have NO default constructor appear, then you need this:

class MyClass
{
    private string _FirstName;

    private MyClass()  //note that it is private, this way there can be no default constructor. an alternative const must be used.
    {
        // Default constructor
    }

    public MyClass(string firstName)
    {
        _FirstName = firstName;
    }
}
My 2 comments would have been a good enough answer and split should have been executed.
.... and strickdd's wrong, anyway... As soon as you define any constructor at all, you don't get the automatic default (no parameters) constructor...

So the fact that you've got public MyClass(string firstName)

means that the constructor MyClass() doesn't exist...
Yes. I agree with andrewjb.

hongjun
In other words with below, default constructor will be "missing".

class MyClass
{
    private string _FirstName;

    public MyClass(string firstName)
    {
        _FirstName = firstName;
    }
}


hongjun
PS I wasn't point-hunting. H gave the original, correct, answer - that's fine!