Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you define an interface such that a class that implements it must contain a member that is also of that class?

Essentially what I want to do is impliment a class that can contain a list of references to instances of the same type. Something like the following:

interface IAccessibilityFeature
{
    List<IAccessibilityFeature> Settings { get; set; }
}

class MyAccess : IAccessibilityFeature
{
    List<MyAccess> Settings { get; set; }
}

I know this won't compile because the interface explicitly says my Settings must be of the type List<IAccessibilityFeature>. What I am after is some guidance as to the correct way to achieve what I'm trying to do in the MyAccess class.

like image 322
Iain Fraser Avatar asked Feb 01 '12 01:02

Iain Fraser


People also ask

Can you define an interface in a class?

Yes, you can define an interface inside a class and it is known as a nested interface. You can't access a nested interface directly; you need to access (implement) the nested interface using the inner class or by using the name of the class holding this nested interface.

When you implement an interface all must be defined in your class?

Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class. Implement every method defined by the interface.

Can interface contain members?

Interfaces can contain instance methods, properties, events, indexers, or any combination of those four member types. Interfaces may contain static constructors, fields, constants, or operators. Beginning with C# 11, interface members that aren't fields may be static abstract .

What is an interface how it is defined and implemented?

An interface is a set of requirements to which classes must conform if they want to use the service provided by the interface. To implement an interface, first declare that your class will implement the given interface; second, define the methods in the interface.


1 Answers

Try this:

interface IAccessibilityFeature<T> where T : IAccessibilityFeature<T>
{
    List<T> Settings { get; set; }
}

class MyAccess : IAccessibilityFeature<MyAccess>
{
    List<MyAccess> Settings { get; set; }
}
like image 85
John Alexiou Avatar answered Oct 13 '22 00:10

John Alexiou