I was reviewing some code today and came across some code (accurately portrayed by this snippet)...
public abstract class FlargBase{
public FlargBase(){
this.DoSomething();
}
public abstract void DoSomething();
}
public class PurpleFlarg: FlargBase{
public PurpleFlarg()
: base(){
}
public override void DoSomething(){
// Do something here;
}
}
The compiler gives no errors or warnings, but CodeAnalysis warns that the call chain contains a call to a virtual method and may produce unintended results.
I was curious because, as I see it, two things can happen.
Creating an instance of the base class will make a call to a method with no defined implementation. I would expect the compiler to error, or the runtime to throw an exception due to a missing implementation. I'm assuming the compiler is providing an implementation of {} I mis-typed the original code; it did contain the abstract keyword on the class.
Creating an instance of a derived class will cause a call to a method on a class that has not actually been constructed yet. I would have expected this to throw an exception.
This code has been in a production environment for several months. It is apparently working correctly enough that no one has noticed any strange behavior.
I'm hoping the incredible talent here at StackOverflow can give me some insight into the behavior and consequences of this code.
A C# object is fully constructed and initialized to zero before the first constructor runs. The base constructor will call the derived implementation of the virtual method.
It's considered bad style to do this, because the derived implementation might behave strangely when the constructor of the derived class has not been called yet. But the behavior by itself is well defined. If you do nothing in the derived implementation that requires the code from the constructor to have already run, it will work.
You can image that the runtime calls the most derived constructor first. And its first action is to implicitly call the base constructor. I'm not sure if it's actually implemented like that, but since some .net languages allow you to call the base constructor at an arbitrary point of the derived constructor, I expect C# to simply call the base class constructor as first action of the derived constructor.
This behavior is very different from how C++ handles it. In C++ the derived classes get constructed one after the other, and before the constructor of the derived class has started the object has still the type of the baseclass and the overrides from the derived class are ignored.
Your PurpleFlarg.DoSomething() is executed before the PurpleFlarg() constructor body.
That can lead to surprises as the general assumption always is that the constructor is the first method to operate on an object.
Here is the MSDN page with an example of an 'error' condition.
In C#, override methods always resolve to the most derived implementation. An example is given in 10.11.3 (Constructor execution) of the C# spec here:
Variable initializers are transformed into assignment statements, and
these assignment statements are executed before the invocation of the
base class instance constructor. This ordering ensures that all
instance fields are initialized by their variable initializers before
any statements that have access to that instance are executed.
Given the example
using System;
class A
{
public A() {
PrintFields();
}
public virtual void PrintFields() {}
}
class B: A
{
int x = 1;
int y;
public B() {
y = -1;
}
public override void PrintFields() {
Console.WriteLine("x = {0}, y = {1}", x, y);
}
}
when new B() is used to create an instance of B, the following output
is produced:
x = 1, y = 0
If the class contains an abstract method (DoSomething), then the class has to be abstract too and cannot be instantiated.
Well, this pattern is really useful for overridable factories of objects in reality, so a case like the one in the next code seems to me perfectly legal and well written.
abstract class MyBase
{
public object CustomObject { get; private set; }
public MyBase()
{
this.CustomObject = this.CreateCustomObject();
}
protected abstract object CreateCustomObject();
}
class MyBaseList : MyBase
{
protected override object CreateCustomObject()
{
return new List<int>();
}
}
class MyBaseDict : MyBase
{
protected override object CreateCustomObject()
{
return new Dictionary<int, int>();
}
}
Related
This question already has answers here:
C# How to execute code after object construction (postconstruction)
(11 answers)
Closed 2 years ago.
I have an interface that I need to implement on a few winforms and I would like to be able to call a specific method when an object is initialized.
I know I can just explicitly call the method from the constructor of the class, but it would be very nice to be able to implicitly call this method on all classes that implement the interface.
Similar to Mixins in Pyhton.
I'm not sure if an interface is the way this should be done, or just simply inheriting from another class that calls the method in it's constructor, but every class will have it's own implementation of the method so the latter might not work.
Desired result:
interface AutoRun{
void CodeToRun();
}
class Foo: AutoRun {
void CodeToRun(){
Console.WriteLine("The Code Was Ran");
}
}
class Bar: AutoRun {
void CodeToRun(){
Console.WriteLine("This Other Code Was Ran");
}
}
Foo f = new Foo(); // -> "The Code Was Ran"
Bar b = new Bar(); // -> "This Other Code Was Ran"
You could use a base class. The constructor chain will always execute for every class in the inheritance chain implicitly. For method calls, it's not completely implicit, but calling base.CodeToRun() will get you whatever base implementation is in there. You can even avoid the base.CodeToRun() call if you decide you don't want it to run.
public interface IAutoRun
{
public void CodeToRun();
}
public abstract class AutoRun : IAutoRun
{
public AutoRun()
{
Console.WriteLine("Base constructor run");
}
public virtual void CodeToRun()
{
Console.WriteLine("The code was run");
}
}
public class Foo : AutoRun
{
public Foo()
{
Console.WriteLine("Derived constructor run");
}
public override void CodeToRun()
{
Console.WriteLine("Running my derived method code");
base.CodeToRun();
}
}
An interface is just a contract. So, you cannot make it run anything. But you can always put code that must be run at object creation into a constructor.
A constructor cannot be specified in an interface. But you can call a method implementing the interface in a constructor.
If you want it to happen automatically, use an abstract base class which implements this interface and calls the code to be run in its constructor. An abstract class cannot be instantiated, and abstract members must be overridden in the deriving (non abstract) classes. In a deriving class the autorun method will then run "magically" without an explicit method call.
The naming conventions in .NET tell us to start Interface names with an upper case "I".
interface IAutoRun
{
void CodeToRun();
}
abstract class AutoRunBase : IAutoRun
{
public AutoRunBase()
{
CodeToRun();
}
public abstract void CodeToRun();
}
Now let us implement a concrete class with an auto run functionality:
class Foo : AutoRunBase
{
public override void CodeToRun()
{
Console.WriteLine("Hello World");
}
}
Note that the AutoRunBase class (I use to append "Base" to abstract classes to mark them as such) calls the not yet implemented CodeToRun method in its constructor. Since you cannot call new on an abstract class, this is not a problem, because it will be overridden in the deriving classes.
The constructor of a base class is automatically called before the constructor of the derived class (in this case Foo has an implicitly declared default constructor).
var run = new Foo(); // Prints "Hello World" to the console.
The interface is not required to make this work, but it allows to separate the contract form the implementation.
If you do not use the interface, you can also declare CodeToRun as protected instead of public and thus disallow it to be called from outside.
I was practicing inheritance, using a test program in C# and I found out that the following statement does not throw an error:
BaseClass baseObj = new DerivedClass();
Why is this statement allowed and is there a situation where this statement would be useful to a programmer?
Here is my test program:
class BaseClass
{
public void show()
{
Console.WriteLine("Base Class!");
}
}
class DerivedClass : BaseClass
{
public void Display()
{
Console.WriteLine("Derived Class!");
}
}
class Result
{
public static void Main()
{
BaseClass baseObj = new DerivedClass();
baseObj.show();
}
}
I recommend you read about inheritance and Polymorphism in more detail. (here and here)
In this answer I try to keep concepts simple enough.
Why is this statement allowed and is there a situation where this
statement would be useful to a programmer?
But in order to explain your question a bit lets take a look at simple and classic example of object oriented program that needs to use polymorphism.
Assume you are writing a program that needs to store some shapes and display them on screen. To achieve this you need to store all shapes in an array for example. right?
Suppose our classes are something like these:
class BaseShape
{
public virtual void Display()
{
Console.WriteLine("Displaying Base Class!");
}
}
class Circle : BaseShape
{
public override void Display()
{
Console.WriteLine("Displaying Circle Class!");
}
}
class Rectangle : BaseShape
{
public override void Display()
{
Console.WriteLine("Displaying Rectangle Class!");
}
}
And your array can be object array. like this:
object[] shapes = new object[10];
In your application you need to write a method to display shapes.
One solution can be iterating over all shapes and call right method of exact type of shape. like this:
public static void DisplayShapes_BAD(){
foreach(var item in Shapes)
{
if(typeof(Circle) == item.GetType())
{
((Circle)item).Display();
}
if(typeof(Rectangle) == item.GetType())
{
((Rectangle)item).Display();
}
}
}
But what happens when another type of Shape appears in application? Basically you need to modify DisplayShapes_BAD() method to support new type of Shape (add new if statement to body of method)
This way you break Open/Closed principle of object oriented programming. and your code is not much maintainable.
Better way to store shapes to avoid this bad method is to use array of BaseShape. like this:
public static List<BaseShape> Shapes = new List<BaseShape>();
Here is how to add item to this list of shapes:
Shapes.Add(new Circle());
Shapes.Add(new Rectangle());
Now take a look at good implementation of DisplayShapes method.
public static void DisplayShapes_GOOD()
{
foreach(var item in Shapes)
{
item.Display();
}
}
In above method we call Display method on item with type of BaseShape. But how C# knows to call right method (for example circle display or rectangle display). This mechanism is Polymorphism.
Complete Code shared as Gist.
As per my understanding in java,You are trying to call object of DerivedClass by using BaseClass reference varibale baseobj and this coding scenario is totally valid because it is providing the facility of runtime polymorphism.
Before runtime polymorphism lets understand the Upcasting. When reference variable of parent class is used to refer the object of child class then it is called as Upcasting
class A{}
class B extends A{}
A obj= new B // Upcasting.
Runtime Polymorphism is a process in which a call to an overridden method is resolved at runtime rather than compile-time.
Since you are not overriding show method in derived class,You are not doing runtime polymorphism but simply upcasting and upcasting is useful when we want to resolve the calling to overridden method at runntime.
First off, the question why it's allowed, is simply because an instance of the derived class is an instance of the base class (subtype polymorphism). Same goes for being able to assign any derived class to an object variable: all .net classes derive from object in the end, so you could also have done object baseObj = new DerivedClass().
The goal of the type that is used for the declaration is to indicate which type of interface is being worked with (intent). If you would declare the variable as object, you'd say that only the reference is important. If you declare as BaseClass, you say that you are using an object where the properties and methods of BaseClass are important. By using BaseClass baseObj = new DerivedClass(), you are saying you need the BaseClass functionality, but are using a DerivedClass instance to define the workings of the mapping described in BaseClass.
One reason for this could be that BaseClass is abstract (BaseClasses often are), you want a BaseClass and need a derived type to initiate an instance and the choice of which derived type should be meaningful to the type of implementation.
A reason for which it's even more often used, is because at any time, another class deriving from BaseClass can be assigned to the same variable. Consider:
BaseClass baseObj = SomeCriterium ? (BaseClass)new DerivedClass() : new AlternateDerivedClass();
The scope of the variable in the example is only in the main method, but if it were anywhere in the class, or it could be changed through a property or otherwise, by using BaseClass, anyone using your class could assign other BaseClass (derived) instance, instead of only DerivedClass (derived) instances.
Finally an example for reassigning, using an interface declaration (as far as polymorphism is concerned, the same can be applied to declaring an implemented interface instead of the class as it can to a baseclass):
IEnumerable<T> values = new List<T>();
if(needfilter)
values = values.Where(el => filtercriterium);
If values was declared as a List, the values variable could not be reused for the filtered enumeration. Basically first you say that you need the values variable only for enumeration. After that you can reassign values with another enumeration instead of only with a list.
I have been making some hamfisted attempts to apply correct OOP principles to my project. I have an abstract class called DocumentSection, and several classes deriving from it (DocumentSectionView, DocumentSectionText, etc). Similarly I have an abstract class (DocAction) with several classes deriving from it (DocumentActionReplaceByTag, DocumentSectionAppend, etc). Each DocumentSection has a DocumentAction within it.
My understanding of all this inheritance business is that by specifying a 'DocumentAction', this would allow any of those derived classes to be put in its place, and that any properties/methods from the base class would be available, as well as any specified in the concrete class I instantiate. So in the below example, I expected to be able to see the PerformAction method (leaving the virtual/override keywords out of the mix for now). And it is available.
However, because I went v.DocAction = new DocumentActionReplaceByTag();, I would also have expected my ReplaceActionFindText property to be visible.
Obviously I've got it wrong somewhere - any comments appreciated.
class Program
{
static void Main(string[] args)
{
DocumentSectionView v = new DocumentSectionView();
v.DocAction = new DocumentActionReplaceByTag();
// would like to go:
//v.DocAction.ReplaceActionFindText...
Console.ReadLine();
}
}
public abstract class DocumentSection
{
public abstract string GetContent();
public DocumentAction DocAction { get; set; }
}
public class DocumentSectionView : DocumentSection
{
public string ViewPath { get; set; }
public dynamic ViewModel { get; set; }
public override string GetContent()
{
return "test";
}
}
public abstract class DocumentAction
{
void PerformAction(StringBuilder sb, string content);
}
public class DocumentActionReplaceByTag : DocumentAction
{
public string ReplaceActionFindText { get; set; }
public void PerformAction(StringBuilder sb, string content)
{
sb.Replace(ReplaceActionFindText, content);
}
}
EDIT:
I've marked an answer as correct, but thought I'd add the fruits of my further thought on this matter for those coming across this later:
a) As pointed out, my intentions were broadly right but my method wrong. Setting the 'Action's property from the Main method was not correct. In all cases, a a DocumentActionReplaceByTag requires the FindText so I placed it in the constructor:
public DocumentActionReplaceByTag(string replaceActionFindText)
{
this.ReplaceActionFindText = replaceActionFindText;
}
From then on, a constructor with 0 arguments will rightly fail, and prevent a case where the action is executed but no findtext is specified.
b) Polymorphism works fine now, because my extra property findtext has been populated, and running PerformAction will run correctly regardless of the action type.
Because you are assigning your derived class to a property with the type of the base class only the methods and properties of the base class will be available. And this makes sense since you could have assigned any instance of a class that derives from the base class - so any derived methods cannot be used in this context.
This is one of the OOP principles - your derived class instances may be used as an instance of a base class (but not the other way round)
Edit:
To elaborate on the solution proposed by #sll to cast to a particular derived class type: Don't do it! It is a workaround but not in the interest of the overall design.
If you have to cast to a derived type then you are violating the Liskov substitution principle meaning that any derived type should be usable in place of the base type - that's clearly not the case if you need a specific cast.
Rethink your design - do you really need a property with the base class type and if so are the methods currently only in one particular derived type better off being in the base type as well?
The v reference type is of the DocumentSectionView which is not aware of methods of the DocumentActionReplaceByTag class even underlying instance is of DocumentActionReplaceByTag as you've assigned it. You need to cast it to be able accesing derived class members:
((DocumentActionReplaceByTag)v.DocAction).ReplaceActionFindText
Also in some cases this is pretty fine when underlying instance could not be casted so some part of code should be skipped, then you can use exception-safe way of casting using as operator:
var typedAction = v.DocAction as DocumentActionReplaceByTag;
if (typedAction != null)
{
// accessing the typedAction.ReplaceActionFindText property
}
My suggestions are only to help you understand C# side of question, regarding overall design and approach please see BrokenGlass's answer.
No, in your example, since DocAction is only a DocumentAction, you will only be able to see the properties of a DocumentAction, no matter which derived type of DocumentAction is used.
When calling methods on a base class from a derived class, should the 'base' keyword be used? It seems using the base keyword would increase code readability but for me so far, when I exclude it, there is no affect on code compilation and execution.
The base keyword is important when overriding methods:
override void Foo()
{
base.Foo();
// other stuff
}
I never use it for anything else.
You should not use base unless you specifically mean "Even if there is a method in this class that overrides the base implementation, I want to call the base implementation and ignore the one on this class".
Using base bypasses the virtual dispatch mechanism that is so important in polymorphism by causing a call instruction to be emitted rather than callvirt.
So saying base.Foo() is very, very different in semantics to saying this.Foo(). And you almost always want the latter.
It does matter if you have overridden a method:
class Test {
public override string ToString() { return "Hello World"; }
public string M1() { return ToString(); } // Test.ToString
public string M2() { return base.ToString(); } // System.Object.ToString
static void Main() {
var t = new Test();
Console.WriteLine("M1: {0}", M1()); // Hello World
Console.WriteLine("M2: {0}", M2()); // Test
}
}
Sometimes, you can't avoid it. If your class overrides an implementation of a function from the base class, then without the base keyword, calls could be dispatched to the implementation in your class.
In all other situations, it's a matter of style (much like "Should I prefix all calls/field accesses with this). I say "No" as it tends to increase code clutter without significantly helping readability, but "Yes" is just as valid an answer - especially if you have a class with many overridden methods, but will be including many calls upwards in the hierarchy.
I'd say no. The main purpose of base is to allow you to call base class versions of virtual methods without virtual dispatch taking place. Personally, I consider any other use of base to be an abuse - it doesn't really buy you anything over just calling a method as usual (or using this), and it will break if you later override the called method in your class.
Also, there is a very real difference if the method is virtual, and someone down the line overrides it. To give an example, say you write this (in a reusable class):
class Base {
public virtual void Foo() {}
}
class Derived : Base {
void Bar() { base.Foo(); }
}
And later on someone else who uses your class writes:
class MoreDerived : Derived {
public override void Foo() {}
}
Now your base.Foo() will not do dynamic dispatch, and therefore will not call the overridden Foo() in MoreDerived. It may be what you actually want, but I'd find such a code very suspect if that was the intent.
There are times when the base keyword has to be used such when you want to call a method in the base class that's been overidden in the derived class.
Look to this example:
class ParentClass {
public virtual void A() {
// Some operations
}
}
class ChildClass : ParentClass {
public override void A()
{
base.A();
}
}
If we execute ChildClass.A() then we have some operations, but in this case:
class ParentClass {
public virtual void A() {
Console.WriteLine("ParentClass.A");
}
}
class ChildClass : ParentClass {
public override void A()
{
A();
}
}
we have StackOverflowException, because ChildClass.A() execute ChildClass.A()
There will be no difference in the generated IL in most cases.
However, if you are overriding a virtual method in the base class, or hiding a method in the base class using the "new" keyword, then this is required, and will change the meaning, since it explicitly calls the base class method.
However, it is often a good idea, since it improves readability, and hence maintainability. If you are explicitly wanting to call a method in the base class, then I feel that it's a good idea, even when not technically required.
In C# what does the term shadowing mean? I have read this link but didn't fully understand it.
Shadowing hides a method in a base class. Using the example in the question you linked:
class A
{
public int Foo(){ return 5;}
public virtual int Bar(){return 5;}
}
class B : A
{
public new int Foo() { return 1;}
public override int Bar() {return 1;}
}
Class B overrides the virtual method Bar. It hides (shadows) the non-virtual method Foo. Override uses the override keyword. Shadowing is done with the new keyword.
In the code above, if you didn't use the new keyword when defining the Foo method in class B, you would get this compiler warning:
'test.B.Foo()' hides inherited member 'test.A.Foo()'. Use the new keyword if hiding was intended.
Overriding : redefining an existing method on a base class
Shadowing : creating an entirely new method with the same signature as one in a base class
Suppose I have a base class that implements a virtual method:
public class A
{
public virtual void M() { Console.WriteLine("In A.M()."); }
}
I also have a derived class that also defines a method M:
public class B : A
{
// could be either "new" or "override", "new" is default
public void M() { Console.WriteLine("In B.M()."); }
}
Now, suppose I write a program like this:
A alpha = new B(); // it's really a B but I cast it to an A
alpha.M();
I have two different choices for how I want that to be implemented. The default behavior is to call A's version of M. (This is identical to the behavior if you applied the "new" keyword to B.M().)
This is called "shadowing" when we have a method with the same name but a different behavior when called from the base class.
Alternately, we could have specified "override" on B.M(). In this case, alpha.M() would have called B's version of M.
Shadowing consist on hiding a base class method with a new definition in a child class.
The difference between hiding and overriding has to do with the way methods are invoked.
That way, when a virtual method is overridden, the call address for the method call table of the base class is replaced with the address of the child routine.
On the other hand, when a method is hidden, a new address is added to the method call table of the child class.
When a call is made to the method in question:
The method call table class type is obtained, if we are invoking with a reference to the base class then the base class method table is obtained, if we have a reference to the child class, then the child class method table is obtained.
The method is searched in the table, if it's found then the invocation takes place, otherwise the base class method table is searched.
If we invoke the method with a reference to the child class then the behavior is the same, if the method has been overridden, the method address will be found in the base class, if the method was hidden the method address will be found on the child class, and since it has been already found, base class table will not be searched.
If we invoke the method with a reference to the base class then behavior changes. When overriding, as the method address overwrites base class entry, we will call the child method, even when holding a reference to the base class. With shadowing, the base class method table (which is the only one visible as we hold a reference to the base class) contains the virtual method address, and therefore, the base class method will be called.
In general shadowing is a bad idea, as it introduces a difference on the behavior of an instance depending on the reference we have to it.
Expanding on Kent's correct answer
When disambiguating when which method will be called, I like to think of shadowing vs. overriding with the following
Shadowing: The method called depends on the type of the reference at the point the call is made
Overriding: The method called depends on the type of the object at the point the call is made.
Here's an MSDN article on Shadowing. The language examples are in Visual Basic (unfortunately there is no equivalent C# page on MSDN), but it deals generally with the concepts and hopefully should help you understand anyway.
Edit: Seems like there is a C# article on shadowing, except that it's called hiding in C#. Also, this page offers a good overview.
If you want to hide Base class method , Use override in base [virtual method in base]
if you want to hide Child class method , Use new in base [nonvirtual method in base]->shadow
Base B=new Child()
B.VirtualMethod() -> Calls Child class method
B.NonVirtualMethod() -> Calls Base class method
Overriding: same name and exactly the same parameters, implemented
differently in sub classes.
If treated as DerivedClass or BaseClass, it used derived method.
Shadowing: same name and exactly the same parameters, implemented differently in sub classes.
If treated as DerivedClass, it used derived method.
if treated as BaseClass, it uses base method.
Hope this brief explanation helps.
Shadowing - Replaces the complete element of the parent class
class InventoryAndSales
{
public int InvoiceNumber { get; set; }
}
//if someone calls for this class then the InvoiceNumber type is now object
class NewInventoryAndSales : InventoryAndSales
{
public new object InvoiceNumber { get; set; }
}
Overriding - Only replaces the implementation. It doesn't replace the data type it doesn't replace like for example you have a variable it doesn't convert it into a method so if there is a method it will use that method and only changed the implementation
class InventoryAndSales
{
public virtual int GetTotalSales(int a, int b)
{
return a + b;
}
}
class NewInventoryAndSales : InventoryAndSales
{
//it replaces the implementation in parent class
public override int GetTotalSales(int a, int b)
{
return a * b;
}
}
Shadowing isn't something I'd be worried about understanding or implementing unless it "fits" the problem really well. I've seen it used improperly and cause weird logic bugs much more often than being used correctly. The big cause, I think, is when the programmer forgets to put overrides in a method signature then the compiler warning will suggest the new keyword. I've always felt that it should recommend using override instead.
private static int x = 10;
static void Main(string[] args)
{ int x = 20;
if (Program.x == 10)
{
Console.WriteLine(Program.x);
}
Console.WriteLine(x);}
Output:
10
20