C # - Interface inside a class

According to the document interface, MSDN can be a member of a class or namespace:

for example, I can declare:

public class Test { public interface IMemberofTest { void get(); } } 

What is the use of an interface inside a class? Wouldn't that violate the purpose of using a real interface?

+4
source share
3 answers

A class is a different namespace. Therefore, an interface can be used to enforce contracts for data that is passed between methods in a class or simply for a thinner interface.

+7
source

They are useful when you want to break things up inside a class.

  public class Invoice { public String Print(Type type) { IPrinter printer = null; switch (type) { case Type.HTML: printer = new HtmlPrinter(this); break; case Type.PDF: printer = new PdfPrinter(this); break; default: throw new ArgumentException("type"); } printer.StepA(); printer.StepB(); printer.StepC(); return printer.FilePath; } private interface IPrinter { void StepA(); void StepB(); void StepC(); String FilePath { get; } } private class HtmlPrinter : IPrinter { //Lots of code } private class PdfPrinter : IPrinter { //Lots of code } public enum Type { HTML, PDF } } 
+3
source

No, if for some reason this interface makes sense only in the context of this class, and you want to make it understandable by implementing it like this.

I have to say that I never used this construct once, for what it's worth.

+2
source

All Articles