Alternatives to nested interfaces (not possible in C#)

Viewed 16145

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?

5 Answers

You can use namespaces like this:

namespace MyApp
{
    public interface ICountry { }

    namespace Country
    {
        public interface ICountryInfo { }
    }
}

Then in MyApp namespace you can use Country.ICountryInfo which is close to your requirement. Also using alias helps make the code clear.

This will work just fine, no need to nest:

public interface ICountry
{
    ICountryInfo Info { get; }
}

public interface ICountryInfo
{
    int Population { get; }
    string Note { get; }
}

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.

Related