Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interfaces cannot declare types

Tags:

c#

I have an abstract class in an API that is used by methods in another assembly. The class has a nested enum defined inside it, a bit like this:

abstract public class Thing
{
    public enum Status { Accepted, Denied, Pending };
    abstract public Status status { get; private set; }
    etc...
}

I then decided it would be a better design if Thing was an interface. But I can't do this:

public interface Thing
{
    enum Status { Accepted, Denied, Pending };
    Status status { get; }
    etc...
}

This produces the error message "Interfaces cannot declare types." However, if I move the definition of the enum outside of the interface, firstly I'd be breaking encapsulation (the Status type really belongs to Thing and is meaningless on its own) and more importantly I would have to go and modify the code in the many other assemblies that use this. Can you think of any solutions?

like image 817
Klitos Kyriacou Avatar asked Feb 21 '13 17:02

Klitos Kyriacou


People also ask

CAN interface have fields in C#?

An interface may not declare instance data such as fields, auto-implemented properties, or property-like events. By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability is important in C# because the language doesn't support multiple inheritance of classes.

What are interfaces in C#?

An interface defines a contract. Any class or struct that implements that contract must provide an implementation of the members defined in the interface. Beginning with C# 8.0, an interface may define a default implementation for members.

WHAT IS interface in asp net?

An interface is a specification for a set of class members, not an implementation. An Interface is a reference type and it contains only abstract members such as Events, Methods, Properties etc. It contain only declaration for its members and implementation defined as separate entities from classes.

Can interface inherit another interface?

An interface can extend any number of interfaces but one interface cannot implement another interface, because if any interface is implemented then its methods must be defined and interface never has the definition of any method.


1 Answers

As the error indicates, you just have to pull the definition of Status outside of the interface. I understand that it breaks encapsulation, but there's really no way around this. I suggest you change the name of Status to something which indicates a strong relation to Thing -- ThingStatus should do the trick.

enum ThingStatus { Accepted, Denied, Pending };

public interface Thing
{
    ThingStatus status { get; }
    etc...
}
like image 118
p.s.w.g Avatar answered Sep 21 '22 06:09

p.s.w.g