Access the base class method with derived class objects - c#

If I am using shadowing and if I want to access base class method with derived class objects, how can I access it?

Use the base keyword:
base.MethodOnBaseClass();
The base keyword is used to access members of the base class from within a derived class:

First cast the derived class object to base class type and if you call method it invokes base class method. Keep in mind it works only when derived class method is shadowed.
For Example,
Observe the commented lines below:
public class BaseClass
{
public void Method1()
{
string a = "Base method";
}
}
public class DerivedClass : BaseClass
{
public new void Method1()
{
string a = "Derived Method";
}
}
public class TestApp
{
public static void main()
{
DerivedClass derivedObj = new DerivedClass();
BaseClass obj2 = (BaseClass)derivedObj; // cast to base class
obj2.Method1(); // invokes Baseclass method
}
}

You qualify the method call:
base.foo();

DerivedClass derivedObj = new DerivedClass();
(derivedObj as BaseClass).Method1(); // cast to base class with method invoke

Related

C# calling overridden method from base class

I'm overriding some existing codes but try not to touch the existing classes.
I have a base class
public class A {
public virtual void Func() {
do something...
}
}
I have several other classes is accessing it by calling A.Func()
I'm writing an extension class
public class B : A {
public override void Func() {
do something else...
}
}
Without touching the base and those classes calling the base class, is there any way to point the method Func() to the extended class?
I mean when there's a class calling A.Func(), it executes the B.Func() instead A.Func()
But without touching the code from that class nor the A class
An example
public class C {
void SomeOutsideFunc()
{
var a = new A();
a.Func(); //in here, is it possible to execute the extended B class's Func()?
}
}
in above example
class A and class C is forbidden for any modification
class B is an extended class I coded.
right now, I have to make another override to class C to make things working
my issue is there are a lot of C type classes (none of those that I can make any changes)
tks
You can create the object of base class which is pointing to the child class, suppose B.
A objA=new B();
objA.Func();
This will call the function of derived class.
What you're describing is how things already work. Imagine you have these two classes:
public class BaseClass
{
public virtual void WriteSomething()
{
Console.WriteLine("base write something");
}
}
public class DerivedClass : BaseClass
{
public override void WriteSomething()
{
Console.WriteLine("derived write something");
}
}
If you create an instance of BaseClass and call WriteSomething, you get "base write something":
BaseClass instance = new BaseClass();
instance.WriteSomething();
// "base write something" is printed to the console
Likewise, creating an instance of DerivedClass and calling WriteSomething results in "derived write something":
DerivedClass instance = new DerivedClass();
instance.WriteSomething();
// "derived write something" is printed to the console
Even if we assign that instance to a BaseClass variable, we still get "derived write something":
DerivedClass instance = new DerivedClass();
BaseClass instanceAsBaseClass = instance;
instanceAsBaseClass.WriteSomething();
// "derived write something" is printed to the console
So we can clearly then pass this into a method as BaseClass but still use the overriden methods from the derived class:
public static void DoSomeThings(BaseClass instance)
{
instance.WriteSomething();
}
BaseClass instance = new DerivedClass();
DoSomeThings(instance);
// "derived write something" is printed to the console
Note that we haven't changed the DoSomeThings method.
Try it online

Downcast type to base class, removing all specific attributes [duplicate]

I'm trying to refresh my memory but can't find answers with Google.
public class BaseClass
{
public virtual void DoSomething()
{
Trace.Write("base class");
}
}
public class DerivedClass : BaseClass
{
public override void DoSomething()
{
Trace.Write("derived class");
}
}
If I create an instance of derived class, how do I convert it to it's base class so that when DoSomething() is called, it uses the base class's method only?
A dynamic cast still calls the derived class's overridden method:
DerivedClass dc = new DerivedClass();
dc.DoSomething();
(dc as BaseClass).DoSomething();
Output: "derived class"
Although this sounds irrational but it works
DerivedClass B = new DerivedClass();
BaseClass bc = JsonConvert.DeserializeObject<BaseClass>(JsonConvert.SerializeObject(B));
You can't - that's entirely deliberate, as that's what polymorphism is all about. Suppose you have a derived class which enforces certain preconditions on the arguments you pass to an overridden method, in order to maintain integrity... you don't want to be able to bypass that validation and corrupt its internal integrity.
Within the class itself you can non-virtually call base.AnyMethod() (whether that's the method you're overriding or not) but that's okay because that's the class itself deciding to potentially allow its integrity to be violated - presumably it knows what it's doing.
You absolutely CAN (call the base method), just read up on Polymorphism:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/polymorphism
Example:
public class BaseClass
{
public void DoWork() { }
public int WorkField;
public int WorkProperty
{
get { return 0; }
}
}
public class DerivedClass : BaseClass
{
public new void DoWork() { }
public new int WorkField;
public new int WorkProperty
{
get { return 0; }
}
}
And how to call it:
DerivedClass B = new DerivedClass();
B.DoWork(); // This calls the new method.
BaseClass A = (BaseClass)B;
A.DoWork(); // This calls the old method.
Try using the new keywor instead of override As far as i know this should enable that desired behavior.
I'm not realy sure about that so please don't blame me if i'm wrong!
public class BaseClass
{
public virtual void DoSomething()
{
Trace.Write("base class");
}
}
public class DerivedClass : BaseClass
{
public new void DoSomething()
{
Trace.Write("derived class");
}
}
The solutions with new instead of override break the polymorphism. Recently I came to the same problem and implemented it the following way. My solution has the following advantages:
virtual and override stays in place;
name BaseClass is not used directly in the type cast, so if I introduce an intermediate MiddleClass in the hierarchy between BaseClass and DerivedClass, which also implements DoSomething(); then the MiddleClass's implementation won't be skipped.
This is the implementation:
public class BaseClass
{
public virtual void DoSomething()
{
Trace.Write("base class");
}
}
public class DerivedClass : BaseClass
{
public override void DoSomething()
{
Trace.Write("derived class");
}
public void BaseDoSomething()
{
base.DoSomething();
}
}
The usage is:
DerivedClass dc = new DerivedClass();
dc.DoSomething();
dc.BaseDoSomething();
For VB.net, I've used the following code to do the conversion (shown with Lists of Objects):
Dim tempPartialList As New List(Of clsBaseData)
For Each iterClsDerivedData As clsDerivedData In ListOfDerivedDataObjects
tempPartialList.Add(CType(iterClsDerivedData, clsBaseData))
Next
Where clsBaseData is the Base Class from which clsDerivedData is made by Inheriting clsBaseData.
ListOfDerivedDataObjects is a List(Of clsDerivedData).
I have found this useful where I have Lists of several Derived Classes and I would like to operate on a property of the Base Class for all the objects in the Lists of Derived Classes. The tempPartialList is, for me, a temporary List meant to facilitate changing this property.

If derived class does not override the method,which version should be called?

I am trying understand the need of override and virtual in C#,so I wrote the following code:
using System;
namespace Override
{
class Base
{
public virtual void method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public override void method()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
d.method();
}
}
}
And I was expecting "Derived method" to be called and printed.Then I wrote the following code without using virtual/override combination.
using System;
namespace Override
{
class Base
{
public void method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public void method()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
d.method();
}
}
}
And I got the same result i.e. "Derived method" called and printed.My question is if the code worked without virtual/override as I expected,what is the need of them? or am I missing something here?
In your source code, you are always doing simple inheritance without any polymorphic behavior. You are always created instance of derived class and assigning it to derived class instance variable.
DerivedClass d = new DerivedClass(); // here no polymorphism, and only inheritance is there
So When you will call method using class variable, it will always call DerivedClass method, no matter if the method is virtual or not in parent class.
In Polymorphism, your programs do not know the exact type of class on which you are calling the method (this concept is called late-binding). As in example below:
BaseClass b = new DerivedClass(); // here b is a base class instance but initiated using derived class
After calling b.method() it will do late binding and will show polymorphic behavior (only if the method has been set virtual in the base class)
NOTE: The virtual keyword delays binding to correct version of method to runtime and is core keywork to implement polyphorphism. So for exact polymorphic behavior, declare methods as virtual in parent class, and then in child class, ovverride that method.
virtual allows the correct version of the method to be chosen at runtime, based on information not available at compile time. Consider the following tweak to your example:
using System;
namespace Override
{
class Base
{
public virtual void method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public override void method()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
Base b = d;
b.method();
}
}
}
With virtual/override, this code will display Derived method, as at runtime we can see that b is really a Derived instance. Without virtual/override, it will display Base method, as the declared type of b is Base.
Here is the test you are missing:
Base d = new Derived();
d.method(); // "Derived method"
Base b = new Base();
b.method(); // "Base method"
Also imagine if you had a collection of Base objects that were composed of different inherited objects. The virtual keyword allows those Base objects to understand what type they really are at runtime.
List<Base> collection = new List<Base>();
collection.Add(new Base());
collection.Add(new Derived()};
collection.Add(new Base());
foreach(Base b in collection)
{
b.method(); // will print out "Base" or "Derived" correctly
}
see the DIFFERENCE
class Base
{
public void method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public void method()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
Derived d;
d = new Derived();
d.method();
d = new Base();
d.method();
}
}
OUTPUT :
Derived method
Derived method
class Base
{
public virtual void method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public override void method()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
Derived d;
d = new Derived();
d.method();
d = new Base();
d.method();
}
}
OUTPUT :
Derived method
Base method
Base class pointers can be used to point to object of the base class or any object derived from the base. So the need of virtual methods come into picture when base class object point to derived class
Base d = new Derived();
d.method(); // "Derived method"
The method 'method' on the Derived class will hide the implementation of the Base class which is why you got the messaged "Derived method".
There are many uses of virtual and abstract but one example is where you have functionality in the base class which may not fit all cases of classes that inherit from your base class. Using virtual allows another class to completely override that functionality and provide its own implementation.

Calling base class methods with interface reference variable

I have a base class and an interface. Now I am creating a subclass from these. If I create a reference variable of the interface type to point to an object of the child class, can I access the base class methods using it?
Class BaseClass
{
public void baseClassMethod()
{
.....
}
}
Interface MyInterface
{
public void Interfacemethod();
}
Class ChildClass:BaseClass, MyInterface
{
....
}
....
main()
{
MyInterface myclass= new ChildClass ();
myclass.baseClassMethod();//Is this possible? y?
}
The variable myclass is statically typed as MyInterface, which does not have a method called baseClassMethod() - so no, that won't work. You would need to cast the reference back to BaseClasss or Child (either would be fine), or add the method to MyInterface (or some additional interface).

Instantiate a class (or derived) with internal constructor

let's say I have a class defined in an assembly with:
public class BaseClass
{
internal BaseClass()
{
}
}
And in another assembly, I would like to instanciate this class with :
BaseClass c = new BaseClass();
I get the CS0143 error.
Trying another way, I try to create a derived class of the first one :
public class DerivedClass : BaseClass
{
}
but same error.
The BaseClass is not sealed. How can I instantiate this class or a derived one? Of course, I can't modify the BaseClass.
You'll have to use reflection to get the internal constructor and invoke it:
var ci = typeof(BaseClass).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
var instance = (BaseClass)ci.Invoke(new object[0]);
Since the existence of the constructor is only discovered at run-time, this approach will break if the constructor of BaseClass is changed or removed.
1) You want an actual instance of the base class:
There needs to be some method in the assembly that it's in that constructs it for you. This would normally be called a "factory". It might look like this:
public class BaseFactory
{
public static BaseClass Create() { return new BaseClass(); } //may also add other creation logic
}
Note that such a creation method may even be in BaseClass itself, or it could be in another class. (If the constructor was private it would need to be in the class itself.)
2) You want an instance of the derived class. (Perhaps you're not supposed to be able to construct the base class. If this is true it probably should be abstract.)
public class Derived : BaseClass { }
public class Foo
{
public void Bar() { Derived d = new Derived();}
}
It's hard to tell from your question if DerivedClass is in the same assembly as BaseClass. If it is, just instantiate the derived class:
BaseClass c = new DerivedClass();
And, like Branko stated, if you have control of the project in which BaseClass lives, you can use InternalsVisibleTo.

Categories

Resources