Reputation: 475
I wrote a class with multiple overloads, however when I attempt to utilise them outside the class, only the default constructor can be used. Otherwise I receive an error stating that no such constructor exists.
public Module()//default Module Class
{
Code = "Undefined";
Title = "Undefined";
Credits = 0;
Mark = 0;
ExamWeighting = 0;
ExamMark = 0;
CourseWorkNumber = 1;
Term = "AY";
CourseWork1Name = "Undefined";
CourseWork1Type = "Undefined";
CourseWork1Weight = 1;
CourseWork1Mark = 0;
}
public Module(string code, string title, int credits, string moduleTerm, double exWeight, double exMark, string cW1Name, string cW1Type, double cW1Weight, double cW1Mark)
{
Code = code;
Title = title;
Credits= credits;
Mark = 0;
ExamWeighting = exWeight;
ExamMark = exMark;
CourseWorkWeight = 1.0 - exWeight;
CourseWorkNumber = 1;
Term = moduleTerm;
CourseWork1Name = cW1Name;
CourseWork1Type = cW1Type;
CourseWork1Weight = cW1Weight;
CourseWork1Mark = cW1Mark;
}
I ensured that I had the correct number and type of parameters, unless of course I'm missing something.
string code = tempArray[0];
string title = tempArray[1];
int credits = Convert.ToInt16(tempArray[2]);
string moduleTerm = tempArray[3];
double exWeight = Convert.ToDouble(tempArray[4]);
double exMark = Convert.ToDouble(tempArray[5]);
string cW1Name = tempArray[10];
string cW1Type = tempArray[11];
double cW1Weight = Convert.ToDouble(tempArray[12]);
double cW1Mark = Convert.ToDouble(tempArray[13]);
// (string code, string title, int credits, string moduleTerm, double exWeight, double exMark, string cW1Name, string cW1Type, double cW1Weight, double cW1Mark)
tempModule = new Module(code, title, credits, moduleTerm, exWeight, exMark, cW1Name, cW1Type, cW1Weight, cW1Mark);
Upvotes: 0
Views: 64
Reputation: 120496
Having a parameter list a mile long is an anti-pattern. You've just discovered why this is the case by messing up the call, because either you've:
or
at the call site.
If it is inevitable that you need a large number of parameters, then you might consider using an options class that encapsulates all these parameters. This allows for sensible defaults too. So
public class ModuleOptions
{
public ModuleOptions()
{
//supply sensible defaults here
Code = "Not set";
Title = "Not set";
//etc
}
public string Code{get;set;}
public string Title{get;set;}
//etc...
}
then
public class Module
{
public Module(ModuleOptions options)
{
this.Code = options.Code;
//etc...
}
}
So now your call site looks like
var opts = new ModuleOptions
{
Code = "1234",
//etc
};
var module = new Module(opts);
Now it's a lot easier to see what's happening and you're far less likely to screw up your call.
Upvotes: 1