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

Anirban Goswami 256 Reputation points
2021-05-12T18:01:31.053+00:00

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,

Developer technologies | .NET | Other
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.