Is there something inherently wrong with giving Abstract Classes a Constructor? - c#

http://msdn.microsoft.com/en-us/library/ms182126.aspx
Microsoft Design Guidelines say that Abstract Types should not have a Constructor.
To me, it seems very plausible that most classes that derive from an abstract class will have a constructor very similar to, if not identical to, its base.
If for no other reason but to follow DRY, is it really terrible to have abstract classes with Constructors if it means that all your derived classes now only need to put
public DerivedClass()
: base()
{
}
Or is there something that I am missing?

There's nothing to prevent you from doing that but by definition abstract classes are those that cannot be instantiated. So if you create a constructor, make it protected, not public otherwise your class won't meet the definition of abstract.
The guideline you mentioned further explains:
Cause: A public type is abstract and has a public constructor.
and
Rule description: Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed.
How to Fix Violations: To fix a violation of this rule, either make the constructor protected or do not declare the type as abstract.

Related

Abstract keyword in front of a class: to be or not to be

Should I always annotate a class which has only protected constructors by design with abstract keyword? Why?
Let’s suppose the class does not have abstract members.
If no, could you give some examples?
No. A type with only protected constructors is still creatable - either through a static factory method on the type, or via reflection (including, as one option, totally skipping the constructors).
An abstract type is never creatable.
Mark the type as abstract: if it is abstract. So: does it make sense for an object of that type (rather than a subclass) to exist?
No, you should not do this by design since thats not what abstract classes are made for.
abstract on MSDN
In my opinion, an abstract class is used to represent a bunch of classes which are of same type in logical view. It means that this bunch of classes are common in either properties or behaviours. It is not used to represent the class which has a 'Private' constructor and can not be created outside the class itself.

Inconsistent accessibility: base class is less accessible than class

So I have an abstract base class in a DLL and child classes of that class. I want the childs to be public, but the base to be private so that it cannot be accessed outside of the dll.
How do I do that?
You don't and you can't.
If you want to expose the class as public, the base-type must be public. One other option is to have a public interface, and only expose the type via the interface (presumably with a factory method somewhere for creating instances).
One final option is to encapsulate the base-class rather than inherit it.
Make it public, make all constructors internal (if you're using the default constructor, add a parameterless constructor to override that).
Then while public and not sealed, it can't be sub-classed by external code.
Just to clarify what I was saying in comments on #Marc Gravel's answer you could
public ChildClass : ParentClass
{
}
public ParentClass
{
internal void MethodIdontWantToExpose()
{
}
}
That said an interface is probably the best solution

Abstract class in C# without any abstract method

Folks
I am surprised to see my code working, that I dont have any abstract method in abstract class. But as per rules we should have atleast one abstract method right ? :S
No, you don't need an abstract method in an abstract class.
The restrictions are:
If a class has an abstract method, property, index, or event then the class must also be abstract.
You can't instantiate an abstract class.
There is no requirement that abstract classes must have abstract methods.
No, this is entirely valid. Indeed, every static class in C# is actually an abstract and sealed class in .NET. (You can't declare an abstract class to be sealed with C# source code though.)
The C# 4 spec explicitly calls this out, in section 10.1.1.1 (abstract classes):
An abstract class is permitted (but not required) to contain abstract members.
It's certainly rare to have an abstract class with no abstract members, but it's not unheard of. (Don't forget that it's not just methods that can be abstract - you can have abstract events and properties, too.)
From MSDN - abstract (Emphasis added):
An abstract class may contain abstract methods and accessors.
Your abstract class can contain nothing but non-abstract methods, or it could be am empty class if you want. It gives you a base class that cannot be instantiated, which could be useful for plymorphism.
You don't need abstract methods to have an abstract class. Sometimes it's useful to just restrict a class from being instantiated, and designate it as a base to some inheritance hierarchy. All the methods can be defined in an abstract class.

Cannot create an instance of the abstract class or interface

I'm not familiar on using abstract class.
I'm trying to call a abstract class and get this error Cannot create an instance of the abstract class or interface and I already research this error but I'm really confused on this.
Here's my code:
string B1String;
while ((B1String = OasisFile.ReadLine()) != null)
{
Questions_Base oQuestions_Base = new Questions_Base(); // error here
oQuestions_Base.Import(B1String);
}
Please advice me.. thanks!
The purpose of an abstract class it to serve as part of a class hierarchy where more-derived classes share some common implementation.
If you have a flight simulator, you might define an abstract class ThingsThatFly that implements some properties (air speed, altitude, heading) and methods (TakeOff(), Land()) that all flying things have in common, but would be declared abstract because ThingsThatFly is an abstraction of all concrete things that fly. You could certainly have classes inbetween as well, for example Cessna172 could inherit from Airplane that inherits from ThingsThatFly. You would do that if all airplanes have some common implementation that e.g. birds don't have (for example, a Fuel Remaining property).
You would then have a number of concrete (= real life) things that fly like a Cessna 172, a Space Shuttle and a Duck. Each of those would be a concrete class that derives from ThingsThatFly
This is different than having the concrete classes implement an interface such as IThingsThatFly in that the abstract class provides not only a definition of the properties and methods that are expected, but also provides a (hopefully useful) implementation of those properties and methods.
An Abstract class can only be inherited.
public class CustomClass : Questions_Base {
}
Here's a link all about abstract classes and how to use them.
You cant create an instance of an abstract class.
You need to define a concrete class that inherits the abstract class, and create an instance of that.
Abstract class is made to be overriden by Derived class. If you have to have Abstract class, first create s Derived class from it and use Derived class contructor.
If it's not important, just remove abstract word from Questions_Base class declaration, so making that non abstract one. Also because in code provided I don't see any abstract member, so may this one is correct choice.
Regards.
An abstract class cannot be instantiated. You must provide an implementation for the class.
abstract class Animal
{
public abstract void Speak() { }
}
public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Woof");
}
}
See MSDN on abstract for more information
From the documentation: "The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class."
The purpose of using abstract is exactly to prevent instantiation, because you only created the class to use as a base class and never want an instance created.
More here.
An abstract class is one which MUST be inherited.
It falls somewhere between an Interface, which defines only the interface that a class must implement and no implementation code and a class that you can create an instance of which defines both the interface and the implementation code. There are several abstract classes in the .NET framework such as CollectionBase. You cannot create an instance of CollectionBase, it is intended for you to create a class that inherits from it and extends it's capabilities.
You should simpley be able to remove the kwy work "abstract" from your class definition of Questions_Base or create a new class definition that inherits from it.
Abstract classes, marked by the keyword abstract in the class definition, are typically used to define a base class in the hierarchy. What's special about them, is that you can't create an instance of them - if you try, you will get a compile error. Instead, you have to subclass them, as taught in the chapter on inheritance, and create an instance of your subclass. So when do you need an abstract class? It really depends on what you do. To be honest, you can go a long way without needing an abstract class, but they are great for specific things, like frameworks, which is why you will find quite a bit of abstract classes within the .NET framework it self. A good rule of thumb is that the name actually makes really good sense - abstract classes are very often, if not always, used to describe something abstract, something that is more of a concept than a real thing.

Abstract class without any abstract method

I am surprised to know that an abstract class in C# is possible with no abstract methods also.
abstract class AbstractDemo
{
public void show()
{
Console.WriteLine("In Show Method");
}
}
class MainDemo:AbstractDemo
{
public static void Main()
{
Console.WriteLine("In Main Method");
}
}
Any explaination ?
Sometimes you don't want to give the possibility to instantiate a class but you need this class as a base class for other classes.
The reason for choosing abstract classes over interfaces is that you can provide some basic implementation.
This is entirely valid, and occasionally useful if you want to provide event-like behaviour: provide an abstract class with all the "event handlers" implemented as virtual methods with a default behaviour of doing nothing.
I've also personally used this a lot for abstract remote API client classes where all methods throw exceptions: they're abstract for the purposes of test doubles, expecting our implementations to be the only production implementations, but allowing users to create their own test doubles either by hand or via mocking frameworks. Making the methods virtual instead of abstract means that new RPCs can be added without that being a breaking change.
A derived class can then override some of the methods, but doesn't have to override any specific one, because nothing's abstract. It still makes sense for the class to be abstract because an instance of the base class would be pointless (as everything would be a no-op).
This pattern is much more common in Java than C#, however - as in C# you'd normally just use "proper" events.
An abstract class is a class that must be extended before it can be used. This does not it any way mean that the function themselves must be abstract.
Take for example an Animal class
public abstract class Animal
{
void Move()
{
//whatever
}
}
public class Fish : Animal
{
void Swim()
{
}
}
public class Dog : Animal
{
void Bark()
{
}
}
All animals can move but only the fish can swim and the dog can bark.
Or for a real life example. I have an Asp.net MVC base controller I use in my application. It has some basic methods I need very often like GetCurrentUser() and a function I wrote to help with localization. It also takes care of tracking so I don't have to rewrite that code in all of my controllers. The class has about 200 lines of code but not a single abstract method.
I think you're confusing abstract classes with interfaces. Interfaces can't have methods with body, abstract classes can. There are times when you want to prevent user from instantiating an object of a specific class; but still provide some base functionality for the classes that derive from it; this is what an abstract class is useful for.
If your class is just a base for other classes and it does not have an full usablility - in other words as a base itselfe is not usable at all then you want to prevent from creating instances of it. In this case you can make abstract class without abstract members.
You could use abstract keyword on a class just to signal the compiler that it can only used inheriting from it, and not directly; In this case you are not oblied to put abstract member on the class.
This is equivalent to put in the class only one protected constructor, but using abstract is more clear and understandable.
No better explanation than MSDN it self
http://msdn.microsoft.com/en-us/library/aa645615(v=VS.71).aspx
An abstract class cannot be instantiated directly, and it is a
compile-time error to use the new
operator on an abstract class. While
it is possible to have variables and
values whose compile-time types are
abstract, such variables and values
will necessarily either be null or
contain references to instances of
non-abstract classes derived from the
abstract types.
An abstract class is permitted (but not required) to contain abstract
members.
An abstract class cannot be sealed.
We have heard that in abstract class, there must be an abstarct member. But when I compile the abstarct class without an abstract method, it compiles. It gives me surprise. Now I am unable to find the article which explain exact behavior of an abstarct class.

Categories