Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with rounding extension on decimal - cannot be accessed with an instance reference; qualify it with a type name instead

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
like image 918
mservidio Avatar asked Aug 12 '11 18:08

mservidio


2 Answers

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.

like image 64
Marc Gravell Avatar answered Nov 15 '22 12:11

Marc Gravell


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();
like image 2
mservidio Avatar answered Nov 15 '22 13:11

mservidio