I am sorry if I am asking something stupid but I am completely a newbie in C# and ASP.NET.
I am having an error in my code and I don't understand it.
I am working on Visual Studio 2008.
In this line of code:
public class SQLFAQProvider : DBFAQProvider
I am getting this error:
Moby.Commerce.DataAccess.FAQ.SQLFAQProvider does not implement inherited abstract member Moby.Commerce.DataAccess.FAQDBFAQProvider.DeleteFAQbyID(int)
When I go to DBFAQProvider the error is in this line of code:
public abstract DBFAQ DeleteFAQbyID(int fAQID);
What should I change to correct it?
First thought would be implement the abstract member in the inherited class ala:
public class SQLFAQProvider : DBFAQProvider
{
public override DBFAQ DeleteFAQbyID(int fAQID)
{
//TODO: Real Code
return null;
}
}
Implement the DeleteFAQbyID method in your derived class:
public override DBFAQ DeleteFAQbyID(int fAQID)
{
// Put your code here
}
The point of an abstract method is to say (in the abstract base class), "I want to make sure that this method is available in every concrete class deriving from me" - it's up to you to provide the implementation. It's a bit like a method in an interface.
Your subclass needs to explicitly implement that particular method.
If you have no idea how to do it, then at least do:
public override DBFAQ DeleteFAQbyID(int fAQID)
{
throw new NotImplementedException("This isn't done yet");
}
When you inherit from a class in C#, you are required to implement all methods marked as abstract unless your class is itself marked as abstract. Abstract classes are ones that cannot be directly instantiated at runtime because they don't fully implement all of the required methods that the base class(es) say must exist.
Abstract methods are a mechanism that allows a class to indicate that a particular method must "eventually" exist - without having to provide an implementation at that point. You typically use abstract classes when you cannot or don't want to dictate what a particular implementation should do, but you need to pre-define a method that you will eventually rely on.
To fix your problem either mark your class as abstract (with the expectation that another level of inheritance will fill in the missing pieces) or implement DeleteFAQbyId() in your class:
public DBFAQ DeleteFAQbyID(int fAQID)
{
// write appropriate implementation here or:
throw new NotImplementedException();
// or possibly NotSupportedException() if the operation should can't ever be supported.
}
When a class inherits from an abstract class it must implement all abstract methods defined by said class. This is the class interface, the abstract methods can be thought of as pure virtual functions, i.e., functions that must be implemented by descended classes but do not make sense to be implemented in the base class.
Because your SQLFAQProvider class isn't abstract, it has to implement every abstract method that it inherits.
To fix this, implement the DeleteFAQbyID method in SQLFAQProvider, like this:
public override DBFAQ DeleteFAQbyID(int fAQID) {
//Do something
}
Alternatively, you could make your SQLFAQProvider class abstract by changing its declaration to public abstract class SQLFAQProvider.
Your subclass (SQLFAQProvider) must provide implementation code for the method DeleteFAQbyID because the parent class (DBFAQProvider) did not.
In the abstract class use an entity property like IsValid. Make it return the abstract method that you want to override in the derived class.
In abstract base class:
public bool IsValid
{
get
{
return DeleteFAQbyID();
}
}
public abstract bool DeleteFAQbyID();
In the derived class now it will override the abstract class' method.
Related
I am new to C# programming. I understand that it is necessary to modify the class as abstract if it contains any abstract methods, and its implementation must be provided in any of the child classes in class hierarchy.
But my question is whether can we have an abstract class without any abstract methods(so it is not necessary for it to be a base class), and if it is so, then what are the significance of the same. Please help in this regard. :)
Yes you can have an abstract base class without any abstract methods. The benefit is that you cannot create an instance of this class.
There is a consideration to replace that abstract class with an interface. The difference is that the interface may not contain any implementation, but in the abstract class you can provide some implementation for methods that any inheritor may use.
You cann't create instances of the abstract class, and if you are not use this class as base - it is useless (only possible for some tricky goals using reflection)
Yes, it can be used without having an implementing subclass. Basically you have three "ways" of defining and calling methods here:
static: Methods that can be called directly on the abstract class, because they do not require an instance at all.
abstract: Methods that must be implemented in a sub-class (note that the existance of one of these does not stop you from using any existing static methods directly!)
"Regular": Normal methods, implemented directly in the abstract class, and which can be called via an instance of a sub-class. Note that you can only call them via sub-classes, since you can only have instances of a subclass (not the abstract class itself). Such a sub-class must also by definition implement any abstract method(s) in the abstract class (otherwise you`ll get a compile time error).
The following simple console app gives a nice, concrete (no pun intended) example:
using System;
namespace ConsoleStuff
{
public abstract class MyAbstractClass
{
public abstract void DoSomethingAbs();
public void DoSomethingElse()
{
Console.WriteLine("Do something general...");
}
public static void TakeABreak()
{
Console.WriteLine("Take a break");
}
}
class MyImplementation : MyAbstractClass
{
public override void DoSomethingAbs()
{
Console.WriteLine("Do something Specific...");
}
}
class Program
{
static void Main(string[] args)
{
// Static method; no instance required
MyAbstractClass.TakeABreak();
var inst = new MyImplementation();
inst.DoSomethingAbs(); // Required implementation in subclass
inst.DoSomethingElse(); // Use method from the Abstract directly
Console.ReadKey();
}
}
}
I need to inherit from a basic abstract class. I want to override only one method. But Visual Studio oblige me to override them all, So I am overriding more than 10 methods that throw NonImplementedException, I find it stupid. Isn't there any way to override only what I need. Or at least to tell Visual Studio to override the rest (non implemented methods and properties)?
The base class is written by the framework so I can't change it (I am talking about RoleProvider of ASP.NET MVC)
abstract class Base
{
public void Method1()
{
//some code
} // No need to override
public abstract void Method2(); // must be overriden
public virtual void Method3()
{
// some code
} // Not necessarily be overriden
}
class Derived : Base
{
}
Here the compiler will only ask you to override Method2() as a mandate. It won't ask you to override Method1() or Method3(). You can override Method3() as it bears keyword virtual though.
If the method is abstract , you must override.
If the method is virtual , you can override but not necessarily
The real problem here is that you have a base class with so many methods that a derived class can work only with a subset of them. This means that your base class most likely has multiple responsibilities and thus violates the Single Responsibility Principle (SRP).
The solution is to split your base class into several smaller classes where each of them has exactly one responsibility.
If the base class is not from you, you really need to implement all of those methods.
If the base class is a class that violates the SRP and your implementation can really work correctly if you implement only a small subset of the methods you could create an abstract base class deriving from that other abstract base class. In your abstract base class you can implement all methods you don't need and throw a NotImplementedException. Don't implement those methods you need.
Now, derive a class from your base class - you now only have to implement the methods you are interested in. Be sure to document this properly.
Isn't there any way to override only what i need.
No, that's how abstract classes work. If you make your class abstract as well you don't need to implement all methods.
It is necessary to override all the methods which are declared as abstract. you cannot skip the non-concrete methods. If you really want to do then make your class as abstract. you cannot change the mechanism of abstraction.
Remember, abstract classes have the following features:
An abstract class cannot be instantiated.
An abstract class may contain abstract methods and accessors.
It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
You could also create an abstract class which would inherit and implement all methods (with NotImplementedException), and then your subclasses could inherit that abstract class and implement only the methods that are relevant for you.
If I have a project that contains similar classes and some may use the same implementation, but in most cases they implement their own way of handling the methods defined in an interface or abstract class. I am trying to figure out if an interface/abstract class is better or not. I don't get the point of an interface if you can just use an abstract class with virtual abstract methods.
Here is an interface:
public interface IAthlete
{
void Run();
}
Here is an abstract class:
public abstract class Athlete
{
public abstract void Run();
}
Here is an implementation of the interface:
public class Sprinter : IAthlete
{
public void Run()
{
Console.WriteLine("Running Fast....");
}
}
Here is an extension of the abstract class:
public class MarathonRunner : Athlete
{
public override void Run()
{
Console.Write("Jogging....");
}
}
Now if I decide to add a method called Stop to either the interface or abstract method, Sprinter and MarathonRunner both break and because I can provide some default implementation to abstract, it seems like a better choice. Am I missing something?
There are 2 main differences between Interfaces and abstract super-classes:
Abstract Classes
code reuse is possible by using an abstract super-class
you can only inherit one super-class
Interfaces
every method has to be implemented in each sub-class
a class can inherit more than 1 interface (multiple inheritance)
In the case where all you have is one piece of commonality to extract, you're quite right that there isn't a substantive difference between the two. But this is rather like saying "in the case of adding 1 to 2, there's no difference between an int and a double" - it's technically true, but not a particularly useful guide to how to think.
In case with any more complexity than this (that is, in most cases) there will be more classes, and pieces of common baheaviour to extract. Then you have to start making a significant choice between class inheritance and interface implementation, taking into account things like:
you only get one shot at choosing a base class, but you can implement as many interfaces as you like
if you want your 'parent' to do any work, it needs to be a class not an interface
and so on.
In general, the semantics of your classes should guide you - where the 'things' have an "IS A" relationship (like MarathonRunner to Athlete), inheritance is suggested; where the 'things' have an "I CAN FULFIL THE CONTRACT OF A" (like, say, Person to Runner), interface implementation is suggested.
Interfaces are a btter way to go as the current consensus amongst the .NET developer comunity is that you should favour composition over inheritance, so Interfaces are a much better strategy (think of Injection Containers and how usefull they are as well, and lets not get started on unit testing).
also, classes can implement many interfaces but can only inherit from one class (abstract or otherwise). also structs can implement interfaces but not inherit from another class.
At the runtime level, interfaces are more efficient as the runtime doesnt have to walk the inheritance stack in order to work out the polymorphic implications of calling a specific member.
Interfaces are a very useful feature, and are very similar to abstract classes, and in some circumstances, exchangable with abstract classes.
But, don't jump straight to interfaces, unleass you have to (very common antipattern in Java developers). I suggest, by reading your example, to stick to abstract classes.
Most of the times I only use interfaces, when I have several non related classes, and I need them to have common members, as If these classes came from the same base class.
In your example, you are trying to find what happen if you need a new stop method, when adding a base virtual method. These can be solved in a different approach, that is not Abstract Classes versus interfaces.
There are 3 choices:
(1) Add an abstract method that coerce the programmer to override it, in order to instantiate objects.
(2) Add a new virtual method that does something, but doesn't have to be overriden.
(3) Add a new method that does nothing, maybe applies to your case.
// cannot instantiate an abstract class
public abstract class Athlete
{
// helper method:
public /* non-abstract */ void DoNothing()
{
// does nothing on purpouse !!!
}
// (1) virtual & abstract method, must be overriden
public abstract void Run();
// (2) new virtual method, doesn't need to be overriden,
// but, maybe you dont like what it does
public virtual void Stop()
{
Message.Show("Stop !!!");
}
// (3) new virtual method, doesn't need to be overriden,
// its safe to be called
public virtual void TakeBreak()
{
// works like an abstract virtual method, but, you don't need to override
DoNothing();
}
} // class Athlete
// in a non abstract class, you must override all abstract methods
public /* non-abstract */ class Runner: Athlete
{
public override void Run()
{
DoNothing();
}
public override void Stop()
{
DoNothing();
}
// don't need to override this method
// public virtual void TakeBreak();
} // class Trekker
// ...
Runner ARunner = new Runner();
ARunner.Run();
ARunner.Stop();
ARunner.TakeBreak();
The third kind of virtual method, that may apply to your example, doesnt' have a special name, I already post a question about it on stackoverflow, but, nobody knew an special name for this case.
Cheers.
An important difference between interfaces and abstract classes is how their members handle multi-generational inheritance. Suppose there's an abstract class BaseFoo with abstract method Bar and interface IFoo with method Boz; class Foo inherits BaseFoo and implements IFoo, and class DerivedFoo inherits from Foo.
If DerivedFoo needs to override BaseFoo.Bar, it may do so, and its override may call base.Bar() if it needs to use its parent's implementation. If Foo implements Boz implicitly using a virtual method, then DerivedFoo may override that method and call base.Boz() (the override being a function of the class rather than the interface) but if Foo explicitly implements IFoo.Boz, then the only way for DerivedFoo to change the behavior of IFoo.Boz will be to re-implement it. If it does so, then Foo's implementation of IFoo.Boz will become inaccessible, even within DerivedFoo's implementation of the same interface member.
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.
I have two classes:
public class MyBase
{
public virtual void DoMe()
{
}
}
public class MyDerived:MyBase
{
public override void DoMe()
{
throw new NotImplementedException();
}
}
And I have the following code to instantiate MyDerived:
MyDerived myDerived=new MyDerived();
The thing is how to call DoMe of the base class? If I use myDerived.DoMe(), then the derived method wil be called, resulting in an exception. I tried to cast myDerived to MyBase, yet it is still the derived version of the method that gets called.
Edit: As mentioned in the below comment, I can't change eitehr MyDerived or MyBase because they are not my code.
There's a solution, but it's ugly: use reflection to get the base-class method, and then emit the IL necessary to call it. Check out this blog post which illustrates how to do this. I've successfully used this approach it to call the base class's implementation of a method when all I have is a reference to a derived class which overrides that method.
You can't call the base-class version.
If the method doesn't work on the derived class, then it's rather unlikely the base version of the method will work when called on an instance of the derived class. That's just asking for trouble. The class was not designed to work that way, and what you're trying to do will probably just cause other parts of the class to behave unpredictably.
Why do you need to call this method on the object when the object tells you outright that it won't work?
It seems to me that these classes have some design flaws, and if you're not allowed to change the classes, maybe you're allowed to change to a more well designed library instead.
To call MyBase.DoMe() from an external class you would need either an instance of MyBase or a derived instance that does not override DoMe(). A method declared as a virtual will be called on the actual runtime type of the object, not the type of the object, which is why casting to MyBase does not change what method is called. If however the method was not declared in MyBase as virtual and MyDerived still implemented DoMe() it would be "hiding" the MyBase's implementation. Therefore, if the reference was MyDerived it would call MyDerived.DoMe(), but in this case casting to MyBase myBase = (MyBase)myDerived and then calling myBase.DoMe() would call MyBase.DoMe().
The derived class does not need to provide an implementation of the method. Remove it and the implementation in the base class will be called by default.
If, unlike your example, the method in the base class is abstract and you must provide an implementation but it doesn't make sense for the derived class to provide one then there is probably something wrong with the design of the classes.
public class MyDerived:MyBase{
public override void DoMe()
{
base.DoMe();
}
}
EDIT:
You can't access the base classes method from the "outside" without going through the subclasses method. Your only option is to instantiate your base class directly and call it's method.
MyBase mb = new MyBase();
mb.DoMe();
Given your restrictions, another possibility exists:
Download .Net Reflector. Decompile the existing code then make any changes you need to support your situation.
Of course, review the legality of this before continuing.
This question is so old but I don't see the following option:
You can use the 'new' keyword to specify overlapping methods. Then you would simply cast to the class whose method you wish to call.
public class MyBase
{
public virtual void DoMe()
{
}
}
public class MyDerived:MyBase
{
//note the use of 'new' and not 'override'
public new void DoMe()
{
throw new NotImplementedException();
}
}
Implementation
var myDerived = new MyDerived();
var derivedDoMe = myDerived.DoMe();
var baseDoMe = ((MyBase)myDerived).DoMe();