new word in interfaces in c# - c#

using System;
namespace random
{
interface IHelper
{
void HelpMeNow();
}
public class Base : IHelper
{
public void HelpMeNow()
{
Console.WriteLine("Base.HelpMeNow()");
}
}
public class Derived : Base
{
public new void HelpMeNow() ///this line
{
Console.WriteLine("Derived.HelpMeNow()");
}
}
class Test
{
public static void Main()
{
Derived der = new Derived();
der.HelpMeNow();
IHelper helper = (IHelper)der;
helper.HelpMeNow();
Console.ReadLine();
}
}
}
the new keyword in the commented line is a little confusing for me. It jsut mean it overrides the implementation of method in base class.
Why not use override keyword?

It's not really overriding it, it's shadowing it. Given a reference to a Derived object, Base's HelpMeNow function will not be accessible1, and derivedObject.HelpMeNow() will call Derived's implementation.
This is not the same as overriding a virtual function, which HelpMeNow is not. If a Derived object is stored in a reference to a Base, or to an IHelper, then Base's HelpMeNow() will be called, and Derived's implementation will be inaccessible.
Derived derivedReference = new Derived();
Base baseReference = derivedReference;
IHelper helperReference = derivedReference;
derivedReference.HelpMeNow(); // outputs "Derived.HelpMeNow()"
baseReference.HelpMeNow(); // outputs "Base.HelpMeNow()"
helperReference.HelpMeNow(); // outputs "Base.HelpMeNow()"
Of course, if the above is not the desired behavior, and it's usually not, there are two possibilities. If you control Base, simply change HelpMeNow() to virtual, and override it in Derived instead of shadowing it. If you don't control Base, then you can at least fix it halfway, by reimplementing IHelper, like so:
class Derived : Base, IHelper{
public new void HelpMeNow(){Console.WriteLine("Derived.HelpMeNow()");}
void IHelper.HelpMeNow(){HelpMeNow();}
}
This version of Derived uses what's called explicit interface implementation, which allows you to satisfy the contract of implementing an interface without adding the implementation to your class's public interface. In this example, we already have an implementation in Derived's public interface that's inherited from Base, so we have to explicitly implement IHelper to change it2. In this example, we just forward the implementation of IHelper.HelpMeNow to our public interface, which is the shadow of Base's.
So with this change, a call to baseReference.HelpMeNow() still outputs "Base.HelpMeNow()", but a call to helperReference.HelpMeNow() will now output "Derived.HelpMeNow()". Not as good as changing Base's implementation to virtual, but as good as we're gonna get if we don't control Base.
1Exception: it is accessible from within methods of Derived, but only when qualified with base., as in base.HelpMeNow().
2Notice that we also have to declare IHelper as an interface the class implements, even though we inherit this declaration from Base.

In general, if interface IBase implements a member DoSomething, and IDerived inherits/implements Ibase, it expected that IDerived.DoSomething will be synonymous with IBase.DoSomething. In general, this is useful since it saves implementers of the class from having to provide redundant implementations. There are, however, some cases where a derived interface must implement a member which has the same name as a member in the base interface, but which will have to be implemented separately. The most common such situations are (1) the derived method will have a different return type from the base type, or (2) the base interface(s) implements a ReadOnly and/or WriteOnly property(s) with a certain and the derived type should implement a Read-Write property. For whatever reason, if interface IReadableFoo provides a read-only property Foo, IWritableFoo provides a write-only property Foo, and interface IMutableFoo simply inherits both, the compiler won't know whether a reference to Foo refers to IReadableFoo.Foo or IWritableFoo.Foo. Even though only IReadableFoo.Foo can be read, and only IWritableFoo.Foo can be written, neither vb.net nor C# can resolve the overload unless one implements a new read-write property Foo which handles both.

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.

Interface and abstract class protection level methods

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.

Can an abstract class contain a public method?

Constructors of an abstract class shouldn't be public and they should be protected. My question is about methods in that abstract class. Can we declare them as public or they should be protected too for the same reason?
The justification for constructors on abstract types being protected is that there is simply no other entity that could call the constructor other than a derived type. Making the constructor public is meaningless in this case as it can't ever be invoked outside the type hierarchy. Hence the recommendation is to use protected as it's the most appropriate access modifier.
The same logic doesn't hold true with other members on the type. They can be freely invoked from outside the type hierarchy should their access modifier permit it.
public abstract class Dog {
// Public is appropriate here as any consumer of Dog could access
// Breed on an instantiated object
public abstract string Breed { get; }
// Public would be meaningless here. It's not legal to say
// 'new Dog' because 'Dog' is abstract. You can only say
// 'new Poodle' or 'new Bulldog'. Only derived types like
// Poodle or Bulldog could invoke the Dog constructor hence it's
// protected
protected Dog() { }
}
public class Poodle : Dog { }
public class Bulldog : Dog { }
Whether or not a particular member should be public or protected is highly dependent upon the particular API. The reasoning should be the exact same for abstract types as it is for non-abstract types
Abstract classes shouldn't have public constructors because they don't make sense. Abstract classes are incomplete, so allowing a public constructor (which anyone could call) wouldn't work as you can't instantiate an instance anyway.
Methods on abstract classes are another story. You can have implementation in an abstract class, which is the behavior that all subclasses will inherit. Think of a Shape class. Its purpose is to draw a shape on the screen, so it makes sense to make a Draw method public as you'll want callers to be able to ask your Shape to draw. The method itself can be abstract, forcing subclasses to implement, or possibly provide an implementation which may or may not allow overriding. It depends on what the defined behavior of your class should be.
It depends on your use case. If you want the methods of the abstract class visible to instances of your derived class, you should make them public. If, on the other hand, you want the methods visible only to your derived class, you should make them protected.

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