C# - Using overriden getter - c#

I have a project called Common along with several other projects. Inside the Common project, I have a class named ItemBase. Inside that class, I have a virtual getter called CachedReference, it looks like so:
public virtual ItemData CachedReference
{
get
{
return new ItemData();
}
}
Now, I'm returning an empty ItemData object because I want the classes that inherit from ItemBase to override this getter so it will refer to the overriden getter and not the default one (I would make it an abstract class, but I can't because the Common project initializes instances of this class).
In my other projects I have a class named Item which inherits from the ItemBase class and overrides the getter. It looks like so:
public override ItemData CachedReference
{
get
{
return LoginServer.Instance.ItemDataProvider[this.MapleId];
}
}
The constructor of the ItemBaseclass uses the CachedReference property to set it's data. However, when I initialize a new instance of the Itemclass that uses the default constructor of ItemBase, it refers to the default getter rather than the overriden one.
Why's that happening? I want to refer the overriden getter only, not the default one so each project can return it's own CachedReference.
EDIT: I've been asked to show how I use CachedReference, so here:
public ItemBase(int mapleId, short quantity = 1)
{
this.MapleId = mapleId;
this.Quantity = quantity;
this.WeaponAttack = this.CachedReference.WeaponAttack;
...
}

This code works as you expect. Can you provide a compilable code of your's that demonstrates your problem?
public static void Main()
{
var derived = new Derived();
}
public class Base
{
protected string _p = "Base";
public virtual string P
{
get { Console.WriteLine("Base get"); return _p; }
set { Console.WriteLine("Base set"); _p = value; }
}
public Base()
{
P = "Base constructor";
}
}
public class Derived : Base
{
public override string P
{
get { Console.WriteLine("Derived get"); return _p; }
set { Console.WriteLine("Derived set"); _p = value; }
}
public Derived()
{
Console.WriteLine(P);
}
}
Output:
Derived set
Derived get
Base constructor

Related

unable to override a Virtual Property from an inherited Class

My Custom Sitecore control inherits from Sitecore.Web.UI.HtmlControls.Control. This Class defines the Property Value as follows:
public virtual string Value {
get {
return this.GetViewStateString("Value");
}
set {
if (!(value != this.Value))
return;
this.SetViewStateString("Value", value);
}
}
My custom class is defined as follows:
public class ClientProfileSelector : Sitecore.Web.UI.HtmlControls.Control, IContentField {
...
public override string Value {
get {
return this.MyOwnValue;
}
set {
if (!(value != this.MyOwnValue))
return;
this.MyOwnValue = value;
}
}
...
}
The code of the entire class is available here.
My class is automatically instantiated by Sitecore, but I know it is running because I can step into other methods defined therein. For example the method GetValue() in my custom class calls the field Value like so:
public string GetValue() {
return string.IsNullOrEmpty(CalculatedValue) ? CalculatedValue : Value;
}
but when I step over it after adding breakpoints in both my definition and the base class' one, the execution stops in the base class.
What am I doing wrong?

Notify in derived class when a property has changed in the base class

I want to execute some code on derived Form whenever a specific property changes in the base Form.
A form implements some common stuff on forms (skining, etc)
Example:
abstract class A
{
private bool _value;
public abstract void Execute();
public A()
{
_value = false;
}
public bool Value
{
get
{
return _value;
}
set
{
_value = value;
if (value)
{
Execute();
}
}
}
}
class B : A
{
public B()
{
}
public override void Excute()
{
// Do some stuff here
}
}
I have been dealing with abstract methods, but I cannot figure how to solve it.
If I declare A as abstract I cannot open B in the designer.
In fact, the real code is a bit more complex, because I have an A base class (a form with the common functions) and B, C, D wich are derived forms more specific: B with button navitagion, C for special forms, etc. So when I create a form in my application, I must inherit from B, or C, ...
Thanks for your help
You can declare the property as virtual in your base class, then override it in your derived class, calling your Foo method from the derived class's setter. Due to polymorphism, your derived property will always be accessed, even when your object is referenced as a base class instance.
class A
{
public virtual bool Value { get; set; }
}
class B : A
{
public override bool Value
{
get
{
return base.Value;
}
set
{
if (base.Value != value)
{
base.Value = value;
Foo();
}
}
}
private void Foo()
{
// code I want to run when base class property changes
}
}

How to Get Base Class Instance from a Derived Class

I don't know if this is possible, but I am trying to get the Base Class instance from a Derived Class. In C#, I can use the base keyword to access properties and methods of the Base Class (of course), but I want to use base itself. Attempting to do so results in a "Use of keyword 'base' is not valid in this context" error.
Example Code
public class SuperParent
{
public int SPID;
public SuperParent()
{
}
}
public class SubChild : SuperParent
{
public SubChild(int pSPID)
{
base.SPID = pSPID;
}
public int BaseSPID
{
get
{
SuperParent sp = base;
return sp.SPID;
}
}
}
If you're working with an instance of the derived class, there is no base instance.
An example:
class A
{
public void Foo() { ... }
}
class B : A
{
public void Bar() { ... }
}
What is not possible within B:
public void Bar()
{
// Use of keyword base not valid in this context
var baseOfThis = base;
}
You can do something like this:
public void Bar()
{
base.Foo();
}
And you can add another method like
public A GetBase()
{
return (A)this;
}
And then you can
public void Bar()
{
var baseOfThis = GetBase();
// equal to:
baseOfThis = (A)this;
}
So this GetBase() method is probably what you want.
The punchline is: If you have an instance of B, it inherits all properties and the non-overriden behaviour of A, but it does not consist of an instance of B which holds an (hidden but automatic) reference to an instance of A. You can cast your B instance to A, but it remains to be an instance of B.
Well you not provide code for your question, but i supsect you want something like
class Base
{
public virtual void Foo()
{
Console.WriteLine("base");
}
}
class Derived : Base
{
public override void Foo()
{
Console.WriteLine("derived");
}
//// bad
//public Base MyBase
//{
// get
// {
// return base; // Use of keyword 'base' is not valid in this context
// }
//}
// work but...
public Base MyBase
{
get
{
return (Base)this;
}
}
}
But keep in mind that MyBase is really of type Derived
new Derived().MyBase.Foo(); // output "derived"
the problem hasn't been explained as clearly as it could. however, typically, you may be better to use an abstract base class and methods and then override the required methods. you can then use the base.method as required in this case (otherwise you'll have just spun up an instance of the derived class).
public abstract class foo {
public virtual void bar(){..}
}
public class footwo : foo {
public override void bar(){
// do somethng else OR:
return base.bar();
}
}
}
The derived instance IS the base instance. It's just one object instance in memory.
example:
public class A : B
{
}
var thing = new A();
thing is an instance of an A, and is also an instance of a B.
You could for example, write this line:
B thing2 = thing;
Point 1: if you want to create the base class instance within child class than it does not worth. You already have public things accessible in child.
Point 2: If you have initialized child class and now want to get base class "instance" then how can you get that if it's not initialized(Because now the base class instance is not present in the physical memory, and there is just child class instance there)?
I interpreted what they were asking a bit differently than the other answers here so I figured I would offer my $0.02.
// Create a "Parent" class that has some attributes.
public class Parent
{
public string attribute_one { get; set; }
public string attribute_two { get; set; }
public string attribute_three { get; set; }
}
// Define a class called "Child" that inherits the
// attributes of the "Parent" class.
public class Child : Parent
{
public string attribute_four { get; set; }
public string attribute_five { get; set; }
public string attribute_six { get; set; }
}
// Create a new instance of the "Child" class with
// all attributes of the base and derived classes.
Child child = new Child {
attribute_one = "interesting";
attribute_two = "strings";
attribute_three = "to";
attribute_four = "put";
attribute_five = "all";
attribute_six = "together";
};
// Create an instance of the base class that we will
// populate with the derived class attributes.
Parent parent = new Parent();
// Using reflection we are able to get the attributes
// of the base class from the existing derived class.
foreach(PropertyInfo property in child.GetType().BaseType.GetProperties())
{
// Set the values in the base class using the ones
// that were set in the derived class above.
property.SetValue(parent, property.GetValue(child));
}
The result is a new object populated with the base class properties of the child class.
class Parent
{
private Parent _parent;
public Parent()
{
_parent = this;
}
protected Parent GetParent()
{
return _parent;
}
}
class Child : Parent
{
private Parent _parent;
public Child()
{
_parent = base.GetParent();
}
}

Are methods "virtual" by default or "not virtual"?:

According to this similar StackOverflow question and other articles, C# methods are "not virtual" by default, which I take it to mean that you cannot override them in a derived class.
If that is true, could you please explain to me how, in the example below, how I am able to implement the property LastName in the Child class which inherits from Base class without the property being marked as "virtual" inh the base class? Does the Child.LastName property "hide" (VB "Shadows") the same property in the base class? if so, why is the "new" key word not used in the Child.LastName pproperty to indicate this?
This test example seems to suggest to me that methods and virtual by default and, in the case of the LastName property, "overrrides" is implied, but I'm pretty sure that this is not the case.
What am I missing?
public class BaseClass
{
private string _FirstName;
public virtual string FirstName {
get { return _FirstName; }
set { _FirstName = value; }
}
private string _LastName;
public string LastName {
get { return _LastName; }
set { _LastName = value; }
}
public void Go()
{
MessageBox.Show("Going at default speed in Base Class");
}
public void Go(int speed)
{
MessageBox.Show("Going at " + speed.ToString() + " in Base Class");
}
}
public class Child : BaseClass
{
public override string FirstName {
get { return "Childs First Name"; }
set { base.FirstName = value; }
}
public string LastName {
get { return "Child's Last Name"; }
set { base.LastName = value; }
}
public void Go()
{
MessageBox.Show("Going in Child Class");
}
public void Go(int speed)
{
MessageBox.Show("Going at " + speed.ToString() + " in Child Class");
}
}
Methods are not virtual in C# by default. LastName in Child class hides the LastName from the BaseClass. As far as i can remember, this code can even compile, but warning will be provided by compiler, telling that new keyword should be used.
They're non-virtual by default.
The subclass hides the base's LastName property.
If you write:
BaseClass b = new Child(...);
Console.WriteLine(b.LastName);
You will see the base implementation is called.
The compiler will warn you about this when you compile the above code. It's standard practice to mark a member which hides a base's member as new.
public new string LastName {
get { return "Child's Last Name"; }
set { base.LastName = value; }
}
This is a very common C# programming interview question :)
A good understanding of Polymorphism will clear this up:
Polymorphism (C# Programming Guide)
Hiding Base Class Members with New Members
If you want your derived member to have the same name as a member in a base class, but you do not want it to participate in virtual invocation, you can use the new keyword. The new keyword is put before the return type of a class member that is being replaced. The following code provides an example:
public class BaseClass
{
public void DoWork() { WorkField++; }
public int WorkField;
public int WorkProperty
{
get { return 0; }
}
}
public class DerivedClass : BaseClass
{
public new void DoWork() { WorkField++; }
public new int WorkField;
public new int WorkProperty
{
get { return 0; }
}
}
Hidden base class members can still be accessed from client code by casting the instance of the derived class to an instance of the base class. For example:
DerivedClass B = new DerivedClass();
B.DoWork(); // Calls the new method.
BaseClass A = (BaseClass)B;
A.DoWork(); // Calls the old method.
Preventing Derived Classes from Overriding Virtual Members
Virtual members remain virtual indefinitely, regardless of how many classes have been declared between the virtual member and the class that originally declared it. If class A declares a virtual member, and class B derives from A, and class C derives from B, class C inherits the virtual member, and has the option to override it, regardless of whether class B declared an override for that member. The following code provides an example:
public class A
{
public virtual void DoWork() { }
}
public class B : A
{
public override void DoWork() { }
}
A derived class can stop virtual inheritance by declaring an override as sealed. This requires putting the sealed keyword before the override keyword in the class member declaration. The following code provides an example:
public class C : B
{
public sealed override void DoWork() { }
}
In the previous example, the method DoWork is no longer virtual to any class derived from C. It is still virtual for instances of C, even if they are cast to type B or type A. Sealed methods can be replaced by derived classes by using the new keyword, as the following example shows:
public class D : C
{
public new void DoWork() { }
}
In this case, if DoWork is called on D using a variable of type D, the new DoWork is called. If a variable of type C, B, or A is used to access an instance of D, a call to DoWork will follow the rules of virtual inheritance, routing those calls to the implementation of DoWork on class C.
well, you got it right. If it's not virtual, it gets hidden.
The new keyword brakes the virtual overriding in the inheritance hierarchy chain.
Simple example to read: Polymorphism, Method Hiding and Overriding in C#

Populate base class along with child class?

I have a need where I have to add some new fields to an existing class along with all its existing fields/attributes.
So whenever my derived class is filled by DAL, I will be filling all fields of base class as well. Currently, I am doing it like this but not sure this is the right way ? Please give me an example. Also I am not sure whether the base class object will be a new one each time a derived class is initialized ?
public class Employee
{
private int _id;
private int _name;
public int ID
{
set { _id=value;}
get { return _id;}
}
public int Name
{
set { _name=value;}
get { return _name;}
}
protected void SetName ()
{
_name=value;
}
protected void SetID()
{
_id=value;
}
}
public class EmployeeWithDepartmentName:Employee
{
private string _deptName;
public string DeptName
{
set { _deptName=value; }
}
public setBaseEmpName()
{
base.SetName();
}
public setBaseID()
{
base.SetID();
}
}
Everything in a base class can automagically be accessed from derived classes without doiing anything, just use the property/method name directly.
public class MyBase
{
public string UserName {get;set;}
}
public class MyClass : MyBase
{
public void DoSomething()
{
Console.WriteLine("UserName: {0}", UserName);
UserName = "Anders";
}
}
You can also do this:
MyClass myClass = new MyClass();
myClass.UserName = "Rune";
Protected means that only derived classes can access the property/method. Public means that everyone can access the properties/methods.
Also I am not sure whether the base class object will be a new one each time a derived class is initialized ?
It's not two objects, it's one object created from two different classes (that's how inheritance works).
Read this article about inheritance: http://www.csharp-station.com/Tutorials/lesson08.aspx

Categories