Error with rounding extension on a decimal basis - access to the instance is not possible; give it a type name instead

I used extension methods many times and did not come across this problem. Anyone have any ideas why this is causing the 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); } 

Using:

 decimal newAmount = decimal.Parse("3.33333333333434343434"); this.rtbAmount.Text = newAmount.Round(3).ToString(); 

newAmount.Round (3) throws a compiler error:

 Error 1 Member 'decimal.Round(decimal)' cannot be accessed with an instance reference; qualify it with a type name instead 
+8
c # rounding visual-studio-2010 extension-methods
source share
2 answers

The conflict here is the conflict between your extension method and decimal.Round . The simplest fix here, as has already been discovered, is to use a different name. Type methods always take precedence over extension methods, even if they conflict with static methods.

+8
source share

Sorry to answer your question so quickly. Within a second after the publication of this question, it became clear to me that perhaps the compiler did not like "Round" as a name. So I changed it to "RoundNew" and it worked. Some kind of name conflict I think ... '

No more errors:

 /// <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(); 
+2
source share

All Articles