I've used extension methods numerous times, and haven't run into this issue. Anyone have any ideas why this is throwing an error?
/// <summary>
/// Rounds the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="decimals">The decimals.</param>
/// <returns></returns>
public static decimal Round (this decimal value, int decimals)
{
return Math.Round(value, decimals);
}
Usage:
decimal newAmount = decimal.Parse("3.33333333333434343434");
this.rtbAmount.Text = newAmount.Round(3).ToString();
newAmount.Round(3) is throwing the compiler error:
Error 1 Member 'decimal.Round(decimal)' cannot be accessed with an instance reference; qualify it with a type name instead
The conflict here is a conflict between your extension method and decimal.Round
. The simplest fix here, as already discovered, is to use a different name. Methods on the type always take precedence over extension methods, even to the point of conflicting with static
methods.
Sorry for answering my own question so fast. Within a second of posting this, it dawned on me that perhaps the compiler didn't like "Round" as the name. So I changed it to "RoundNew" and it worked. Some sort of naming conflict I guess...'
No errors anymore:
/// <summary>
/// Rounds the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="decimals">The decimals.</param>
/// <returns></returns>
public static decimal RoundNew (this decimal value, int decimals)
{
return Math.Round(value, decimals);
}
decimal newAmount = decimal.Parse("3.33333333333434343434");
this.rtbAmount.Text = newAmount.RoundNew(3).ToString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With