Inheritance: Internal Class vs. Internal Interface - c#

While expressing concern with preventing exposure of base classes, I learned (through testing) that a public class cannot inherit from an internal class; however, a public class can inherit from an internal interface. I am truly curious as to why this is possible. I believe it could be due to one of (or any combination of) the following:
An interface simply contains signatures that must be implemented.
A class may have properties, methods, etc. that can be accessed via the derived type.
A class may have methods that can be overridden by derived types.
Case 1
I believe that since an interface is simply a contract that contains signatures and states that derived types must implement those signatures, the inheritance is allowed. This is due to the fact that the interface doesn't care who accesses these signatures, only that the derived type implements them.
Case 2 and 3
Unlike interfaces, classes can have public properties that can be accessed by derived types. For example:
private class A {
public int SomeProperty { get; set; } = 0;
}
public class B : A {
// Some cool code.
}
public class C : B {
public int MyInt => SomeProperty;
}
This structure has inconsistent accessibility since SomeProperty is public and can be accessed by all derived types; thus A and B must have the same access levels to prevent exposure.
Is this the reason why a public class can derive from an internal interface but not a internal class, or am I missing something? Also, are there any other reasons why this is possible?
Note
I am not looking for an opinion based answer; I am looking for the technically correct reason why this is possible.
This is not a duplicate as I wanted the reason why you can't derive from one, but you can another.

I think that the key concept you are missing is the difference between inheritance and interface implementation.
When a class inherits another class, it means it's basically a more specific type of the base class - for instance, a dog is a specific type of an animal, so when you have classes like these:
class Animal {/* implementation here */}
class Dog : Animal {/* dog implementation here */}
The Dog class already contains all the implementation of the Animal, except it's constructors (static and instance) and Finalizers.
However, when a class implements an interface, it means that it must provide the members of said interface (namely method, properties, events and indexers), so if you have an IAnimal interface and a Dog class implementing it directly, your code looks like this:
interface IAnimal
{
void Eat();
}
class Dog : IAnimal
{
public void Eat() {/* implementation here */}
}
Note that everything that the IAnimal is declaring must be implemented, explicitly or implicitly, in the Dog class - so the contract provided by the interface is preserved in the class - regardless of whether the user of the class knows the interface or not.
So in conclusion - To use the class you don't need to know anything about the interfaces it implements, but you do need to know everything that is the class, and since a Dog IS an Animal, if the Dog is public, so must be the Animal.
The IAnimal interface, on the other hand, can stay internal.
One more point about implementing internal interfaces, already mentioned on the comments to the question by user2864740 - Since all implicit interface implementations must be public - if you are implementing an internal interface, you should consider implementing it explicitly - this way the implementation stays internal and is not exposed outside of the containing assembly.

Related

What is usage of this recuring generic class?

This code is compiled in visual studio, what is it's usage
public class MyClass<T>
where T : MyClass<T>
Note where T : MyClass<T>
This is the recurring template pattern and is usually used so that a base class can refer to its real type statically. This is done in an attempt to preserve type-safety so that parameter or return values referred to in the base class track the current type in the hierarchy e.g
public class Animal<T> where T : Animal<T>
{
public abstract T GiveBirth();
}
public class Cat : Animal<Cat>
{
public override Cat GiveBirth() { return new Cat(); }
}
Without the type parameter the Animal base class method would only be able to define the return type of GiveBirth to be Animal, which may reduce type safety for the clients.
It may be acceptible if you control the entire hierarchy and can ensure that classes supply the correct type parameter, but note that it can be abused e.g.
public class Cat : Animal<Dog> { ... }
Another downside is that any clients need to take account of the generic type parameter if they want to be applied to the base class e.g.
public static void Feed<T>(Animal<T> animal) where T : Animal<T> { ... }
public static void Feed<T>(T animal) where T : Animal<T> { ... }
This is an example of the curiously recurring pattern. Eric Lippert has an excellent article on this, including why you should usually avoid it.
It might be extended like this:
public class MyChild : MyClass<MyChild>
The pattern doesn't really clue you as to why you want this generic. This is unlike most generics/constraints...e.g. if I have List<Giraffe> I can see the relationship; if I have MyGeneric<T, U> where T : IComparer<U>, I can see what T will do. With T : MyClass<T>, I really have no hints as to the relationships or usages here. Perhaps there's a...
abstract T Instance { get; }
...that you wish to have the stronger-typing of MyChild in the case of MyChild.
As an example of why this isn't so good, you could have MyOtherClass : MyClass<MyChild>, or you could have MyGrandchild : MyChild, neither of which are probably what you were trying to enforce.
For types which will only have a single layer of inheritance from an abstract base type, use of the described pattern will make it possible for the abstract base type to include methods which, when called on any member of a derived type, will return a member of that derived type. This can be a useful design feature, allowing for much cleaner caller code than would otherwise be possible. The biggest problem with this design is that because .NET has no support for covariant generic class parameters, the approach won't work with multiple layers of inheritance.
Given abstract class AnimalBase<T> where T:AnimalBase<T>, with method T Clone() and class Cat: AnimalBase<Cat>, code could say var newCat = someCat.Clone(); newCat.Meow(); rather than having to say var newCat = (Cat)(someCat.Clone()); newCat.Meow();. Unfortunately, there would be no way to have a type SiameseCat properly derives from Cat, since the only way to have mySiameseCat.Clone(); return a SiameseCat would be to have SiameseCat derive from AnimalBase<SiameseCat>, but that would prevent it from deriving from Cat.
If rather than having a class constrain to its own type, one instead defines a generic interface and constrains to that, one may avoid such difficulties. There would be no problem having SiameseCat derive from Cat while implementing IAnimal<SiameseCat>. Further, interfaces are covariant, so a type which implements IAnimal<SiameseCat> could implicitly also implement IAnimal<Cat> [if Cat was an abstract type that didn't implement the interface itself]. Every derivative of the class would have to provide its own implementations of any methods whose return value varies with the generic type parameter, but from the caller's perspective, the interface types could behave perfectly with derived classes.
It looks to be guaranteeing the type is two-dimensional (if that term makes sense here).
For example: Node<int> would end up being Node<Node<int>>.

Why do abstract classes need to define abstract methods from interfaces they implement?

When an abstract class implements an interface, it is required to also either define or declare the methods (as asked before):
public interface MyInterface
{
void Method();
}
public abstract class MyAbstractClass : MyInterface
{
public abstract void Method(); // required, even though MyAbstractClass does not implement
}
public class MyClass : MyAbstractClass
{
public override void Method()
{
}
}
public interface MyInterface2 : MyInterface
{
// no need to declare Method() -- why can't abstract classes do the same for unimplemented methods?
}
What is the design rationale of the c# language to require the definition of abstract methods of abstract classes that implement interfaces? It seems completely redundant for an abstract class to be required to define a method that it does not implement (and to make it even worse, for the class that actually implements the method to have to mark the method as override). I see no reason why an abstract class could not behave like MyInterface2, which inherits from MyInterface but does not need to declare MyInterface's methods.
An abstract class is a fully-fledged type, just except it cannot be instantiated. Hence its full contract must be declared even though some of its methods are not implemented. A user of a particular abstract class must be able to bind to all its methods, be they coming from interfaces or directly declared in the abstract class. It the methods from interfaces were not (at least) declared (if not even implemented) in the abstract class, the used couldn't bind to them.
Further, classes and interfaces are somewhat loosely-coupled. A class may declare a method, which is later mapped to a same-signature method in an interface which is implemented by its descendant. Hence it is again a “good idea” from the language-design viewpoint to require all methods of interfaces being directly implemented on an abstract class to be actually declared in it.
You can think of an interface as a detachable feature (except when explicit implementations are used). The abstract class may live on its own and its direct users need not to know of any of its interfaces.
It's a design feature that only virtual methods can be left without an implementation, because the technical mechanism of virtual methods needs to be leveraged for the whole concept of abstract classes work in practice.
UPDATE: Example:
public interface IFoo { void M(); }
public abstract class Bar : IFoo
{
public virtual abstract void M();
public void N() { }
}
public class Baz : Bar
{
public override void M() { … }
}
…
public void Method(Bar par)
{
par.M();
}
…
Baz x = new Baz();
Method(x);
The Method see the instance denoted by the variable x as Bar — neither as Baz nor as IFoo. In other words, the user of class Bar does not care of whether it implemented one, two, ten, or no interface at all. All it does is access its members. It rely's on Bar's contract, not of IFoos contract. Hence if Bar implements IFoo, it must define all members from IFoo.
A method you create in an abstract class that implements the interface doesn't need to be abstract. Abstract classes can contain non-abstract methods too and you can define a full implementation of the interface there. The inheriting classes wouldn't need to override any of those methods.
Also, this is described in MSDN for abstract classes:
An abstract class must provide implementation for all interface members.
An abstract class that implements an interface might map the interface methods onto abstract methods.
Notice the word "might", it's not "has to".
Please also note what MSDN says about implementing an interface:
When a class or struct implements an interface, the class or struct must provide an implementation for all of the members that the interface defines.
This is true for all kinds of classes and structures.
A class which implements IFoo with method void Bar() has the option of whether or not it wishes to expose a public method Bar(), or whether it wishes to use a non-public member to implement the interface [C# requires the direct implementation method to be either public or private; vb.net also allows protected scope, which is often the most useful sort for abstract classes].
There are two useful ways via which an abstract class could implement IFoo.Bar():
public abtract void Bar();
// or
protected abstract void IFoo_Bar(); // Note that the exact name is arbitrary
void IFoo.Bar() { IFoo_Bar(); }
Both implementations are reasonable. The first would make an unjustified presumption that a class would want to have a public method which appears nowhere in its code; the latter would require the compiler to 'guess' at what name should be given to the abstract method. Because there is no behavior which would be clearly better than any alternative, C# requires the programmer to specify which behavior is desired.

Abstract Class and Interface in C#

I read an article from some site and in that article i read this :
Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.
I don't understand what it means. Can anyone explain this more specifically , with a Good Example ?
this is the article which i read Link
Because interfaces only define members that types must implement, adding any new member to an interface will break any class that implements the old version because it inherently doesn't implement the new member. Any time you change the definition of an interface you must change every single class that implements that interface. Adding an abstract member to an abstract class does the same for derived classes but if you add a virtual member to the abstract class then it will have no impact on derived classes. They can be changed to override that member but they don't have to.
What it means is that if you consider a Abstract Class called Phone
and it has 3 virtual functions i.e.
AddPhonePrice , AddAccessoryPrice, AddAuxillaryPrice
and if there are two child classes
1) SamsungPhone 2) Iphone
now SamsungPhone will have implementation for all 3 functions.
while Iphone will have implementation for only AddPhonePrice, since they dont provide anything else with the phone
if we make interface called IMainPhone with
AddPhonePrice , AddAccessoryPrice, AddAuxillaryPrice functions
then both SamsungPhone and Iphone will need to implement all 3 functions
irrespective of whether they need them or not.
This means that you are able to add new members (methods, properties, fields, ...) to abstract classes that do not lead to changes in the derived classes - as long as the members are not abstract this is correct. For instance, consider this example:
internal abstract class MyBaseClass
{
public abstract void DoSomething();
// This method can also be added later without having an effect on the derived classes
public virtual void DoSomethingElse()
{
// Do something else...
}
}
internal class MyDerivedClass : MyBaseClass
{
public override void DoSomething()
{
// Do something...
}
}
In this case, the derived class has to implement the method DoSomething. But you can add non-abstract functions to the abstract base class later on. However, as soon as you add another abstract member to the base class, this also affects all non-abstract derived classes because the must implement the new members.
An interface on the other hand does not define concrete implementations at all but does only contain the abstract signature that all implementors must provide. Therefore, if you add a new member (method, property) to an interface it forces all implementors of the interface to also provide an implementation of the new members.
Interface: When you add a method to the base interface class, then you have to (manually) make sure all of the derived classes implement that method.
Abstract Base: When you add a method to an abstract base class, you aren't required by the compiler to implement that method in the derived classes.

Why does C# allow for an abstract class with no abstract members?

The C# spec, section 10.1.1.1, states:
An abstract class is permitted (but
not required) to contain abstract
members.
This allows me to create classes like this:
public abstract class A
{
public void Main()
{
// it's full of logic!
}
}
Or even better:
public abstract class A
{
public virtual void Main() { }
}
public abstract class B : A
{
public override sealed void Main()
{
// it's full of logic!
}
}
This is really a concrete class; it's only abstract in so far as one can't instantiate it. For example, if I wanted to execute the logic in B.Main() I would have to first get an instance of B, which is impossible.
If inheritors don't actually have to provide implementation, then why call it abstract?
Put another way, why does C# allow an abstract class with only concrete members?
I should mention that I am already familiar with the intended functionality of abstract types and members.
Perhaps a good example is a common base class that provides shared properties and perhaps other members for derived classes, but does not represent a concrete object. For example:
public abstract class Pet
{
public string Name{get;set;}
}
public class Dog : Pet
{
public void Bark(){ ... }
}
All pets have names, but a pet itself is an abstract concept. An instance of a pet must be a dog or some other kind of animal.
The difference here is that instead of providing a method that should be overridden by implementors, the base class declares that all pets are composed of at least a Name property.
The idea is to force the implementor to derive from the class as it is intended to provide only a basis for a presumably more specialized implementation. So the base class, while not having any abstract members may only contain core methods an properties that can be used as a basis for extension.
For example:
public abstract class FourLeggedAnimal
{
public void Walk()
{
// most 4 legged animals walk the same (silly example, but it works)
}
public void Chew()
{
}
}
public class Dog : FourLeggedAnimal
{
public void Bark()
{
}
}
public class Cat : FourLeggedAnimal
{
public void Purr()
{
}
}
I think a slightly more accurate representation of your question would be: Why does C# allow an abstract class with only concrete members?
The answer: There's no good reason not to. Perhaps someone out there has some organizational structure where they like to have a noninstantiatable class at the top, even if a class below it just inherits and adds nothing. There's no good reason not to support that.
You said it -- because you can't instantiate it; it is meant to be a template only.
It is not "really a concrete class" if you declare it as abstract. That is available to you as a design choice.
That design choice may have to do with creating entities that are (at risk of mixing the terminology) abstractions of real-world objects, and with readability. You may want to declare parameters of type Car, but don't want objects to be declarable as Car -- you want every object of type Car to be instantiated as a Truck, Sedan, Coupe, or Roadster. The fact that Car doesn't require inheritors to add implementation does not detract from its value as an abstract version of its inheritors that cannot itself be instantiated.
Abstract means providing an abstraction of behaviour. For example Vehicle is an abstract form. It doesn't have any real world instance, but we can say that Vehicle has accelerating behaviour. More specifically Ford Ikon is a vehicle, and Yamaha FZ is a vehicle. Both these have accelerating behaviour.
If you now make this in the class form. Vehicle is abstract class with Acceleration method. While you may/ may not provide any abstract method. But the business need is that Vehicle should not be instantiated. Hence you make it abstract. The other two classes - Ikon and FZ are concrete classes deriving from Vehicle class. These two will have their own properties and behaviours.
With regards to usage, using abstract on a class declaration but having no abstract members is the same as having the class public but using protected on its constructors. Both force the class to be derived in order for it to be instantiated.
However, as far as self-documenting code goes, by marking the class abstract it informs others that this class is never meant to be instantiated on its own, even if it has no virtual or abstract members. Whereas protecting the constructors makes no such assertion.
The compiler does not prevent implementation-logic, but in your case I would simply omit abstract ?! BTW some methods could be implemented with { throw Exception("must inherit"); } and the compiler could not distinguish fully implemented classes and functions including only throw.
Here's a potential reason:
Layer Supertype
It's not uncommon for all the objects
in a layer to have methods you don't
want to have duplicated throughout the
system. You can move all of this
behavior into a common Layer
Supertype.
-- Martin Fowler
There's no reason to prevent having only concrete methods in an abstract class - it's just less common. The Layer Supertype is a case where this might make sense.
I see abstract classes serving two main purposes:
An incomplete class that must be specialized to provide some concrete service. Here, abstract members would be optional. The class would provide some services that the child classes can use and could define abstract members that it uses to provide its service, like in the Template Method Pattern. This type of abstract class is meant to create an inheritance hierarchy.
A class that only provides static utility methods. In this case, abstract members don't make sense at all. C# supports this notion with static classes, they are implicitly abstract and sealed. This can also be achieved with a sealed class with a private constructor.

C# - Interface Clarification

I read some points about interface:
"
Interface is the definition of contract that a class must conform.It does not
inherit anything.
"
while defining the differece between interface and abstract class can i say :
when a class is derived from abstract class it is known as real inheritance.When a class uses interface then it is not inheritance,it is an implementation of contracts ?
yes you are right . interface is just a contract to class.
note : Interfaces don’t derive from any System.Object-derived type. An interface is simply an
abstract type that consists of a set of virtual methods, each with its own name, parameters,
and return type. Interface methods can’t contain any implementation; hence, interface types
are incomplete(abstract).
e.g :
interface I1
{
}
interface I2
{
}
abstract class a1
{
}
abstract class a2
{
}
class App:a1,I1,I2 //no Error
{
static void Main(string[] args)
{
}
}
note : The CLR allows a type to inherit from only one other type, which has System.Object as its root base type
interface I1
{
}
interface I2
{
}
abstract class a1
{
}
abstract class a2
{
}
class App:a1,a2,I1,I2 // Error
{
static void Main(string[] args)
{
}
}
Yes ..you are right just to summarize
What is an Abstract Class?
An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
What is an Interface?
An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn't support multiple inheritance, interfaces are used to implement multiple inheritance.
Both Together
When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
when a class is derived from abstract
class it is known as real
inheritance.When a class uses
interface then it is not
inheritance,it is an implementation of
contracts ?
Yes
The difference between an abstract class and an interface is that an interface does not define the implementation of any of this methods, and an abstract class provides some implementation. That's the only difference. The difference between an abstract class and a concrete class is that an abstract class has at least one member for which an implementation is not provided.
Interfaces can derive from other interfaces.
Multiple inheritance is only allowed for interfaces due to reasons which are complicated and part of the religious wars of a previous era.
When a class uses interface then it is
not inheritance,it is an
implementation of contracts
Yes, that is exactly how it is.
This may be a bit clearer if you look into what happens when you have one interface inheriting another one. That may be confusing since we just said that with interface it's not inheritance but just a contract definition. If you take the following code:
interface IA
{
void MethodA();
}
interface IB : IA
{
void MethodB();
}
class B : IB
{
public void MethodA() { }
public void MethodB() { }
}
class AB : IA, IB
{
public void MethodA() { }
public void MethodB() { }
}
If you examine the IL code of the classes B and AB (using ildasm or similar) you will find that both classes are identical when it comes to which interfaces they implement. The interface IB works as a "shortcut" to include also the interface IA, but there is no inheritance in the traditional sense involved.
The difference between an abstract class and an interface is best understood if you research the use of the two keywords in question:
C# abstract Keyword
C# interface Keyword
Essentially, an interface is a special construct that defines a code contract. It can contain no implementation whatsoever when you create it; it simply specifies the signatures of the properties and methods that the contract requires. When a class implements the interface, it must provide every property and method exactly as it is specified in the contract. It is the responsibility of the implementing class to provide the implementation.
An abstract class, however, is free to provide as much or as little implementation as it wants or needs to. It may, itself, implement an interface. All that is required of an abstract class is that it is marked abstract. Its members can be overriden by derived classes by marking the methods virtual in the abstract (base) class, and using the overrides keyword in the derived class. But the abstract base class is under no obligation to provide any functionality at all; nor is it under any obligation to provide a minimal number of virtual methods that lack implementation.
Hope this helps!
An interface is defining an interface. Just think of the word interface.
Simple.
It defines how you interact (interface!) with the class.
Just reroute your brain back around upon itself and you see the answer was right there in front of you.

Categories

Resources