must be accessible from the derived class. The derived class will use the override
keyword.
Code:
public class Base
{
Int32 _x;
public virtual Int32 MyProperty
{
get
{
return _x;
}
}
public virtual void DoSomething()
{
_x = 13;
}
}
public class Derived : Base
{
public override Int32 MyProperty
{
get
{
return _x * 2;
}
}
public override void DoSomething()
{
_x = 14;
}
}
it. For example, the following will print “28,” not “13.”
Code:
Base d = new Derived(); d.DoSomething(); Console.WriteLine(d.MyProperty().ToString());
Code:
public class Base
{
public virtual void DoSomething()
{
Console.WriteLine(“Base.DoSomething”);
}
}
public class Derived
{
public virtual void DoSomething()
{
base.DoSomething();
Console.WriteLine(“Derived.DoSomething”);
}
}
Code:
Base.DoSomething Derived.DoSomething
You can still override it, but with a caveat: The override method will only be called through a reference to the derived class. To do this, use the new keyword (in a different context than you're probably used to).
Code:
class Base
{
public virtual void DoSomethingVirtual()
{
Console.WriteLine(“Base.DoSomethingVirtual”);
}
public void DoSomethingNonVirtual()
{
Console.WriteLine(“Base.DoSomethingNonVirtual”);
}
}
class Derived : Base
{
public override void DoSomethingVirtual()
{
Console.WriteLine(“Derived.DoSomethingVirtual”);
}
public new void DoSomethingNonVirtual()
{
Console.WriteLine(“Derived.DoSomethingNonVirtual”);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(“Derived via Base reference:”);
Base baseRef = new Derived();
baseRef.DoSomethingVirtual();
baseRef.DoSomethingNonVirtual();
Console.WriteLine();
Console.WriteLine(“Derived via Derived reference:”);
Derived derivedRef = new Derived();
derivedRef.DoSomethingVirtual();
derivedRef.DoSomethingNonVirtual();
}
}
Derived via Base reference:
Derived.DoSomethingVirtual
Base.DoSomethingNonVirtual
Derived via Derived reference:
Derived.DoSomethingVirtual
Derived.DoSomethingNonVirtual
Make sure you understand why the output is the way it is.
