tags:

views:

437

answers:

3

I'm using interfaces in this case mostly as a handle to an immutable instance of an object. The problem is that nested interfaces in C# are not allowed. Here is the code:

public interface ICountry
{
    ICountryInfo Info { get; }

    // Nested interface results in error message:
    // Error    13  'ICountryInfo': interfaces cannot declare types
    public interface ICountryInfo
    {
        int Population { get; }
        string Note { get; }
    }
}


public class Country : ICountry
{
    CountryInfo Info { get; set; }

    public class CountryInfo : ICountry.ICountryInfo
    {
        int Population { get; set; }
        string Note { get; set; }
        .....
    }
    .....
}

I'm looking for an alternative, anybody would have a solution?

+3  A: 

This will work just fine, no need to nest:

public interface ICountry
{
    ICountryInfo Info { get; }
}

public interface ICountryInfo
{
    int Population { get; }
    string Note { get; }
}
Oded
Yes, but... this defeats the reasons why I created a nested class. ICountryInfo shouldn't have a meaning in any other places than from within ICountry.
ericdes
+3  A: 

If ICountryInfo has no reason to exist outside ICountry, then why shouldn't you just put the properties of ICountryInfo in ICountry and dismiss the idea of nested interfaces?

An interface that hasn't a meaning of its own without another interface doesn't make sense to me, as an interface on itself is useless if not implemented by a class.

Webleeuw
+1 I'd agree totally. There seems to be no need to have an ICountryInfo in this example.
Ian
Well, I just extracted the sample code from an application that contains over 100 classes with many nested classes bearing the same names. It is much cleaner if I retain that setup with nested classes. As for using interfaces, it's a way of getting their immutable counterparts. Once the objects have been instantiated, the main application mostly deals with their corresponding interfaces using the dependency injection pattern. I don't want to modify the nesting structure in a way that would result in unpractical code.
ericdes
A: 

VB.NET allows this. So, you can create a VB.NET assembly only with the interface definitions that you need:

Public Interface ICountry
  ReadOnly Property Info() As ICountryInfo

  Public Interface ICountryInfo
    ReadOnly Property Population() As Integer
    ReadOnly Property Note() As String
  End Interface
End Interface

As for the implementation, C# does not support covariant return types, so you must declare your class like this:

public class Country : ICountry {
  // this property cannot be declared as CountryInfo
  public ICountry.ICountryInfo Info { get; set; }

  public class CountryInfo : ICountry.ICountryInfo {
    public string Note { get; set; }
    public int Population { get; set; }
  }
}
Jordão