question

AnirbanGoswami-8125 avatar image
0 Votes"
AnirbanGoswami-8125 asked AnirbanGoswami-8125 commented

Extension method must be defined in a top level static class; DiscountedClass is a nested class

Hi All,

I am trying to understanding extension method and it uses. So i wrote below code at C#.Net-4.7 sdk..


 public class Program
 {
  //concrete class
  public  class OriginalClass  
  {  
     public   int TotalPrice(int productCount,int Cost)  
    {  
   return productCount* Cost ;  
    }  
  } 
  //We want to provide flat 100 rupees discount to the final price.
  // so we created an extension method with deriving the above  concrete class
  public static class DiscountedClass  
  {  
     public static int FinalPriceAfterDiscount(this OriginalClass obj, int productCount, int finalPrice)  
    {  
   // flat 100 rupees discount  
   return productCount * finalPrice - 100;  
    }  
  } 
  public static void Main()
  {
   Console.WriteLine("Hello World");
    OriginalClass rate = new OriginalClass();  
    int price = rate.TotalPrice(4, 1000);  
    int discountedPrice = rate.FinalPriceAfterDiscount(4, 1000);  
    Console.WriteLine("Price Without Discount :" + price);  
    Console.WriteLine("Price With discount :" + discountedPrice); 
  }
 }

But, at compilation time it was giving an error as "Extension method must be defined in a top level static class; DiscountedClass is a nested class".

Any suggestion or Help on above is appreciate ..

Thanks,

dotnet-standard
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @AnirbanGoswami-8125 ,
The code works for me, what's the type of your application?
Here's a reference you can refer to.
Error: Extension methods must be defined in a top level static class (CS1109)


1 Vote 1 ·

Thanks @XingyuZhao-MSFT , I used Visual studio 2019 ide and it is working fine.

Thanks for replay.

0 Votes 0 ·

0 Answers