Interface implementation

I am confused about implementing interfaces.

According to MSDN, ICollection<T> has the IsReadOnly property

th -

According to MSDN Collection<T> implements ICollection<T>

-So -

I thought Collection<T> would have the IsReadOnly property.

-However -

 Collection<string> testCollection = new Collection<string>(); Console.WriteLine(testCollection.IsReadOnly); 

The above code gives a compiler error:

'System.Collections.ObjectModel.Collection<string>' does not contain a definition for 'IsReadOnly' and no extension method 'IsReadOnly' accepting a first argument of type

'System.Collections.ObjectModel.Collection<string>' could be found (are you missing a using directive or an assembly reference?)

-Although -

 Collection<string> testInterface = new Collection<string>(); Console.WriteLine(((ICollection<string>)testInterface).IsReadOnly); 

The above code works.

-Question -

I thought classes that implement interfaces should implement each property, so why testCollection n't testCollection have IsReadOnly property if you don't use it as ICollection<string> ?

+4
source share
2 answers

Interfaces can be implemented in several ways. Explicitly and implicitly.

Explicit implementation: When an element is explicitly implemented, it cannot be accessed through an instance of the class, but only through an instance of the interface

Implicit implementation: Interface methods and properties may be available to them, as if they were part of a class.

IsReadonly property is implemented explicitly, so it is not directly accessible through the class. Take a look here .

Example:

 public interface ITest { void SomeMethod(); void SomeMethod2(); } public ITest : ITest { void ITest.SomeMethod() {} //explicit implentation public void SomeMethod2(){} //implicity implementation } 
+3
source

Perhaps he explicitly implements the property.

C # allows you to define methods as "explicitly implemented methods / properties of an interface", which are only visible if you have a link to the exact interface. This allows you to provide a β€œclean” API without much noise.

+10
source

Source: https://habr.com/ru/post/1494979/


All Articles