Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors with the same argument type

Tags:

c#

.net

oop

I have a Person object with two constructors - one takes an int (personId), the other a string (logonName). I would like another constructor that takes a string (badgeNumber). I know this can't be done, but seems it might be a common situation. Is there a graceful way of handling this? I suppose this would apply to any overloaded method. Code:

public class Person
{
    public Person() {}

    public Person(int personId)
    {
        this.Load(personId);
    }

    public Person(string logonName)
    {
        this.Load(logonName);
    }

    public Person(string badgeNumber)
    {
        //load logic here...
    }

...etc.

like image 597
JasonS Avatar asked Aug 27 '08 20:08

JasonS


2 Answers

You could perhaps use factory methods instead?

public static Person fromId(int id) {
    Person p = new Person();
    p.Load(id);
    return p;
}
public static Person fromLogonName(string logonName) {
    Person p = new Person();
    p.Load(logonName);
    return p;
}
public static Person fromBadgeNumber(string badgeNumber) {
    Person p = new Person();
    // load logic
    return p;
}
private Person() {}
like image 121
toolkit Avatar answered Oct 12 '22 11:10

toolkit


You might consider using custom types.

For example, create LogonName and BadgeNumber classes.

Then your function declarations look like...

public Person(LogonName ln)
{
    this.Load(ln.ToString());
}

public Person(BadgeNumber bn)
{
    //load logic here...
}

Such a solution might give you a good place to keep the business logic that governs the format and usage of these strings.

like image 29
Zack Peterson Avatar answered Oct 12 '22 09:10

Zack Peterson