constructor overloads

  • Thread starter Thread starter Mike P
  • Start date Start date
M

Mike P

What do you do in a situation where you have more than 1 overload with
the same signature (e.g. class(string, string, string, string))? Is the
best think to do to send through an extra parameter such as an int as an
identifier?


Regards,

Mike
 
Hi Mike,

I would prefer an enumeration over int to distinguish the various
constructors.
 
Mike,

You can't do that. The compiler will complain when you try and do this
for a constructor, or any method. You will have to add an extra flag
indicating what the other parameters represent.

Hope this helps.
 
Having 2 constructors with the same signature would never compile. You would
have to vary number/type of parameters.
 
Mike P said:
What do you do in a situation where you have more than 1 overload with
the same signature (e.g. class(string, string, string, string))? Is the
best think to do to send through an extra parameter such as an int as an
identifier?

One alternative is to use factory methods which differ in name:

MyType (string name, string country)
{
this.name = name;
this.country = country;
}

public static MyType FromName (string name)
{
return new MyType (name, null);
}

public static MyType FromCountry (string country)
{
return new MyType (null, name);
}
 
From a code-readability standpoint, you're probably better off going with
fewer constructors, then setting properties after you've created an instance
of the object. Trying to pass everything into multiple constructors can get
messy.

-James
 
Back
Top