B. Clay Shannon B. Clay Shannon - 1 year ago 95
C# Question

(Why) is invoking as extension method the preferred...way?

I am in the process of resharpening my solution, using the just-released version of Resharper (2016.2.2)

It flags this line of code:

ReportRunnerConstsAndUtils.ConvertValueToAppropriateTypeAndAssign(totalPackagesCell, packages);

...intimating that I should "Invoke as extension method"

If I acquiesce, it changes that line to this:


Is this better? If so, how? why?

Here is the method being called, which is in a "ConstsAndUtils" class:

// Adapted from https://stackoverflow.com/questions/26483496/is-it-possible-to-ignore-excel-warnings-when-generating-spreadsheets-using-epplu
public static void ConvertValueToAppropriateTypeAndAssign(this ExcelRangeBase range, object value)
string strVal = value.ToString();
if (!String.IsNullOrEmpty(strVal))
decimal decVal;
double dVal;
int iVal;

if (decimal.TryParse(strVal, out decVal))
range.Value = decVal;
if (double.TryParse(strVal, out dVal))
range.Value = dVal;
else if (Int32.TryParse(strVal, out iVal))
range.Value = iVal;
range.Value = strVal;
range.Value = null;

Answer Source

As some of the comments have indicated, this is at least partially a preference issue. Personally, I think it's "cleaner" and clearer to use an extension method here but some people may disagree with this.

"Under the hood," of course, the extension method is a static method (not an actual instance method), it's just that the compiler's giving you some syntactic sugar here (but that's besides the point).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download