issue of virtual method in C# - c#

In MSDN, it is mentioned,
http://msdn.microsoft.com/en-us/library/9fkccyh4(VS.80).aspx
I am confused what does this item mean "A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier."?
(this is the 2nd differences between virtual and abstract)
thanks in advance,
George

The only difference between virtual and abstract, is that an abstract method or propery has no implementation in the class where it has been defined (the abstract class), and that it must be overriden in a subclass; whereas a virtual method or property has an implementation in the class where it has been defined, and so it is not mandatory to override it in a subclass.
public abstract AbstractClass
{
// This class cannot be instantiated, since it is
// abstract, and the class is abstract because
// it has an abstract member
public abstract MyProperty {get; set; }
}
In a class where you derive from AbstractClass (the above AbstractClass is just for explanation purposes; since it has no methods / properies that have an implementation, you could create an interface instead of an abstract class), you will have to provide an implementation of MyProperty. Otherwise, it won't compile.
You do this by 'overriding' the MyProperty, you don't want to introduce a new member, but just provide an implementation for a property that has been defined previously.
public class ConcreteClass : AbstractClass
{
public override MyProperty {
get
{
return _someValue;
}
set
{
if( _someValue != value ) _someValue = value;
}
}

I can understand the confusion. I have been there before, so I'll share how I keep the basic differences straight...
virtual vs. abstract:
If a class method (or property) is
marked virtual, then it may be
overridden using the override
keyword, if you choose to inherit
(aka derive) from that class. The virtual keyword is intended to evoke the idea that the method may or may not be the actual method called. Therefore, I always think of virtual members as default implementations, meaning that it represents functionality that can be generalized, such as an Eat() method on a Human class, which might involve eating with one's hands. However, a ChineseHuman class might override the default implementation of Eat(), in order to allow for an implementation that uses chop sticks instead. Finally, because virtual methods and properties are default implementations, the class that defines that member must provide a complete implementation of the method or property. All Human objects must know how to Eat(). An object-oriented way of thinking might declare that virtual members represent instincts. To Eat() is an instinct of a Human class object. A ChineseHuman may learn to Eat() with chop sticks.
If a class method (or property) is
marked abstract, then it must
be overridden using the override
keyword, if you choose to inherit
from that class.The abstract keyword is intended to evoke the idea that the class only supports the capability represented by the member, and that there is not any common logic that can be generalized for that feature. In other words, abstract members are only conceptual, and therefore they lack an implementation. It is a little confusing that C# asks us to override abstract members when we implement an inheritance relationship, but in this case it really means that we are overriding the empty concept with a concrete implementation. An example of an abstract member of a Human class might be Speak(). There would not be a common way of speaking for all Human objects, nor is it instinctual, because it requires language to express. Note: Some might argue that Speak() belongs on an interface instead.An object-oriented way of thinking might declare that abstract members represent behavior (methods) to be learned and knowledge or beliefs (properties) to be acquired. To Speak() is a learned behavior of a Human class object. A ChineseHuman may learn to Speak() differently than an EnglishHuman and neither knows how to Speak() just because they are both Human.
Nuances:
virtual methods do NOT need to be overridden.
There is no such thing as a virtual class.
abstract members can only appear on abstract classes. In the above examples, having an abstract method on the Human class implies that Human is an abstract class, and that, therefore, a Human cannot be instantiated using the phrase var baby = new Human();. Instead, the BabyHuman class should inherit from Human, and it should be instantiated as var baby = new BabyHuman();. Because a BabyHuman() is a Human and EnglishHuman and ChineseHuman both also inherit from Human, EnglishHuman could inherit from BabyHuman instead of Human. Being Human is abstract because we are all something more than simply Human.
abstract members cannot be hidden, only their override implementations may be (further up the inheritance chain). For example, BabyHuman must implement the abstract Speak() method as an override. If EnglishHuman inherits from BabyHuman, it may then hide the BabyHuman implementation of Speak() with its own implementation by using the new keyword (see "Method Hiding in C#" reference below).
abstract classes can have virtual members. That's a main distinction between an interface and an abstract class. In that sense, an abstract class can define both a contract and a template of the class' behavior, whereas an interface only defines a contract.
Code Reference:
Abstract Class versus Interface
By Rahman Mahmoodi
http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx
Method Hiding in C#
By Chetan Kudalkar
http://www.codeproject.com/KB/cs/cs_methodhiding.aspx

Can you explain what's confusing about it? Properties can be overridden like any other method.
public class Base {
public virtual int Prop1 { get { ... } set { ... } }
}
public class Derived : Base {
public override int Prop1 { get { ... } set { ... } }

If you declare a method virtual in your base class you can override it in your derived class.
Example
class MyBaseClass
{
public virtual void MyOverridableMethod()
{
...
}
}
class MyDerivedClass : MyBaseClass
{
public override void MyOverridableMethod()
{
...
}
}
Notice the override modifier in MyDerivedClass.

Okay, let's say you have a base class, and that that base class is, itself, derived from another class.
public class Bar : Foo
{
virtual public int SomeProperty { get; set; }
}
What the virtual keyword means is that in a class derived from Bar, you can override SomeProperty to change its behavior:
public class Baz : Bar
{
private int thisInt;
override public int SomeProperty
{
get { return thisInt; }
set
{
if(value < 0)
{
throw new ArgumentException("Value must be greater than or equal to zero.");
}
thisInt = 0;
}
}
}
Clarification: When an object of type Baz is used, its version of SomeProperty is invoked, unless the type is cast to Bar. If you define Baz's SomeProperty as virtual, classes derived from Baz can also override it (in fact, that may be required--can't recall right off the top of my head).
Further Clarification: An abstract method has no implementation; when you add one to your class, you must also mark the class as abstract, and you cannot instantiate new instances of it, like this:
MyAbstractType m = new MyAbstractType();
Virtual members, on the other hand, can have an implementation (like SomeProperty, above), so you don't have to mark the class abstract, and you can instantiate them.

Related

Abstract Class must override an abstract method?

Let's say this abstract class:
abstract public class MyBase {
abstract public int GetValue();
<some concrete methods here>
}
Now I want to inherit that as another abstract class, implementing GetValue() but adding new abstract methods:
abstract public class MyBase2 : MyBase {
abstract public int GetValue2();
public override int GetValue() {
// some code here
return something;
}
}
Why do I have to specify override for MyBase2.GetValue()? Isn't MyBase.GetValue() already marked as abstract and thus will naturally be overridden by anything inheriting from MyBase?
Why do I have to specify override for MyBase2.GetValue()?
This is a paradigm which has been adopted by c++ as well.
The idea is: by explitly having the need to use the keywords override for virtual and abstract, you will ensure that you're not making a typo when doing the override. Because if you would mot see such a typo, the behaviour, escpecially on virtual would change significantly.
Having said that; I still find it strange that the new keyword for added methods is still optional and only emits a warning when omitted.
Since your MyBase2 class is also marked as abstract you should tell the compiler that GetValue() is implemented in this class instead of other class(es) higher in hierarchy (implementing MyBase2)

When should I use an abstract property, and when should property be in my abstract class [duplicate]

I'm not really sure what looks better or when do I really use in abstract classes and properties, or when to use non abstract properties. I'll try to make a simple example. Let's say I have this:
abstract class Human
{
public GenderType Gender { get; set; }
public string Name { get; set; }
public Date Born { get; set; }
public bool IsNerd { get; set; }
abstract public void Speak();
abstract public void Sleep();
abstract public void AnoyingPeopleOnStackOverflow();
//... so on
}
class Peter : Human
{
//Peter is special, he got a second name
//But thats all, everything else is the same as like on other humans
public string SecondName { get; set; }
//...override abstract stuff
}
Is this alright? As I understood, I don't have to use an abstract property if I dont want to override it. And in this situation it would be ok, just the methods like Speak, Sleep and so on should be abstract.
Now, if this is ok, when would or should I use an abstract property?
Use an abstract property when you have no default implementation and when derived classes must implement it.
Use a virtual property when you have an implementation in the base class but want to allow overriding.
Use the override keyword to override a member. Mark the member as sealed override if it should not be overridden again.
Don't mark the property as abstract or virtual if you don't want it to be overridden.
Use the new keyword to hide a non-abstract, non-virtual member (this is rarely a good idea).
How to: Define Abstract Properties
I find that abstract properties often occur in a design which implies that they will have type-specific logic and/or side effects. You are basically saying, "here is a data point that all subclasses must have, but I don't know how to implement it". However, properties which contain a large amount of logic and/or cause side effects may not be desirable. This is an important consideration, though there is no fixed right/wrong way to do it.
See:
Should Properties have Side Effects
CA1024: Use properties where appropriate
Personally, I find that I use abstract methods frequently but abstract properties rarely.
I know what I want them to do, I don't care how they do it: Interface.
I know what I want them to do, I don't care how they do some of it, but I've firm ideas on how they'll (or at least most of them) do other bits: Abstract class.
I know what I want them to do, and how most of them will do it: Concrete class with virtual members.
You can have other cases such as e.g. an abstract class with no abstract members (you can't have an instance of one, but what functionality it offers, it offers completely), but they're rarer and normally come about because a particular hierarchy offers itself cleanly and blatantly to a given problem.
(Incidentally, I wouldn't think of a Peter as a type of Human, but of each peter as an instance of human who happens to be called Peter. It's not really fair to pick on example code in this way, but when you're thinking about this sort of issue it's more pertinent than usual).
Abstract members are simply virtual members that you have to override. You use this for something that has to be implemented, but can't be implemented in the base class.
If you want to make a virtual property, and want that it has to be overridden in the class that inherits your class, then you would make it an abstract property.
If you for example have an animal class, its ability to breathe would not be possible to detemine just from the information that it's an animal, but it's something that is pretty crucial:
public abstract class Animal {
public abstract bool CanBreathe { get; }
}
For a fish and a dog the implementation would be different:
public class Dog : Animal {
public override bool CanBreathe { get { return !IsUnderWater; } }
}
public class Fish : Animal {
public override bool CanBreathe { get { return IsUnderWater; } }
}
Use abstract when all sub-classes have to implement the method/property. If there's no need for each and every sub-class to implement it, then don't use it.
As for your example, if SecondName is not required for each person, then there's no need to make an abstract property in the base class. If on the other hand, every person does need a second name, then make it an abstract property.
Example of correct usage of an abstract property:
public class Car
{
public abstract string Manufacturer { get; }
}
public class Odyssey : Car
{
public override string Manufacturer
{
get
{
return "Honda";
}
}
}
public class Camry : Car
{
public override string Manufacturer
{
get
{
return "Toyota";
}
}
}
Making Maker abstract is correct because every car has a manufacturer and needs to be able to tell the user who that maker is.
An abstract property would be used where you want the class to always expose the property, but where you can't pin down the implemetation of that property - leaving it up to/forcing the inheriting class to do so.
There's an example here, where the abstract class is named Shape, and it exposes an abstract Area property. You can't implement the Area property in the base class, as the formula for area will change for each type of shape. All shapes have an area (of some sort), so all shapes should expose the property.
Your implementation itself looks just fine. Was trying to think of a sensible example of an abstract property for a Human, but couldn't think of anything reasonable.

Adding accessor to interface property allowed, but not to abstract property

Why is it that the following is legal C#:
public interface ISomeInterface
{
int SomeProperty
{
get;
}
}
public class SomeClassImplementingInterface : ISomeInterface
{
public int SomeProperty
{
get { return 32; }
protected set {}
}
}
but this is not:
public abstract class SomeAbstractClass
{
public abstract int SomeProperty
{
get;
}
}
public class SomeClassExtendingAbstractClass : SomeAbstractClass
{
public override int SomeProperty
{
get { return 32; }
protected set {}
}
}
The latter results in the following compile-time error:
'InterfaceAbstractTest.SomeClassExtendingAbstractClass.SomeProperty.set':
cannot override because
'InterfaceAbstractTest.SomeAbstractClass.SomeProperty' does not have
an overridable set accessor InterfaceAbstractTest
What is the reasoning for not disallowing the latter whilst allowing the former?
Because a caller using the interface only cares that an implementer of the interface at least implements the interface's definition, as #davisoa states, whereas SomeAbstractClass in your example defines a public contract which states exactly the type, accessibility, and (for properties) readability/writability of members.
If you use reflection to get the PropertyInfo of SomeProperty (from either the base or child class), it needs to resolve that information from somewhere. Allowing the child class to change the readability/writability would be as much of a contract violation as a change in return type or argument list.
Imagine for instance:
SomeAbstractClass sc = new SomeClassExtendingAbstractClass();
PropertyInfo pi = sc.GetType().GetProperty("SomeProperty");
Console.Out.WriteLine(pi.CanWrite); // What should be printed here?
This is because the Interface implementation is making a promise that there will be a property SomeProperty that you can "Get".
The abstract class implementation is making a promise that it's child classes will provide an implementation of a property SomeProperty with a public get method.
In the end, the base class is defining something that must be overridden, whereas the interface is defining a contract.
This is by design. I am quoting from the C# language specs:
An overriding property declaration must specify the exact same
accessibility modifiers, types and name as the inherited property, if
the inherited property has only a single accessor (i.e.,... ready only
or write-only), the overriding property must include only that
accessor.
The reason behind that decesion could be because the interfaces are more flexibly type of contracts than abstract classes. Interfaces cares only about the least common denominator rather than the whole implementation. I think there are good reasons to choose one design over the other.
You're trying to override a set operator that doesn't exist. Either define a set portion of the property in the abstract class, or don't try to define one in the concrete class. Since you have the set as protected in the concrete class, my guess is what you want to do is make a protected set operator in the abstract definition.
What is necessary is to both override the existing property and shadow it with a new read-write one. Unfortunately, .net does not provide any means of both overriding and shadowing a member within a single class. The best one can do is probably to have the abstract base class define a concrete non-virtual read-only property whose getter calls an abstract function. A derived class can then shadow the property with a non-virtual read-write function which calls the same function in its getter, and a new abstract or virtual function in its setter.

Abstract class constructor in C#

In c# we can't create an obeject of a abstact class or interface it means abstract class do not have any constructor, is it true ?
or if it have then what is it's purpose there?
As others have said, abstract classes usually have constructors (either explicitly or the default one created by the compiler) - and any derived class constructor will have to chain through the abstract class's constructor in the normal way. That's the important bit... suppose you have an abstract class which stores the name associated with an instance - because you always want a name, and you don't want to write the Name property in each concrete derived class. You might provide a constructor which takes that name and assigns it to a field... and then every subclass constructor would have to go through that constructor, so that you still knew you'd always have a name. If you want to know more about constructor chaining, read my article on it.
Here's an example of that:
public abstract class DemoBase
{
private readonly string name;
public string Name { get { return name; } }
protected DemoBase(string name)
{
this.name = name;
}
// Abstract members here, probably
}
public class FixedNameDemo : DemoBase
{
public FixedNameDemo()
: base ("Always the same name")
{
}
// Other stuff here
}
public class VariableNameDemo : DemoBase
{
public VariableNameDemo(string name)
: base(name)
{
}
// Other stuff here
}
To further answer your comment on BoltClock's answer, asbtract classes can't have private abstract methods, but they can have private constructors. Indeed, it's sometimes useful to have only private constructors in an abstract class, because it means the class can only be derived from within the program text of the same class. This allows you to create pseudo-enums:
public abstract class ArithmeticOperator
{
public static readonly ArithmeticOperator Plus = new PlusOperator();
public static readonly ArithmeticOperator Minus = new MinusOperator();
public abstract int Apply(int x, int y);
private ArithmeticOperator() {}
private class PlusOperator : ArithmeticOperator
{
public override int Apply(int x, int y)
{
return x + y;
}
}
private class MinusOperator : ArithmeticOperator
{
public override int Apply(int x, int y)
{
return x - y;
}
}
}
In this respect, an abstract private method/property could make sense - it could be accessed by the base class but provided by the derived classes within the same class's program text. However, it's prohibited by the specification. Usually, protected abstract members would solve the same problem - but not quite always.
Good question. Here's why Abstract classes need constructors even though they cannot be instantited.
In any Object oriented language like C#, object construction is an hierarchical process. Look at the code below. When you instantiate any object of type DerivedClass, it must construct the base object first before creating the object of typeof DerivedClass. Here the base class may or may not be an Abstract class. But even when you instantiate an object of a concrete type derived from an abstract class it will still need to call the constructor of the Base class before the object of DerivedClass type is created, hence you always need a constructor for Abstract class. If you have not added any constructor, C# compiler will automatically add a public parameterless constructor to the class in the generated MSIL.
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("BaseClass constructor called..");
}
}
public class DerivedClass : BaseClass
{
public DerivedClass()
{
Console.WriteLine("DerivedClass constructor called..");
}
}
DerivedClass obj = new DerivedClass();
//Output
//BaseClass constructor called..
//DerivedClass constructor called..
PS: Assuming, If Abstract base classes
are not allowed to have constructors
because they need not be instantiated,
the whole fundamentals of the object
oriented programming will go on toss.
The idea behind Abstract types are to
represent objects that have some
features and behaviours but not
complete as whole to allow independant
existence.
No. it means that operator new is not allowed to create object from this type of class.
The purpose might be that are allocated/initialized some properties of class.
abstract usually leave some methods to implement.
Regarding the interface, this structure holds only the signatures of method, delegates or events. That may be implemented in class that use interface. You cant create a object.
Read about new
EDIT:
What is the purpose of constructor in abstract class ?
When one class inherit another class, the parent class of it had to be created first while object is crated. In class do not implement some special constructor always is used default one [className()]. When you override some method then the implementation of functionality is taken form class which override the method. This is why method used in constructor should never be virtual. Same logic for abstract class, such class can have a lot of functionality, and only one method that should be implemented by child class.
Abstract classes have constructors but you can't call them directly as you can't directly instantiate abstract classes.
To answer your comment, the concept of a private abstract method or property makes no sense, because private prevents anybody else from accessing it, and abstract prevents itself from accessing it. So there would essentially be no possible way to call it.
EDIT: see Jon Skeet's answer on private constructors. Private members of other kinds cannot exist in abstract classes, though.
Abstract classes do have constructors. When you create an instance of a derived class, its parent class' constructors are called. This applies to classes derived from abstract classes as well.

Why should an abstract class implement an abstract method of an abstract base class?

In the following example, the class Derived implements the abstract method method from class Main. But I can't think of a reason to fill in the method body in the abstract Derived class' implementation. Surely I should only implement abstract methods within real classes.
So how can I avoid doing it? What else can I do?
abstract class Main
{
public abstract void method();
}
abstract class Derived : Main
{
public override void method()
{
}
}
class RealClass : Derived
{
}
Usually if someone has specified that an abstract class has an abstract method, it's either because that class depends on that method for some of what it does, or it's because it's part of an expected API that it wouldn't make sense for the parent class to implement at this time. In either case, there must be an implementation once you get to a non-abstract implementation of the class.
Note also that if you are implementing an interface, you are required to state how that interface will be implemented, even if you just call the member abstract and pass the responsibility onto the subclass
public interface IPet {string GetNoise(); int CountLegs(); void Walk();}
public abstract class Pet : IPet
{
public string Name {get; set;}
public abstract string GetNoise(); // These must be here
public abstract int CountLegs();
public abstract void Walk();
}
When it comes to implementing the sub-class, you have a few choices depending on the circumstances. If your implementation is itself an abstract class, you shouldn't need to implement the abstract method.
public abstract class Quadruped : Pet
{
public override int CountLegs () { return 4; }
}
If your implementation is non-abstract, but the standard reason for the method in question really doesn't apply in your circumstance, you can do a no-op method (in the case of void methods), or return some dummy value, or even throw a NotImplementedException to indicate that the method should never have been called in the first place.
public class Fish : Pet
{
public override string GetNoise() {return "";} // dummy value: fish don't make noise
public override int CountLegs() {return 0;}
public override void Walk() {} // No-op
// public override void Walk() { throw new NotImplementedException("Fish can't walk"); }
}
Does that answer your question?
If there's no implementation of method in Derived then you can just make Derived abstract as well:
abstract class Derived : Main
{
}
class RealClass : Derived
{
public override void method() { ... }
}
EDIT: To clarify the comments - if there is no meaningful implementation of an abstract method in a subclass, then one does not need to be provided. This will however require that the derived class is itself abstract, and an implementation must be provided somewhere in the chain of descendant classes to some concrete subclass. I am not saying you should leave the implementation of method empty, as it is in the question, but rather you remove the override in Derived and mark the class abstract. This forces RealClass to provide an implementation (or itself be marked abstract).
All non-abstract descendant classes must provide concrete implementations of abstract methods. If you don't provide an implementation, then it's impossible to call that method.
If some concrete classes don't have an obvious proper implementation of a abstract method then your object design is incorrect. Maybe you should have an abstract class with some abstract methods (but not all). That class could have an both an abstract descendant and some concrete descendants.

Categories