According to the MSDN document interface 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 having interface inside a class? Won't it break the purpose of real interface usage?
From stackoverflow
-
Not if, for some reason, that interface only makes sense within the context of that class, and you want to make that clear by implementing it like so.
I must say, I've never used this construct once, for what it's worth.
-
The class is another namespace. Therefore the interface can be used to enforce contracts on data that flows between methods in the class, or just to scope the interface more precisely.
-
They are useful when you want to break things up within 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 } }
Paddy : Personally I'm not a fan of many classes within one code file - I find it just makes things hard to find.macke : Wouldn't dependancy injection be a better alternative in this case? That way you could let whoever calls Print decide in what manner it should be printed (as long as IPrinter is implemented) thus reducing the complexity of Invoice while at the same time allowing for more types of printers than HTML and PDF (Mocking for instance).
0 comments:
Post a Comment