Interface and abstract class protection level methods - c#

I came across a bit of code and am not quite sure why it works or why you'd want to do it this way. I would love it if someone could tear it down for me. I do understand well OOP concepts, I simply have not seen this technique before. Thanks
Here is the example:
public interface IInterface
{
IEnumerable<object> DoSomething();
}
public abstract class MyBase : IInterface
{
protected MyBase()
{
}
IEnumerable<object> IInterface.DoSomething()
{
return DoSomething();
}
protected virtual IEnumerable<object> DoSomething()
{
return new List<object>();
}
}
public class MyClass : MyBase
{
internal MyClass() : base() {}
protected override IEnumerable<object> DoSomething()
{
return new List<object>();
}
}

If you're talking about this line of code:
IEnumerable<object> IInterface.DoSomething()
That's called explicit interface implementation.
That forces consumers to access this method only via the interface,
and not to your class directly.
The above method is not private, it's just not explicitly set as public in code. In fact, with explicit interface implementation, you can't even use access modifiers.
One of the reasons for taking this approach is to force better coding practices. If you're the developer of this class, and you know it should only be accessed via an interface, this is the way to force that to happen.

In C#, explicitly implementing an interface by using a sealed method which does nothing but call a protected virtual method allows derived-classes great flexibility with regard to what they want to do with the interface; the method should be given a name other than the name of the interface method (in the above example, it could perhaps be DoSomething_Prot). Explicit interface implementation makes it impossible for a derived class re-implementation to chain to the base-class implementation, but if the only thing the base-class implementation is doing is chaining to a protected virtual or abstract method, there's no need for a derived class to re-implement the interface. Further, even if the derived class were to re-implement the interface either deliberately or as a result of covariance it would still be able to invoke the "guts" of the base-class implementation using the protected method from the base class.
Putting all the code for the interface implementation in a public virtual method which implicitly implements the interface is better than putting code in an explicit implementation, since derived-class code can generally chain to the private member. Such an approach, however, requires that all derived classes publicly implement the method with the same signature. While it may seem like what one would naturally expect anyway, it isn't always. For example, in the above example a derived class may wish to have its DoSomething method return a type other than IEnumerable<object> (e.g. it might return an IList<Kangaroo>). The method which implements the interfae would still have to return precise type IList<Kangaroo>, but code that knew it was dealing with the derived type could use the return type as an IList<Kangaroo> without a typecast. If the actual code for the method were in a method called DoSomething_Prot(), the derived class could both override DoSomething_Prot and declare a new public IList<Kangaroo> DoSomething(). If the base-class method were called DoSomething(), there would be no way for the derived class to both override it and define a new method with a different return type.

Off the top of my head I'm having trouble of thinking of a practical use for this, but one thing that this accomplishes is that objects of type MyBase or its subclasses do not have a public or internally visible DoSomething() method:
MyClass a = new MyClass();
a.DoSomething(); // Compile error
but the DoSomething() method is visible when the object is used as an IInterface:
void AMethod(IInterface i)
{
i.DoSomething(); // compiles just fine
}
void AnotherMethod(MyBase a)
{
AMethod(a); // as does this
}
Making the non-explicit version protected virtual allows subclasses to override the behavior of the DoSomething() method.
This is a way of implementing a method that cannot be called directly when working with MyBases as MyBases, but can be used when they are being treated as IInterfaces. There's nothing to prevent someone from doing this: ((IInterface)a).DoSomething(); but it seems the hiding is done for semantic reasons.

My take on this is that it is an implementation of the template pattern as described here. Typically you see the template pattern used along with the strategy pattern. In your particular example, users of the IInterface could call the DoSomething
method without regard for how the concrete subclass implemented the method.
This kind of OO programming allows you to take advantage of quite a few other patterns such as the AbstractFactory for creating your concrete subclasses of MyBase which implement IInterface.

The important thing to note is that the two DoSomething methods have nothing to do with each other - they just happen to have the same name.
Basically, you've just got a normal interface that exposes a DoSomething method, so the caller who has a IInterface object can call it. It will then in turn pass the call on to the appropriate implementation of the protected DoSomething method, which can either be from the base class or the derived one.
Explicit implementation like this forces you to code by contract instead of implementation - doesn't really provide any actual protection, just makes it more difficult to accidentally use the wrong type when you declare your variable. They just as easily could have done:
public abstract class MyBase : IInterface {
public virtual IEnumerable<object> DoSomething() {
// blah
}
}
public class MyClass : MyBase {
public override IEnumerable<object> DoSomething() {
// blah
}
}
but that would let you call DoSomething on a variable declared as MyClass or MyBase, which you may not want them to do.

Related

Can C# mark and check when a class implements interface methods? [duplicate]

This question already has answers here:
Equivalent of Java 1.6 #Override for interfaces in C#
(4 answers)
Closed 8 years ago.
When a base class contains a virtual method, to add a more derived version in a sub class, we have to use override.
AFAICT, this serves two purposes:
We don't accidentally overide a base method
If we mistype the method name when we want to override, we get an error (similar to Java, right?)
However, to my dismay it seems that (in VS2010 / .NET4) it is not possible to use override when implementing an interface method.
Obviously the first bullet is rather a non issue, but the overridekeyword would have served as a good simple documentation and check that the interface methods are actually these that are marked as override.
So, when looking at a class implementation, is there any way other than a // comment to indicate that this method implements the method of a certain interface?
However, to my dismay it seems that (in VS2010 / .NET4) it is not possible to use override when implementing an interface method.
That's because interface methods aren't overridden, they're implemented. It's a seemingly trivial semantic difference, but when we're talking about the use of language semantics are pretty important.
but the overridekeyword would have served as a good simple documentation and check that the interface methods are actually these that are marked as override
Wouldn't it be a bit misleading? override implies that there's a base class definition being, well, overridden. The MSDN documentation defines it as:
The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.
Interfaces aren't inherited, they're implemented. Again, just semantics, but a pretty important distinction. A class may implement multiple interfaces, the same method may be applied to multiple interface definitions, etc.
Overriding inherited behavior implies:
There is inherited behavior (either with a default implementation in the case of virtual or without in the case of abstract), keeping in mind that C# is a single-inheritance language
The implementation is being overridden (which carries specific distinctions in an inheritance model when the parent class internally invokes that member)
These conditions don't apply to interfaces.
So, when looking at a class implementation, is there any way other than a // comment to indicate that this method implements the method of a certain interface?
Actually, yes. You can explicitly implement an interface. Something like this:
interface IDimensions
{
float Length();
float Width();
}
class Box : IDimensions
{
public float IDimensions.Length()
{
// implementation
}
public float IDimensions.Width()
{
// implementation
}
}
I believe that everything about your concern is summarized by this sentence:
but the overridekeyword would have served as a good simple
documentation and check that the interface methods are actually these
that are marked as override.
Think about what's an interface, and what's an implementer. A class may or may not implement an interface, and can still implement a method with the same signature as an interface. What an interface does is the job of ensuring that some class has the required members to fullfil a contract.
For example, a class Calculator may implement ICalculator and Calculator implements Addition(int, int). But Calculator couldn't implement ICalculator and it could perform an Addition(int, int) anyway.
How do you distinguish both cases? When to use override or not.
Another point: it's nice to implement a class, and fulfill an interface, and stop fulfilling it by just removing it from the class signature after the inheritance colon.
In the other hand, think that the documentation you're looking for is the compiler error telling you that Calculator implements interface ICalculator but it doesn't declare and implement one or more members defined by ICalculator. If the code compiles, you shouldn't care about if a member is of some or other interface. You know that some members are implementations of some interface, because your Calculator signature would look like this: public class Calculator : ICalculator.
Also, there's the case where a implementation member implements it to fulfill more than an interface. What's overriding your implementation? Isn't this more confusing than avoiding override keyword?
Suppose you have these types:
interface ISampleInterface
{
void Method();
}
class A : ISampleInterface
{
public void Method()
{
}
}
class B : A, ISampleInterface
{
void ISampleInterface.Method()
{
}
}
class C : A, ISampleInterface
{
public new void Method()
{
}
}
and use them this way:
ISampleInterface a = new A();
ISampleInterface b = new B();
ISampleInterface c = new C();
a.Method(); // calls A.Method
b.Method(); // calls explicit ISampleInterface.Method
((B)b).Method(); // calls A.Method
c.Method(); // calls C.Method
((A)c).Method(); // calls A.Method
Looks like it is hard to define, which of implementations of Method could be marked as override.

Abstract Method in Non Abstract Class

I want to know the reason behind the design of restricting Abstract Methods in Non Abstract Class (in C#).
I understand that the class instance won't have the definition and thus they wont be callable, but when static methods are defined,they are excluded from the instance too. Why abstract methods are not handled that way, any specific reason for the same?
They could be allowed in concrete class and the deriving class can be forced to implement methods, basically that is what, is done in case of abstract methods in an abstract class.
First, I think that what you're asking doesn't logically make sense. If you have an abstract method, it basically means that the method is unfinished (as #ChrisSinclair pointed out). But that also means the whole class is unfinished, so it also has to be abstract.
Or another way to put it: if you had an abstract method on a class that wasn't abstract, that would mean you had a method that cannot be called. But that means the method is not useful, you could remove it and it would all work the same.
Now, I'll try to be more concrete by using an example: imagine the following code:
Animal[] zoo = new Animal[] { new Monkey(), new Fish(), new Animal() };
foreach (Animal animal in zoo)
animal.MakeSound();
Here, Animal is the non-abstract base class (which is why I can put it directly into the array), Monkey and Fish are derived from Animal and MakeSound() is the abstract method. What should this code do? You didn't state that clearly, but I can imagine few options:
You can't call MakeSound() on a variable typed as Animal, you can call it only using a variable typed as one of the derived classes, so this is a compile error.
This is not a good solution, because the whole point of abstract is to be able to treat instances of derived classes as the base class, and still get behaviour that's specific to the derived class. If you want this, just put a normal (no abstract, virtual or override) method into each derived class and don't do anything with the base class.
You can't call MakeSound() on an object whose runtime type is actually Animal, so this is a runtime error (an exception).
This is also not a good solution. C# is a statically typed language and so it tries to catch errors like “you can't call this method” at compile time (with obvious exceptions like reflection and dynamic), so making this into a runtime error wouldn't fit with the rest of the language. Besides, you can do this easily by creating a virtual method in the base class that throws an exception.
To sum up, you want something that doesn't make much sense, and smells of bad design (a base class that behaves differently than its derived classes) and can be worked around quite easily. These are all signs of a feature that should not be implemented.
So, you want to allow
class C { abstract void M(); }
to compile. Suppose it did. What do you then want to happen when someone does
new C().M();
? You want an execution-time error? Well, in general C# prefers compile-time errors to execution-time errors. If you don't like that philosophy, there are other languages available...
I think you've answered your own question, an abstract method isn't defined initially. Therefore the class cannot be instanciated. You're saying it should ignore it, but by definition when adding an abstract method you're saying "every class created from this must implement this {abstract method}" hence the class where you define the abstract class must also be abstract because the abstract method is still undefined at that point.
The abstract class may contain abstract member. There is the only method declaration if any method has an abstract keyword we can't implement in the same class. So the abstract class is incompleted. That is why the object is not created for an abstract class.
Non-abstract class can't contain abstract member.
Example:
namespace InterviewPreparation
{
public abstract class baseclass
{
public abstract void method1(); //abstract method
public abstract void method2(); //abstract method
public void method3() { } //Non- abstract method----->It is necessary to implement here.
}
class childclass : baseclass
{
public override void method1() { }
public override void method2() { }
}
public class Program //Non Abstract Class
{
public static void Main()
{
baseclass b = new childclass(); //create instance
b.method1();
b.method2();
b.method3();
}
}
}
You can achieve what you want using "virtual" methods but using virtual methods can lead to more runtime business logic errors as a developer is not "forced" to implement the logic in the child class.
I think there's a valid point here. An abstract method is the perfect solution as it would "enforce" the requirement of defining the method body in children.
I have come across many many situations where the parent class had to (or it would be more efficient to) implement some logic but "Only" children could implement rest of the logic"
So if the opportunity was there I would happily mix abstract methods with complete methods.
#AakashM, I appreciate C# prefers compile time errors. So do I. And so does anybody. This is about thinking out-of-the-box.
And supporting this will not affect that.
Let's think out of the box here, rather than saying "hurrah" to big boy decisions.
C# compiler can detect and deny someone of using an abstract class directly because it uses the "abstract" keyword.
C# also knows to force any child class to implement any abstract methods. How? because of the use of the "abstract" keyword.
This is pretty simple to understand to anyone who has studied the internals of a programming language.
So, why can't C# detect an "abstract" keyword next to a method in a normal class and handle it at the COMPILE TIME.
The reason is it takes "reworking" and the effort is not worth supporting the small demand.
Specially in an industry that lacks people who think out of the boxes that big boys have given them.
It's still not clear why you would want that, but an alternative approach could be to force derived classes to provide a delegate instance. Something like this
class MyConcreteClass
{
readonly Func<int, DateTime, string> methodImpl;
// constructor requires a delegate instance
public MyConcreteClass(Func<int, DateTime, string> methodImpl)
{
if (methodImpl == null)
throw new ArgumentNullException();
this.methodImpl = methodImpl;
}
...
}
(The signature string MethodImpl(int, DateTime) is just an example, of course.)
Otherwise, I can recommend the other answers to explain why your wish probably isn't something which would make the world better.
So the answers above are correct: having abstract methods makes the class inherently abstract. If you cannot instance part of a class, then you cannot instance the class itself. However, the answers above didn't really discuss your options here.
First, this is mainly an issue for public static methods. If the methods aren't intended to be public, then you could have protected non-abstract methods, which are allowed in an abstract class declaration. So, you could just move these static methods to a separate static class without much issue.
As an alternative, you could keep those methods in the class, but then instead of having abstract methods, declare an interface. Essentially, you have a multiple-inheritance problem as you want the derived class to inherit from two conceptually different objects: a non-abstract parent with public static members, and an abstract parent with abstract methods. Unlike some other frameworks, C# does permit multiple inheritance. Instead, C# offers a formal interface declaration that is intended to fill this purpose. Moreover, the whole point of abstract methods, really, is just to impose a certain conceptual interface.
I have a scenario very similar to what the OP is trying to achieve. In my case the method that I want to make abstract would be a protected method and would only be known to the base class. So the "new C().M();" does not apply because the method in question is not public. I want to be able to instantiate and call public methods on the base class (therefore it needs to be non-abstract), but I need these public methods to call a protected implementation of the protected method in the child class and have no default implementation in the parent. In a manner of speaking, I need to force descendants to override the method. I don't know what the child class is at compile time due to dependency injection.
My solution was to follow the rules and use a concrete base class and a virtual protected method. For the default implementation, though, I throw a NotImplementedException with the error "The implementation for method name must be provided in the implementation of the child class."
protected virtual void MyProtectedMethod()
{
throw new NotImplementedException("The implementation for MyProtectedMethod must be provided in the implementation of the child class.");
}
In this way a default implementation can never be used and implementers of descendant implementations will quickly see that they missed an important step.

Is an interface and an abstract class with just virtual abstract methods the same thing?

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.

abstract method use vs regular methods

I would like to know the difference between two conventions:
Creating an abstract base class with an abstract method
which will be implemented later on the derived classes.
Creating an abstract base class without abstract methods
but adding the relevant method later on the level of the derived classes.
What is the difference?
Much like interfaces, abstract classes are designed to express a set of known operations for your types. Unlike interfaces however, abstract classes allow you to implement common/shared functionality that may be used by any derived type. E.g.:
public abstract class LoggerBase
{
public abstract void Write(object item);
protected virtual object FormatObject(object item)
{
return item;
}
}
In this really basic example above, I've essentially done two things:
Defined a contract that my derived types will conform to.
Provides some default functionality that could be overriden if required.
Given that I know that any derived type of LoggerBase will have a Write method, I can call that. The equivalent of the above as an interface could be:
public interface ILogger
{
void Write(object item);
}
As an abstract class, I can provide an additional service FormatObject which can optionally be overriden, say if I was writing a ConsoleLogger, e.g.:
public class ConsoleLogger : LoggerBase
{
public override void Write(object item)
{
Console.WriteLine(FormatObject(item));
}
}
By marking the FormatObject method as virtual, it means I can provide a shared implementation. I can also override it:
public class ConsoleLogger : LoggerBase
{
public override void Write(object item)
{
Console.WriteLine(FormatObject(item));
}
protected override object FormatObject(object item)
{
return item.ToString().ToUpper();
}
}
So, the key parts are:
abstract classes must be inherited.
abstract methods must be implemented in derived types.
virtual methods can be overriden in derived types.
In the second scenario, because you wouldn't be adding the functionality to the abstract base class, you couldn't call that method when dealing with an instance of the base class directly. E.g., if I implemented ConsoleLogger.WriteSomethingElse, I couldn't call it from LoggerBase.WriteSomethingElse.
The idea of putting abstract methods in a base class and then implementing them in subclasses is that you can then use the parent type instead of any specific subclass. For example say you want to sort an array. You can define the base class to be something like
abstract class Sorter {
public abstract Array sort(Array arr);
}
Then you can implement various algorithms such as quicksort, mergesort, heapsort in subclasses.
class QuickSorter {
public Array sort(Array arr) { ... }
}
class MergeSorter {
public Array sort(Array arr) { ... }
}
You create a sorting object by choosing an algorithm,
Sorter sorter = QuickSorter();
Now you can pass sorter around, without exposing the fact that under the hood it's a quicksort. To sort an array you say
Array sortedArray = sorter.sort(someArray);
In this way the details of the implementation (which algorithm you use) are decoupled from the interface to the object (the fact that it sorts an array).
One concrete advantage is that if at some point you want a different sorting algorithm then you can change QuickSort() to say MergeSort in this single line, without having to change it anywhere else. If you don't include a sort() method in the parent, you have to downcast to QuickSorter whenever calling sort(), and then changing the algorithm will be more difficult.
In the case 1) you can access those methods from the abstract base type without knowing the exact type (abstract methods are virtual methods).
The point of the abstract classes is usually to define some contract on the base class which is then implemented by the dervied classes (and in this context it is important to recognize that interfaces are sort of "pure abstract classes").
Uhm, well, the difference is that the base class would know about the former, and not about the latter.
In other words, with an abstract method in the base class, you can write code in other methods in the base class that call that abstract method.
Obviously, if the base class doesn't have those methods... you can't call them...
An abstract function can have no functionality. You're basically saying, any child class MUST give their own version of this method, however it's too general to even try to implement in the parent class. A virtual function, is basically saying look, here's the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality...
And of course, if you override a virtual method, you can always refer to the parent method by calling base.myVirtualMethod()
Okay, when you see a method like this:
A.Foo();
What you really have (behind the scenes) is a signature like this.
Foo(A x);
And when you call A.Foo() you're really calling Foo(this) where this is a reference to an object of type A.
Now, sometimes you'd like to have Foo(A|B|C|D...) where Foo is a method that can take either a type A, or B, or C, or D. But you don't want to worry about what type you're passing, you just want it to do something different based on the type that was passed in. Abstract methods let you do that, that's their only purpose.

Force calling the base method from outside a derived 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();

Categories