C# method implementation with dot notation - c#

Reading an article I came across the following C# syntax in method name.
private class sortYearAscendingHelper : IComparer
{
int IComparer.Compare(object a, object b)
{
...
}
}
I understand Compare method is method of IComparer interface, but coming from C++ I am not certain what this syntax means. If Compare is part of interface, I would expect to mention that only like int Compare(...). Why we have to specify class?

That is an explicit interface implementation You use it when you derive from multiple interfaces that contain similar (same signature) functions but need different implementations for each interface.
More information can be found on MSDN.
(Sample from linked page):
If the two interface members do not perform the same function,
however, this can lead to an incorrect implementation of one or both
of the interfaces. It is possible to implement an interface member
explicitly—creating a class member that is only called through the
interface, and is specific to that interface. This is accomplished by
naming the class member with the name of the interface and a period.
For example:
public class SampleClass : IControl, ISurface
{
void IControl.Paint()
{
System.Console.WriteLine("IControl.Paint");
}
void ISurface.Paint()
{
System.Console.WriteLine("ISurface.Paint");
}
}
The class member IControl.Paint is only available through the IControl
interface, and ISurface.Paint is only available through ISurface. Both
method implementations are separate, and neither is available directly
on the class.

Related

C# interface class is not visible [duplicate]

What are the differences in implementing interfaces implicitly and explicitly in C#?
When should you use implicit and when should you use explicit?
Are there any pros and/or cons to one or the other?
Microsoft's official guidelines (from first edition Framework Design Guidelines) states that using explicit implementations are not recommended, since it gives the code unexpected behaviour.
I think this guideline is very valid in a pre-IoC-time, when you don't pass things around as interfaces.
Could anyone touch on that aspect as well?
Implicit is when you define your interface via a member on your class. Explicit is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: IList.CopyTo would be implicitly implemented as:
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
and explicitly as:
void ICollection.CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
The difference is that implicit implementation allows you to access the interface through the class you created by casting the interface as that class and as the interface itself. Explicit implementation allows you to access the interface only by casting it as the interface itself.
MyClass myClass = new MyClass(); // Declared as concrete class
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.
I use explicit primarily to keep the implementation clean, or when I need two implementations. Regardless, I rarely use it.
I am sure there are more reasons to use/not use explicit that others will post.
See the next post in this thread for excellent reasoning behind each.
Implicit definition would be to just add the methods / properties, etc. demanded by the interface directly to the class as public methods.
Explicit definition forces the members to be exposed only when you are working with the interface directly, and not the underlying implementation. This is preferred in most cases.
By working directly with the interface, you are not acknowledging,
and coupling your code to the underlying implementation.
In the event that you already have, say, a public property Name in
your code and you want to implement an interface that also has a
Name property, doing it explicitly will keep the two separate. Even
if they were doing the same thing I'd still delegate the explicit
call to the Name property. You never know, you may want to change
how Name works for the normal class and how Name, the interface
property works later on.
If you implement an interface implicitly then your class now exposes
new behaviours that might only be relevant to a client of the
interface and it means you aren't keeping your classes succinct
enough (my opinion).
In addition to excellent answers already provided, there are some cases where explicit implementation is REQUIRED for the compiler to be able to figure out what is required. Take a look at IEnumerable<T> as a prime example that will likely come up fairly often.
Here's an example:
public abstract class StringList : IEnumerable<string>
{
private string[] _list = new string[] {"foo", "bar", "baz"};
// ...
#region IEnumerable<string> Members
public IEnumerator<string> GetEnumerator()
{
foreach (string s in _list)
{ yield return s; }
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}
Here, IEnumerable<string> implements IEnumerable, hence we need to too. But hang on, both the generic and the normal version both implement functions with the same method signature (C# ignores return type for this). This is completely legal and fine. How does the compiler resolve which to use? It forces you to only have, at most, one implicit definition, then it can resolve whatever it needs to.
ie.
StringList sl = new StringList();
// uses the implicit definition.
IEnumerator<string> enumerableString = sl.GetEnumerator();
// same as above, only a little more explicit.
IEnumerator<string> enumerableString2 = ((IEnumerable<string>)sl).GetEnumerator();
// returns the same as above, but via the explicit definition
IEnumerator enumerableStuff = ((IEnumerable)sl).GetEnumerator();
PS: The little piece of indirection in the explicit definition for IEnumerable works because inside the function the compiler knows that the actual type of the variable is a StringList, and that's how it resolves the function call. Nifty little fact for implementing some of the layers of abstraction some of the .NET core interfaces seem to have accumulated.
Reason #1
I tend to use explicit interface implementation when I want to discourage "programming to an implementation" (Design Principles from Design Patterns).
For example, in an MVP-based web application:
public interface INavigator {
void Redirect(string url);
}
public sealed class StandardNavigator : INavigator {
void INavigator.Redirect(string url) {
Response.Redirect(url);
}
}
Now another class (such as a presenter) is less likely to depend on the StandardNavigator implementation and more likely to depend on the INavigator interface (since the implementation would need to be cast to an interface to make use of the Redirect method).
Reason #2
Another reason I might go with an explicit interface implementation would be to keep a class's "default" interface cleaner. For example, if I were developing an ASP.NET server control, I might want two interfaces:
The class's primary interface, which is used by web page developers; and
A "hidden" interface used by the presenter that I develop to handle the control's logic
A simple example follows. It's a combo box control that lists customers. In this example, the web page developer isn't interested in populating the list; instead, they just want to be able to select a customer by GUID or to obtain the selected customer's GUID. A presenter would populate the box on the first page load, and this presenter is encapsulated by the control.
public sealed class CustomerComboBox : ComboBox, ICustomerComboBox {
private readonly CustomerComboBoxPresenter presenter;
public CustomerComboBox() {
presenter = new CustomerComboBoxPresenter(this);
}
protected override void OnLoad() {
if (!Page.IsPostBack) presenter.HandleFirstLoad();
}
// Primary interface used by web page developers
public Guid ClientId {
get { return new Guid(SelectedItem.Value); }
set { SelectedItem.Value = value.ToString(); }
}
// "Hidden" interface used by presenter
IEnumerable<CustomerDto> ICustomerComboBox.DataSource { set; }
}
The presenter populates the data source, and the web page developer never needs to be aware of its existence.
But's It's Not a Silver Cannonball
I wouldn't recommend always employing explicit interface implementations. Those are just two examples where they might be helpful.
To quote Jeffrey Richter from CLR via C#
(EIMI means Explicit Interface Method Implementation)
It is critically important for you to
understand some ramifications that
exist when using EIMIs. And because of
these ramifications, you should try to
avoid EIMIs as much as possible.
Fortunately, generic interfaces help
you avoid EIMIs quite a bit. But there
may still be times when you will need
to use them (such as implementing two
interface methods with the same name
and signature). Here are the big
problems with EIMIs:
There is no documentation explaining how a type specifically
implements an EIMI method, and there
is no Microsoft Visual Studio
IntelliSense support.
Value type instances are boxed when cast to an interface.
An EIMI cannot be called by a derived type.
If you use an interface reference ANY virtual chain can be explicitly replaced with EIMI on any derived class and when an object of such type is cast to the interface, your virtual chain is ignored and the explicit implementation is called. That's anything but polymorphism.
EIMIs can also be used to hide non-strongly typed interface members from basic Framework Interfaces' implementations such as IEnumerable<T> so your class doesn't expose a non strongly typed method directly, but is syntactical correct.
I use explicit interface implementation most of the time. Here are the main reasons.
Refactoring is safer
When changing an interface, it's better if the compiler can check it. This is harder with implicit implementations.
Two common cases come to mind:
Adding a function to an interface, where an existing class that implements this interface already happens to have a method with the same signature as the new one. This can lead to unexpected behavior, and has bitten me hard several times. It's difficult to "see" when debugging because that function is likely not located with the other interface methods in the file (the self-documenting issue mentioned below).
Removing a function from an interface. Implicitly implemented methods will be suddenly dead code, but explicitly implemented methods will get caught by compile error. Even if the dead code is good to keep around, I want to be forced to review it and promote it.
It's unfortunate that C# doesn't have a keyword that forces us to mark a method as an implicit implementation, so the compiler could do the extra checks. Virtual methods don't have either of the above problems due to required use of 'override' and 'new'.
Note: for fixed or rarely-changing interfaces (typically from vendor API's), this is not a problem. For my own interfaces, though, I can't predict when/how they will change.
It's self-documenting
If I see 'public bool Execute()' in a class, it's going to take extra work to figure out that it's part of an interface. Somebody will probably have to comment it saying so, or put it in a group of other interface implementations, all under a region or grouping comment saying "implementation of ITask". Of course, that only works if the group header isn't offscreen..
Whereas: 'bool ITask.Execute()' is clear and unambiguous.
Clear separation of interface implementation
I think of interfaces as being more 'public' than public methods because they are crafted to expose just a bit of the surface area of the concrete type. They reduce the type to a capability, a behavior, a set of traits, etc. And in the implementation, I think it's useful to keep this separation.
As I am looking through a class's code, when I come across explicit interface implementations, my brain shifts into "code contract" mode. Often these implementations simply forward to other methods, but sometimes they will do extra state/param checking, conversion of incoming parameters to better match internal requirements, or even translation for versioning purposes (i.e. multiple generations of interfaces all punting down to common implementations).
(I realize that publics are also code contracts, but interfaces are much stronger, especially in an interface-driven codebase where direct use of concrete types is usually a sign of internal-only code.)
Related: Reason 2 above by Jon.
And so on
Plus the advantages already mentioned in other answers here:
When required, as per disambiguation or needing an internal interface
Discourages "programming to an implementation" (Reason 1 by Jon)
Problems
It's not all fun and happiness. There are some cases where I stick with implicits:
Value types, because that will require boxing and lower perf. This isn't a strict rule, and depends on the interface and how it's intended to be used. IComparable? Implicit. IFormattable? Probably explicit.
Trivial system interfaces that have methods that are frequently called directly (like IDisposable.Dispose).
Also, it can be a pain to do the casting when you do in fact have the concrete type and want to call an explicit interface method. I deal with this in one of two ways:
Add publics and have the interface methods forward to them for the implementation. Typically happens with simpler interfaces when working internally.
(My preferred method) Add a public IMyInterface I { get { return this; } } (which should get inlined) and call foo.I.InterfaceMethod(). If multiple interfaces that need this ability, expand the name beyond I (in my experience it's rare that I have this need).
In addition to the other reasons already stated, this is the situation in which a class is implementing two different interfaces that have a property/method with the same name and signature.
/// <summary>
/// This is a Book
/// </summary>
interface IBook
{
string Title { get; }
string ISBN { get; }
}
/// <summary>
/// This is a Person
/// </summary>
interface IPerson
{
string Title { get; }
string Forename { get; }
string Surname { get; }
}
/// <summary>
/// This is some freaky book-person.
/// </summary>
class Class1 : IBook, IPerson
{
/// <summary>
/// This method is shared by both Book and Person
/// </summary>
public string Title
{
get
{
string personTitle = "Mr";
string bookTitle = "The Hitchhikers Guide to the Galaxy";
// What do we do here?
return null;
}
}
#region IPerson Members
public string Forename
{
get { return "Lee"; }
}
public string Surname
{
get { return "Oades"; }
}
#endregion
#region IBook Members
public string ISBN
{
get { return "1-904048-46-3"; }
}
#endregion
}
This code compiles and runs OK, but the Title property is shared.
Clearly, we'd want the value of Title returned to depend on whether we were treating Class1 as a Book or a Person. This is when we can use the explicit interface.
string IBook.Title
{
get
{
return "The Hitchhikers Guide to the Galaxy";
}
}
string IPerson.Title
{
get
{
return "Mr";
}
}
public string Title
{
get { return "Still shared"; }
}
Notice that the explicit interface definitions are inferred to be Public - and hence you can't declare them to be public (or otherwise) explicitly.
Note also that you can still have a "shared" version (as shown above), but whilst this is possible, the existence of such a property is questionable. Perhaps it could be used as a default implementation of Title - so that existing code would not have to be modified to cast Class1 to IBook or IPerson.
If you do not define the "shared" (implicit) Title, consumers of Class1 must explicitly cast instances of Class1 to IBook or IPerson first - otherwise the code will not compile.
If you implement explicitly, you will only be able to reference the interface members through a reference that is of the type of the interface. A reference that is the type of the implementing class will not expose those interface members.
If your implementing class is not public, except for the method used to create the class (which could be a factory or IoC container), and except for the interface methods (of course), then I don't see any advantage to explicitly implementing interfaces.
Otherwise, explicitly implementing interfaces makes sure that references to your concrete implementing class are not used, allowing you to change that implementation at a later time. "Makes sure", I suppose, is the "advantage". A well-factored implementation can accomplish this without explicit implementation.
The disadvantage, in my opinion, is that you will find yourself casting types to/from the interface in the implementation code that does have access to non-public members.
Like many things, the advantage is the disadvantage (and vice-versa). Explicitly implementing interfaces will ensure that your concrete class implementation code is not exposed.
An implicit interface implementation is where you have a method with the same signature of the interface.
An explicit interface implementation is where you explicitly declare which interface the method belongs to.
interface I1
{
void implicitExample();
}
interface I2
{
void explicitExample();
}
class C : I1, I2
{
void implicitExample()
{
Console.WriteLine("I1.implicitExample()");
}
void I2.explicitExample()
{
Console.WriteLine("I2.explicitExample()");
}
}
MSDN: implicit and explicit interface implementations
Every class member that implements an interface exports a declaration which is semantically similar to the way VB.NET interface declarations are written, e.g.
Public Overridable Function Foo() As Integer Implements IFoo.Foo
Although the name of the class member will often match that of the interface member, and the class member will often be public, neither of those things is required. One may also declare:
Protected Overridable Function IFoo_Foo() As Integer Implements IFoo.Foo
In which case the class and its derivatives would be allowed to access a class member using the name IFoo_Foo, but the outside world would only be able to access that particular member by casting to IFoo. Such an approach is often good in cases where an interface method will have specified behavior on all implementations, but useful behavior on only some [e.g. the specified behavior for a read-only collection's IList<T>.Add method is to throw NotSupportedException]. Unfortunately, the only proper way to implement the interface in C# is:
int IFoo.Foo() { return IFoo_Foo(); }
protected virtual int IFoo_Foo() { ... real code goes here ... }
Not as nice.
The previous answers explain why implementing an interface explicitly in C# may be preferrable (for mostly formal reasons). However, there is one situation where explicit implementation is mandatory: In order to avoid leaking the encapsulation when the interface is non-public, but the implementing class is public.
// Given:
internal interface I { void M(); }
// Then explicit implementation correctly observes encapsulation of I:
// Both ((I)CExplicit).M and CExplicit.M are accessible only internally.
public class CExplicit: I { void I.M() { } }
// However, implicit implementation breaks encapsulation of I, because
// ((I)CImplicit).M is only accessible internally, while CImplicit.M is accessible publicly.
public class CImplicit: I { public void M() { } }
The above leakage is unavoidable because, according to the C# specification, "All interface members implicitly have public access." As a consequence, implicit implementations must also give public access, even if the interface itself is e.g. internal.
Implicit interface implementation in C# is a great convenience. In practice, many programmers use it all the time/everywhere without further consideration. This leads to messy type surfaces at best and leaked encapsulation at worst. Other languages, such as F#, don't even allow it.
One important use of explicit interface implementation is when in need to implement interfaces with mixed visibility.
The problem and solution are well explained in the article C# Internal Interface.
For example, if you want to protect leakage of objects between application layers, this technique allows you to specify different visibility of members that could cause the leakage.
I've found myself using explicit implementations more often recently, for the following practical reasons:
Always using explicit from the starts prevents having any naming collisions, in which explicit implementation would be required anyways
Consumers are "forced" to use the interface instead of the implementation (aka not "programming to an implementation") which they should / must do anyways when you're using DI
No "zombie" members in the implementations - removing any member from the interface declaration will result in compiler errors if not removed from the implementation too
Default values for optional parameters, as well constraints on generic arguments are automatically adopted - no need to write them twice and keep them in sync

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.

Predefined Interface exposes some method,we are using that method but interface doent have definition part ,then how its working in c#?

Interface exposes some method,we are using that method in class but interface doent have definition part ,then how its working in c#.
For Example
class ProductNameComparer : IComparer
{
public int Compare(object x, object y)
{
Product first = (Product)x;
Product second = (Product)y;
return first.Name.CompareTo(second.Name);
}
}
Here IComparer exposes CompareTo() method, but IComparer doesn't have CompareTo() method definition part, then how its working?
Interface are simply contract which only declares method rather than having implementation part....Class which implements that particular Interface should have implemenation detail.
For instance, You have IAnimal interface and Dog is a class which implements IAnimal interface,
public interface IAnimal
{
void Walk(); // Just declares the method, not implemenation
}
//Class implementing the interface
//must define the method specified in the interface
class Dog : IAnimal
{
public void Walk()
{
Console.WriteLine("Dog can walk");
}
}
In your example, you misunderstood the IComparer interface.
IComparer defines an interface with a Compare() method
whereas
CompareTo() is declared by IComparable interface.
In above code, you have implemented IComparer interface so, you are defining Compare() method details in your ProductNameComparer class.
An interface doesn't have any implementation, it's only a contract for how something should work.
You can't create an instance of an interface, you can only create instances of actual classes (or structs) that implement the interface. If you get a reference to an interface, it points to an actual object that implements the interface.
Any class that implements the interface has to implement all members of the interface, so if you have an actual object that fits the interface, you know that the method is implemented.
You can use an interface without any knowledge of any class that implements it, so you can write code that uses an interface even before there is any actual implementation of the interface.
Here IComparer exposes CompareTo() method, but IComparer doesn't have CompareTo() method definition part, then how its working?
If this is your question that I think you are very much misunderstanding what is going and what "exposed" means.
Using your example:
class ProductNameComparer : IComparer
{
public int Compare(object x, object y)
{
Product first = (Product)x;
Product second = (Product)y;
return first.Name.CompareTo(second.Name);
}
}
Your ProductNameComparer class is implementing IComparer. The requirement classes implementing IComparer is they contain a method with the signature Compare(object x, object y). This is the only thing that your ProductNameComparer is exposing. That is nothing else.
Now you are using CompareTo() within the method, but you are not exposing it publicly. It is difficult to explain in more detail without knowing the definition of Product.Name, but let's assume it is a string.
System.String implements IComparable (among other interfaces), so string has a CompareTo() method. You are simply calling String.CompareTo() in your method, but nothing is exposed.
Interfaces define the contract between types, they don't define the implementation, that's up to the classes implementing the interface.
Consider:
interface IWorkable
{
void DoWork();
}
Then the implementation:
public class GoodWork : IWorkable
{
public void DoWork()
{
//add the implementation here
}
}
You should read a good c# tutorial before beginning to program..
http://www.codeproject.com/Articles/18743/Interfaces-in-C-For-Beginners
CompareTo method is not from IComparer but it is the method of your property first.Name which I suppose is a string.

interface with base class and derived class to achieve multiple inheritance

I got the following code where i would like to know the relationship between those class and interface.
Multiple inheritance wont work with C# but can we implement using interface?
Please tell me whether the following code will complie or not? why it is so ?
I am very confused?
Pleasehelp me out........
public interface MyInterface
{
void Method();
}
public class Base
{
public void Method() { }
}
public class Derived : Base, MyInterface { }
Please tell me whether the following code will complie or not?
Yes, it will - but you could have found that out for yourself just by trying it.
Why it is so?
Quite simply, Derived implements the contract required by MyInterface. It happens to do that via Base which is unaware of the interface, but it still has all the relevant members.
There's a danger here, though - in reality, interfaces are about more than just having appropriate members available for callers; they're about the semantics of those members. A class hierarchy like this only works when the semantics of Base.Method() exactly match the requirements of MyInterface.Method() by coincidence (as opposed to by explicit, declared design). Even if it's valid to start with, the maintainer of Base may decide to make a change to the behaviour of Method which is valid according to what Base.Method has guaranteed, but isn't valid according to what the interface guarantees.
EDIT: In terms of the language specification, this is in section 13.4.4 of the C# 4 spec:
A class or struct must provide implementations of all members of the interfaces that are listed in the base class list of the class or struct. The process of locating implementations of interface members in an implementing class or struct is known as interface mapping.
Interface mapping for a class or struct C locates an implementation for each member of each interface specified in the base class list of C. The implementation of a particular interface member I.M, where I is the interface in which the member M is declared, is determined by examining each class or struct S, starting with C and repeating for each successive base class of C, until a match is located.
[...]
A compile-time error occurs if implementations cannot be located for all members of all interfaces specified in the base class list of C.

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.

Categories