I have a class with the following method.
public cIPLink(int paramCaseNo, int paramIPID, string paramIPReference, int paramContactID)
{
this.cLinkDate = DateTime.Now;
this.cCaseNo = paramCaseNo;
this.cIPID = paramIPID;
this.cIPReference = paramIPReference;
this.cContactID = paramContactID;
string strConnect = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnect);
linkToDB.Open();
string sqlStat = "INSERT INTO tblIPLinks (LinkID, LinkDate, CaseNo, IPID, ContactID, IPReference)" +
"VALUES (@LinkID, @LinkDate, @CaseNo, @IPID, @ContactID, @IPReference);";
SqlCommand sqlCom = new SqlCommand(sqlStat, linkToDB);
sqlCom.Parameters.Add("@LinkID", SqlDbType.Int);
sqlCom.Parameters.Add("@LinkDate", SqlDbType.Date);
sqlCom.Parameters.Add("@CaseNo", SqlDbType.Int);
sqlCom.Parameters.Add("@IPID", SqlDbType.Int);
sqlCom.Parameters.Add("@ContactID", SqlDbType.Int);
sqlCom.Parameters.Add("@IPReference", SqlDbType.Text);
this.cLinkID = NextLinkID();
sqlCom.Parameters["@LinkID"].Value = this.cLinkID;
sqlCom.Parameters["@LinkDate"].Value = this.cLinkDate;
sqlCom.Parameters["@CaseNo"].Value = this.cCaseNo;
sqlCom.Parameters["@IPID"].Value = this.cIPID;
sqlCom.Parameters["@ContactID"].Value = this.cContactID;
sqlCom.Parameters["@IPReference"].Value = this.cIPReference;
sqlCom.ExecuteNonQuery();
linkToDB.Close();
}
However I want to make this a little more flexible. Sometimes when the method is called I want to drop the field IPID, and sometimes I want to drop the field ContactID. Now I thought about copying and pasting this code and having three overload methods; one with just IPID, one wth just ContactID and a third with both fields, but I’m sure there must be a neater way of doing what I want.
Any ideas?
If you are using dotnet 4.0 and above, you can use optional parameters.
So, from that moment on you can invoke it as follows: