Optional parameter

  • Thread starter Thread starter Curious
  • Start date Start date
C

Curious

I have two methods that are almost identical, except for the
"HtmlLogger varLogger" parameter passed to #2.
In #1, it uses a default HtmlLogger "logger" while in #2, it uses
"varLogger" parameter.

Other than that, the two methods are identical. I would like to
combine the two methods into a single method, but I wish to know:

- How to identify the optional parameter in the method; and
- When there is no optional parameter passed to the method, how to set
the default as "logger".

Method #1:

void PublishNegativeAlpha ( IGridEntry entry)
{
try
{
foreach (NegativeAlphaForEntry negA in mNegativeAList)
{

if (negA.List == entry.List.Name &&
negA.Ticker == entry.Ticker &&
negA.TargetShares == entry.TargetShares)
{

ESide side = entry.TargetSide;
string strSide = GetSideString(side);

if (negA.Side == strSide)
{
NegativeAlpha neg = new NegativeAlpha();
neg.ObjectId = entry.ObjectId;
neg.NegativeStatus = "Negative Alpha";

CustomObjectManager.Publish(neg,
PublishMode.Regular);


logger.LogMessageBarMessage(ESeverity.Detail, "Published negative
alpha for ticker " + negA.Ticker);

break;
}
}
}
}
catch (Exception e)
{
logger.LogMessageBarMessage(ESeverity.Error,
e.Message);
}
}


Method #2:

void PublishNegativeAlpha ( IGridEntry entry, HtmlLogger
varLogger)
{
try
{
foreach (NegativeAlphaForEntry negA in mNegativeAList)
{

if (negA.List == entry.List.Name &&
negA.Ticker == entry.Ticker &&
negA.TargetShares == entry.TargetShares)
{

ESide side = entry.TargetSide;
string strSide = GetSideString(side);

if (negA.Side == strSide)
{
NegativeAlpha neg = new NegativeAlpha();
neg.ObjectId = entry.ObjectId;
neg.NegativeStatus = "Negative Alpha";

CustomObjectManager.Publish(neg,
PublishMode.Regular);


varLogger.LogMessageBarMessage(ESeverity.Detail, "Published negative
alpha for ticker " + negA.Ticker);

break;
}
}
}
}
catch (Exception e)
{
varLogger.LogMessageBarMessage(ESeverity.Error,
e.Message);
}
}
 
Curious said:
I have two methods that are almost identical, except for the
"HtmlLogger varLogger" parameter passed to #2.
In #1, it uses a default HtmlLogger "logger" while in #2, it uses
"varLogger" parameter.

Other than that, the two methods are identical. I would like to
combine the two methods into a single method, but I wish to know:

- How to identify the optional parameter in the method; and
- When there is no optional parameter passed to the method, how to set
the default as "logger".

There's no such thing as an optional parameter in C#. The trick is to
make one overload call the other, supplying an appropriate default (in
this case "logger"). In other words, change PublishNegativeAlpha(entry)
to:

void PublishNegativeAlpha (IGridEntry entry)
{
PublishNegativeAlpha(entry, logger);
}
 
Back
Top