can subclass of another subclass inherit method from base class in c# - c#

Say Class A is the base class and then you have class B subclass of A (class B : A). Then you have class C : B.
Question is if you have a method in class A, can class C use that method?

Yes, you can, if it is declared public or protected. but not private.
Thanks to #DavidL.. I forgot to mention the special case of internal.
From C# Manual that comes with Visual Studio (2012 edition here)::
• Inheritance is transitive. If C is derived from B, and B is derived
from A, then C inherits the members declared in B as well as the
members declared in A. • A derived class extends its direct base
class. A derived class can add new members to those it inherits, but
it cannot remove the definition of an inherited member. • Instance
constructors, destructors, and static constructors are not inherited,
but all other members are, regardless of their declared accessibility
(§3.5). However, depending on their declared accessibility, inherited
members might not be accessible in a derived class. • A derived class
can hide (§3.7.1.2) inherited members by declaring new members with
the same name or signature. Note however that hiding an inherited
member does not remove that member—it merely makes that member
inaccessible directly through the derived class. • An instance of a
class contains a set of all instance fields declared in the class and
its base classes, and an implicit conversion (§6.1.6) exists from a
derived class type to any of its base class types. Thus, a reference
to an instance of some derived class can be treated as a reference to
an instance of any of its base classes. • A class can declare virtual
methods, properties, and indexers, and derived classes can override
the implementation of these function members. This enables classes to
exhibit polymorphic behavior wherein the actions performed by a
function member invocation varies depending on the run-time type of
the instance through which that function member is invoked.
Also this is a new hiding feature, if I am right, in C# 5.0:
A nested type may hide (§3.7.1) a base member. The new modifier is permitted on nested type declarations so that hiding can be expressed explicitly. The example
using System;
class Base
{
public static void M() {
Console.WriteLine("Base.M");
}
}
class Derived: Base
{
new public class M
{
public static void F() {
Console.WriteLine("Derived.M.F");
}
}
}
class Test
{
static void Main() {
Derived.M.F();
}
}
shows a nested class M that hides the method M defined in Base.

It depends.
When the method in class A is private: no
When the method in class A is protected: yes
When the method in class A is public: yes
When the method in class A is public or protected and virtual, class C can override that method.

Yes, when you inherit from a class you get all of it's methods, including all those it inherited from others.

public class A
{
public int Id { get; set; }
protected int protectedId { get; set; }
private int privateId;
}
public class B : A
{
}
public class C : B
{
public C()
{
int temp = Id; // works
int temp1 = protectedId; // works
int temp2 = privateId; // does NOT work
}
}
and in some other class;
public void SomeMethod()
{
C c = new C();
int i = c.Id; // works
int j = c.protectedId; // does NOT work
int k = c.privateId; // does NOT work
}

Related

Explicitly marking derived class as implementing interface of base class

interface IBase
{
string Name { get; }
}
class Base : IBase
{
public Base() => this.Name = "Base";
public string Name { get; }
}
class Derived : Base//, IBase
{
public Derived() => this.Name = "Derived";
public new string Name { get; }
}
class Program
{
static void Main(string[] args)
{
IBase o = new Derived();
Console.WriteLine(o.Name);
}
}
In this case output will be "Base".
If I explicitly state that Derived implements IBase (which is in fact already implemented by base class Base and such annotation seem to be useless) the output will be "Derived"
class Derived : Base, IBase
{
public Derived() => this.Name = "Derived";
public new string Name { get; }
}
What's the reason for such behavior?
VS 15.3.5, C# 7
It's explained in sections 13.4.4 to 13.4.6 of the C# 5 specification. The relevant sections are quoted below, but basically if you explicitly state that a class implements an interface, that triggers interface mapping again, so the compiler takes that class as the one to use to work out which implementation each interface member is mapped to.
13.4.4 Interface mapping
A class or struct must provide implementations of all members of the interfaces that are listed in the base class list of the class or struct. The process of locating implementations of interface members in an implementing class or struct is known as interface mapping.
Interface mapping for a class or struct C locates an implementation for each member of each interface specified in the base class list of C. The implementation of a particular interface member I.M, where I is the interface in which the member M is declared, is determined by examining each class or struct S, starting with C and repeating for each successive base class of C, until a match is located:
If S contains a declaration of an explicit interface member implementation that matches I and M, then this member is the implementation of I.M.
Otherwise, if S contains a declaration of a non-static public member that matches M, then this member is the implementation of I.M. If more than one member matches, it is unspecified which member is the implementation of I.M. This situation can only occur if S is a constructed type where the two members as declared in the generic type have different signatures, but the type arguments make their signatures identical.
...
13.4.5 Interface implementation inheritance
A class inherits all interface implementations provided by its base classes.
Without explicitly re-implementing an interface, a derived class cannot in any way alter the interface mappings it inherits from its base classes. For example, in the declarations
interface IControl
{
void Paint();
}
class Control: IControl
{
public void Paint() {...}
}
class TextBox: Control
{
new public void Paint() {...}
}
the Paint method in TextBox hides the Paint method in Control, but it does not alter the mapping of Control.Paint onto IControl.Paint, and calls to Paint through class instances and interface instances will have the following effects
Control c = new Control();
TextBox t = new TextBox();
IControl ic = c;
IControl it = t;
c.Paint(); // invokes Control.Paint();
t.Paint(); // invokes TextBox.Paint();
ic.Paint(); // invokes Control.Paint();
it.Paint(); // invokes Control.Paint();
...
13.4.6 Interface reimplementation
A class that inherits an interface implementation is permitted to re-implement the interface by including it in the base class list.
A re-implementation of an interface follows exactly the same interface mapping rules as an initial implementation of an interface. Thus, the inherited interface mapping has no effect whatsoever on the interface mapping established for the re-implementation of the interface. For example, in the declarations
interface IControl
{
void Paint();
}
class Control: IControl
{
void IControl.Paint() {...}
}
class MyControl: Control, IControl
{
public void Paint() {}
}
the fact that Control maps IControl.Paint onto Control.IControl.Paint doesn’t affect the re-implementation in MyControl, which maps IControl.Paint onto MyControl.Paint.
If Derived does not implement IBase and declares new string Name, that means that Derived.Name and IBase.Name are logically not the same. So when you access IBase.Name, it looks for it in Base class, implementing IBase. If you remove new string Name property, the output will be Derived, because now Derived.Name = Base.Name = IBase.Name. If you implement IBase excplicitly, the output will be Derived, because now Derived.Name = IBase.Name. If you cast o to Derived, the output will be Derived, because now you are accessing Derived.Name instead of IBase.Name.

accessibility propagation of nested types/type members

In my understanding, if we have some type T1 and a nested type T2 (or a member M2) inside T1, the accessibility of T2 (M2) is the minimum of the accessibility of T1 and T2.
By minimum I mean the accessibility I would get by searching the two accessibility levels in the below schema and taking the one that is lower:
public
|
protected internal
| |
internal protected
| |
(protected AND internal)*
|
private
(* This is not definable directly by an access modifier. It only allows access from inherited types defined inside the assembly.)
Example:
internal class T1
// internal
{
public int i;
// internal
protected class T2
// protected and internal
{
public int j;
// protected and internal
}
}
Is that correct? If not, what are exceptions to this rule?
I'm asking because in the book "Programming in C#: Exam Ref 70-483" by Wouter de Kort there is written:
Something to keep in mind is that the access modifier of the enclosing
type is always taken into account. For example, a public method inside
an internal class has an accessibility of internal. There are
exceptions to this (for example, when an internal class implements a
public interface or when a class overrides a public virtual member of
a base class), so you need to keep track of those things when
determining the accessibility of a type you need.
But there is no further explanation of what that means, and I don't get it.
If an internal class implements a public interface, this class can only be used inside the assembly. So how can the implemented interface methods be more accessible than internal? Does it have something to do with static methods?
If a child class overrides a public method of a base class, the child can only be accessed in its specified level. So how can the overridden method be more accessible if the child is not? Does it have something to do with static methods?
how can the implemented interface methods be more accessible than internal?
Here is the setup: a nested private class implements a public interface.
public interface IVisible {
void CallMe();
}
public class Outer {
private class Hidden : IVisible {
public void CallMe() {
Console.WriteLine("I'm hidden!");
}
}
public static IVisible GetObject() {
return new Hidden();
}
}
The user of this class gain access to CallMe() method of Hidden by virtue of casting it to a public interface IVisible:
IVisible obj = Outer.GetObject();
obj.CallMe(); // prints "I'm hidden!"
how can the overridden method be more accessible if the child is not?
Same setup applies: you make an accessible method that returns an instance of an inaccessible type (Hidden) as an object of its public base class or its public interface (i.e. imagine that IVisible is a class, not an interface).
Essentially, public interface (e.g. IVisible) provides a "window" into a non-public implementation (e.g. Hidden). This is a very powerful technique for controlling access to behavior that you wish to expose.

Difference between "protected" and "virtual/override"

I couldn't understand the need or purpose of "protected" when i have "virtual/override" could someone explain me what do i need those 2 things if they are almost the same.
Edit:
Thanks for all the helpers, i now understand that "protected" is only for visibility purposes, while virtual/override is for class behavior.
They are certainly not almost the same.
The protected modifier sets the visibility of a field or method: such a member can only be accessed from the class it is defined in or from a derived class.
The virtual modifier specifies that the method it is applied to can be overridden in a derived class.
These modifiers can be combined: a method can be protected and virtual.
protected means private for current class and derived classes
virtual means it can be used as-is but also be overridden in derived classes
Maybe it is better with some code instead of things you have probably already read, here is a little sample you can play with. Try removing the comments (//) and you can see that the compiler tells you that the properties cannot be accessed
[TestFixture]
public class NewTest
{
[Test]
public void WhatGetsPrinted()
{
A a= new B();
a.Print(); //This uses B's Print method since it overrides A's
// a.ProtectedProperty is not accesible here
}
}
public class A
{
protected string ProtectedProperty { get; set; }
private string PrivateProperty { get; set; }
public virtual void Print()
{
Console.WriteLine("A");
}
}
public class B : A
{
public override void Print() // Since Print is marked virtual in the base class we can override it here
{
//base.PrivateProperty can not be accessed hhere since it is private
base.ProtectedProperty = "ProtectedProperty can be accessed here since it is protected and B:A";
Console.WriteLine("B");
}
}
I can be argued that the Most important distinction about virtual, is that this causes the compiler, when calling a method member polymorphically, which implementation to bind the compiled code to. When you call a member of a class from client code where the actual type of the object is, say derived class foo, but the variable it is being called on is actually typed (declared) as some base class, say bar, Members declared as virtual will bind to the implementation in the actual object type, (or to the most derived base class of the objects type that has an implementation). Members not declared as virtual will bind to the implementation in the type that the variable is declared to be.
A. Virtual. then, if the member is declared as virtual, the implementation in the derived class will be executed even if the variable is declared as a base type.
public class Animal
{ public virtual Move() { debug.Print("Animal.Move()"); }
public class Bird: Animal
{ public virtual override Move() { debug.Print("Bird.Move()"); }
Animal x = new Bird();
x.Move(); // Will print "Bird.Move"
B. Not Virtual. When a member which is not declared as virtual, then the implementation will be chosen based on the declared type of the variable the method is executed on. So if you have a Bird Object, in variable x declared as `Animal', and you call a method that is implemented in both classes, the compiler will bind to the implementation in the Animal class, not in Bird, even though the object is really a Bird.
public class Animal
{ public Move() { debug.Print("Animal.Move()"); }
public class Bird: Animal
{ public Move() { debug.Print("Bird.Move()"); }
Animal x = new Bird();
x.Move(); // Will print "Animal.Move"
I think you need to understand above two things properly, since both has different purpose.
protected is the type or member can only be accessed by code in the same class or struct, or in a derived class.
The virtual keyword is for modify a method, property and allow it to be overridden in a derived class.

What is the difference between the override and new keywords in C#?

What is the difference between the override and new keywords in C# when defining methods in class hierarchies?
The following page summarizes your question very nicely.
Knowing When to Use Override and New Keywords
Summary
Override: When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn't "know" that the object was an instance of the derived class.
New: If you use the new keyword instead of override, the method in the derived class doesn't override the method in the base class, it merely hides it.
If you don't specify either new or overrides, the resulting output is the same as if you specified new, but you'll also get a compiler warning (as you may not be aware that you're hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword).
Override: used with virtual/abstract/override type of method in base class
New: when base class has not declared method as virtual/abstract/override
new will shadow the method with a completely new method (which may or may not have the same signature) instead of overriding it (in which case the new method must have the same signature), meaning that polymorphism won't work. For example, you have these classes:
class A {
public virtual int Hello() {
return 1;
}
}
class B : A {
new public int Hello(object newParam) {
return 2;
}
}
class C : A {
public override int Hello() {
return 3;
}
}
If you do this:
A objectA;
B objectB = new B();
C objectC = new C();
Console.WriteLine(objectB.Hello(null)); // 2
Console.WriteLine(objectC.Hello()); // 3
objectA = objectB;
Console.WriteLine(objectA.Hello()); // 1
objectA = objectC;
Console.WriteLine(objectA.Hello()); // 3
Since you can define new method signatures with new, it's impossible for the compiler to know that the instance of A is actually an instance of B and the new method B defines should be available. new can be used when the parent object's method, property, field or event is not declared with virtual, and because of the lack of virtual the compiler won't “look up” the inherited method. With virtual and override, however, it works.
I would strongly recommend you avoid new; at best, it’s confusing, because you’re defining a method with a name that could be recognized as something else, and at worst, it can hide mistakes, introduce seemingly impossible bugs, and make extending functionality difficult.
Looks like an old question, let me try a different answer:
new : as the name says, it is a new member in the family of inheritance hierarchy and this will be used as base member for further down the chain (if marked as virtual).
override : It means I don't accept my parent class' member implementation and I will do differently.
Consider the following class hierarchy:
using System;
namespace ConsoleApp
{
public static class Program
{
public static void Main(string[] args)
{
Overrider overrider = new Overrider();
Base base1 = overrider;
overrider.Foo();
base1.Foo();
Hider hider = new Hider();
Base base2 = hider;
hider.Foo();
base2.Foo();
}
}
public class Base
{
public virtual void Foo()
{
Console.WriteLine("Base => Foo");
}
}
public class Overrider : Base
{
public override void Foo()
{
Console.WriteLine("Overrider => Foo");
}
}
public class Hider : Base
{
public new void Foo()
{
Console.WriteLine("Hider => Foo");
}
}
}
Output of above codes must be:
Overrider => Foo
Overrider => Foo
Hider => Foo
Base => Foo
A subclass overrides a virtual method by applying the override modifier:
If you want to hide a member deliberately, in which case you can apply the new modifier to the member in the subclass. The new modifier does nothing more than suppress the compiler warning that would otherwise result
override lets you override a virtual method in a base class so that you can put a different implementation in. new will hide a non-virtual method in a base class.
The simple difference is that override means the method is virtual (it goes in conduction with virtual keyword in base class) and new simply means it's not virtual, it's a regular override.
So both really are function overrides, one is with virtual characteristics, the other not.
What does mean exactly? It simply means polymorphism will not be in play for `new' methods.
The following image illustration might make this clear.
Note if you don't use new keyword, it is still implied but it will generate a warning message.

What are the different purpose of "new" is available in C#

Can any one explain in the detail(with example) the different purpose of the "new" in C#.
You have:
new operator:
Used to create objects and invoke
constructors
new modifier
When used as a modifier, the new
keyword explicitly hides a member
inherited from a base class
new constraint
The new constraint specifies that any
type argument in a generic class
declaration must have a public
parameterless constructor
Object instantiation
In anonymous types
To signal that a member of the base class is being hidden.
As a constraint
About 3 (from MSDN):
public class BaseC
{
public int x;
public void Invoke() { }
}
public class DerivedC : BaseC
{
new public void Invoke() { }
}
The keyowrd is not necessary but should be used to make it clear that the base-class constructor is being hidden.

Categories

Resources