Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors With Same Arguments?

Tags:

c#

constructor

I have a WinForm that I want to be able to construct using two different ID values. So for instance:

var f1 = new Form(table1Id);
var f2 = new Form(table2Id);

The first constructor would build the form based on data in table1, the second constructor would build the form based on data in table2. The problem is, if I have two constructors that take an int, there is no differentiating between the two. What is the best way around this problem?

like image 611
sooprise Avatar asked Mar 23 '26 20:03

sooprise


1 Answers

Consider a factory approach instead of a constructor. Named methods are a way to disambiguate when the parameter types are the same but mean different things. For example

public static Form CreateFromTable1(int id)
{
    // instantiate, build form
    return form;
}

public static Form CreateFromTable2(int id)
{
    // instantiate, build form
    return form;
}
like image 173
Anthony Pegram Avatar answered Mar 25 '26 08:03

Anthony Pegram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!