tags:

views:

65

answers:

4

Are you able to define class-implementations in an interface?

For instance (pseudo-code alert!)...

interface IClass1
{
    String s { get; set; }

    // classes implementing this interface has to implement Class2 as "SubClass"
    Class2 SubClass;
}

interface IClass2
{
     Int32 i { get; set; }
}

class Class1 : IClass1
{
    String IClass1.s { get; set; }

    class IClass1.Class2 SubClass
    {
        Int32 IClass2.i { get; set; }
    }
}
A: 

No, I don't think it is possible

saurabh
+2  A: 

No. Also, Class2 isn't a subclass, it's a nested class or inner class. "Sub-class" is (in this context, there are other contexts that are completely different) another name for a derived class, in which context the base class is called a "super-class" (which is why Java has a keyword super that is analogous to base in C# though with some differences). "Derived" and "base" are the more popular terms in C#, perhaps because they are more popular terms in C++, perhaps because Bjarne Stroustrup says he finds them confusing and even he gets mixed up about which is which (after all, the subclass has a superset of behaviour and vice-versa).

Inner classes are essentially using their containing class as a namespace and nothing else, while interfaces only detail member methods and properties.

Jon Hanna
+2  A: 

There is no syntax for forcing a class to implement another nested class. What you have effectively defined here is that any IClass1 implementation must have a field of type Class2.

Unfortunately there are two things wrong with this:

  1. Class2 does not resolve to a known accessible type, therefore a compiler error will be generated.
  2. The SubClass member of IClass1 is declared as a field, and interfaces cannot declare fields.
Josh
+2  A: 

The purpose of an interface is to define a contract which is separate from any implementation.

What you can do with an interface is defining a property like so:

interface IClass1
{
    String S { get; set; }

    Class2 SubClass { get; set; }
}
0xA3