Related
Why was C# designed this way?
As I understand it, an interface only describes behaviour, and serves the purpose of describing a contractual obligation for classes implementing the interface that certain behaviour is implemented.
If classes wish to implement that behavour in a shared method, why shouldn't they?
Here is an example of what I have in mind:
// These items will be displayed in a list on the screen.
public interface IListItem {
string ScreenName();
...
}
public class Animal: IListItem {
// All animals will be called "Animal".
public static string ScreenName() {
return "Animal";
}
....
}
public class Person: IListItem {
private string name;
// All persons will be called by their individual names.
public string ScreenName() {
return name;
}
....
}
Assuming you are asking why you can't do this:
public interface IFoo {
void Bar();
}
public class Foo: IFoo {
public static void Bar() {}
}
This doesn't make sense to me, semantically. Methods specified on an interface should be there to specify the contract for interacting with an object. Static methods do not allow you to interact with an object - if you find yourself in the position where your implementation could be made static, you may need to ask yourself if that method really belongs in the interface.
To implement your example, I would give Animal a const property, which would still allow it to be accessed from a static context, and return that value in the implementation.
public class Animal: IListItem {
/* Can be tough to come up with a different, yet meaningful name!
* A different casing convention, like Java has, would help here.
*/
public const string AnimalScreenName = "Animal";
public string ScreenName(){ return AnimalScreenName; }
}
For a more complicated situation, you could always declare another static method and delegate to that. In trying come up with an example, I couldn't think of any reason you would do something non-trivial in both a static and instance context, so I'll spare you a FooBar blob, and take it as an indication that it might not be a good idea.
My (simplified) technical reason is that static methods are not in the vtable, and the call site is chosen at compile time. It's the same reason you can't have override or virtual static members. For more details, you'd need a CS grad or compiler wonk - of which I'm neither.
For the political reason, I'll quote Eric Lippert (who is a compiler wonk, and holds a Bachelor of Mathematics, Computer science and Applied Mathematics from University of Waterloo (source: LinkedIn):
...the core design principle of static methods, the principle that gives them their name...[is]...it can always be determined exactly, at compile time, what method will be called. That is, the method can be resolved solely by static analysis of the code.
Note that Lippert does leave room for a so-called type method:
That is, a method associated with a type (like a static), which does not take a non-nullable “this” argument (unlike an instance or virtual), but one where the method called would depend on the constructed type of T (unlike a static, which must be determinable at compile time).
but is yet to be convinced of its usefulness.
Most answers here seem to miss the whole point. Polymorphism can be used not only between instances, but also between types. This is often needed, when we use generics.
Suppose we have type parameter in generic method and we need to do some operation with it. We dont want to instantinate, because we are unaware of the constructors.
For example:
Repository GetRepository<T>()
{
//need to call T.IsQueryable, but can't!!!
//need to call T.RowCount
//need to call T.DoSomeStaticMath(int param)
}
...
var r = GetRepository<Customer>()
Unfortunately, I can come up only with "ugly" alternatives:
Use reflection
Ugly and beats the idea of interfaces and polymorphism.
Create completely separate factory class
This might greatly increase the complexity of the code. For example, if we are trying to model domain objects, each object would need another repository class.
Instantiate and then call the desired interface method
This can be hard to implement even if we control the source for the classes, used as generic parameters. The reason is that, for example we might need the instances to be only in well-known, "connected to DB" state.
Example:
public class Customer
{
//create new customer
public Customer(Transaction t) { ... }
//open existing customer
public Customer(Transaction t, int id) { ... }
void SomeOtherMethod()
{
//do work...
}
}
in order to use instantination for solving the static interface problem we need to do the following thing:
public class Customer: IDoSomeStaticMath
{
//create new customer
public Customer(Transaction t) { ... }
//open existing customer
public Customer(Transaction t, int id) { ... }
//dummy instance
public Customer() { IsDummy = true; }
int DoSomeStaticMath(int a) { }
void SomeOtherMethod()
{
if(!IsDummy)
{
//do work...
}
}
}
This is obviously ugly and also unnecessary complicates the code for all other methods. Obviously, not an elegant solution either!
I know it's an old question, but it's interesting. The example isn't the best. I think it would be much clearer if you showed a usage case:
string DoSomething<T>() where T:ISomeFunction
{
if (T.someFunction())
...
}
Merely being able to have static methods implement an interface would not achieve what you want; what would be needed would be to have static members as part of an interface. I can certainly imagine many usage cases for that, especially when it comes to being able to create things. Two approaches I could offer which might be helpful:
Create a static generic class whose type parameter will be the type you'd be passing to DoSomething above. Each variation of this class will have one or more static members holding stuff related to that type. This information could supplied either by having each class of interest call a "register information" routine, or by using Reflection to get the information when the class variation's static constructor is run. I believe the latter approach is used by things like Comparer<T>.Default().
For each class T of interest, define a class or struct which implements IGetWhateverClassInfo<T> and satisfies a "new" constraint. The class won't actually contain any fields, but will have a static property which returns a static field with the type information. Pass the type of that class or struct to the generic routine in question, which will be able to create an instance and use it to get information about the other class. If you use a class for this purpose, you should probably define a static generic class as indicated above, to avoid having to construct a new descriptor-object instance each time. If you use a struct, instantiation cost should be nil, but every different struct type would require a different expansion of the DoSomething routine.
None of these approaches is really appealing. On the other hand, I would expect that if the mechanisms existed in CLR to provide this sort of functionality cleanly, .net would allow one to specify parameterized "new" constraints (since knowing if a class has a constructor with a particular signature would seem to be comparable in difficulty to knowing if it has a static method with a particular signature).
Short-sightedness, I'd guess.
When originally designed, interfaces were intended only to be used with instances of class
IMyInterface val = GetObjectImplementingIMyInterface();
val.SomeThingDefinedinInterface();
It was only with the introduction of interfaces as constraints for generics did adding a static method to an interface have a practical use.
(responding to comment:) I believe changing it now would require a change to the CLR, which would lead to incompatibilities with existing assemblies.
To the extent that interfaces represent "contracts", it seems quiet reasonable for static classes to implement interfaces.
The above arguments all seem to miss this point about contracts.
Interfaces specify behavior of an object.
Static methods do not specify a behavior of an object, but behavior that affects an object in some way.
Because the purpose of an interface is to allow polymorphism, being able to pass an instance of any number of defined classes that have all been defined to implement the defined interface... guaranteeing that within your polymorphic call, the code will be able to find the method you are calling. it makes no sense to allow a static method to implement the interface,
How would you call it??
public interface MyInterface { void MyMethod(); }
public class MyClass: MyInterface
{
public static void MyMethod() { //Do Something; }
}
// inside of some other class ...
// How would you call the method on the interface ???
MyClass.MyMethod(); // this calls the method normally
// not through the interface...
// This next fails you can't cast a classname to a different type...
// Only instances can be Cast to a different type...
MyInterface myItf = MyClass as MyInterface;
Actually, it does.
As of Mid-2022, the current version of C# has full support for so-called static abstract members:
interface INumber<T>
{
static abstract T Zero { get; }
}
struct Fraction : INumber<Fraction>
{
public static Fraction Zero { get; } = new Fraction();
public long Numerator;
public ulong Denominator;
....
}
Please note that depending on your version of Visual Studio and your installed .NET SDK, you'll either have to update at least one of them (or maybe both), or that you'll have to enable preview features (see Use preview features & preview language in Visual Studio).
See more:
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members
https://blog.ndepend.com/c-11-static-abstract-members/
https://khalidabuhakmeh.com/static-abstract-members-in-csharp-10-interfaces#:~:text=Static%20abstract%20members%20allow%20each,like%20any%20other%20interface%20definition.
Regarding static methods used in non-generic contexts I agree that it doesn't make much sense to allow them in interfaces, since you wouldn't be able to call them if you had a reference to the interface anyway. However there is a fundamental hole in the language design created by using interfaces NOT in a polymorphic context, but in a generic one. In this case the interface is not an interface at all but rather a constraint. Because C# has no concept of a constraint outside of an interface it is missing substantial functionality. Case in point:
T SumElements<T>(T initVal, T[] values)
{
foreach (var v in values)
{
initVal += v;
}
}
Here there is no polymorphism, the generic uses the actual type of the object and calls the += operator, but this fails since it can't say for sure that that operator exists. The simple solution is to specify it in the constraint; the simple solution is impossible because operators are static and static methods can't be in an interface and (here is the problem) constraints are represented as interfaces.
What C# needs is a real constraint type, all interfaces would also be constraints, but not all constraints would be interfaces then you could do this:
constraint CHasPlusEquals
{
static CHasPlusEquals operator + (CHasPlusEquals a, CHasPlusEquals b);
}
T SumElements<T>(T initVal, T[] values) where T : CHasPlusEquals
{
foreach (var v in values)
{
initVal += v;
}
}
There has been lots of talk already about making an IArithmetic for all numeric types to implement, but there is concern about efficiency, since a constraint is not a polymorphic construct, making a CArithmetic constraint would solve that problem.
Because interfaces are in inheritance structure, and static methods don't inherit well.
What you seem to want would allow for a static method to be called via both the Type or any instance of that type. This would at very least result in ambiguity which is not a desirable trait.
There would be endless debates about whether it mattered, which is best practice and whether there are performance issues doing it one way or another. By simply not supporting it C# saves us having to worry about it.
Its also likely that a compilier that conformed to this desire would lose some optimisations that may come with a more strict separation between instance and static methods.
You can think of the static methods and non-static methods of a class as being different interfaces. When called, static methods resolve to the singleton static class object, and non-static methods resolve to the instance of the class you deal with. So, if you use static and non-static methods in an interface, you'd effectively be declaring two interfaces when really we want interfaces to be used to access one cohesive thing.
To give an example where I am missing either static implementation of interface methods or what Mark Brackett introduced as the "so-called type method":
When reading from a database storage, we have a generic DataTable class that handles reading from a table of any structure. All table specific information is put in one class per table that also holds data for one row from the DB and which must implement an IDataRow interface. Included in the IDataRow is a description of the structure of the table to read from the database. The DataTable must ask for the datastructure from the IDataRow before reading from the DB. Currently this looks like:
interface IDataRow {
string GetDataSTructre(); // How to read data from the DB
void Read(IDBDataRow); // How to populate this datarow from DB data
}
public class DataTable<T> : List<T> where T : IDataRow {
public string GetDataStructure()
// Desired: Static or Type method:
// return (T.GetDataStructure());
// Required: Instantiate a new class:
return (new T().GetDataStructure());
}
}
The GetDataStructure is only required once for each table to read, the overhead for instantiating one more instance is minimal. However, it would be nice in this case here.
FYI: You could get a similar behavior to what you want by creating extension methods for the interface. The extension method would be a shared, non overridable static behavior. However, unfortunately, this static method would not be part of the contract.
Interfaces are abstract sets of defined available functionality.
Whether or not a method in that interface behaves as static or not is an implementation detail that should be hidden behind the interface. It would be wrong to define an interface method as static because you would be unnecessarily forcing the method to be implemented in a certain way.
If methods were defined as static, the class implementing the interface wouldn't be as encapsulated as it could be. Encapsulation is a good thing to strive for in object oriented design (I won't go into why, you can read that here: http://en.wikipedia.org/wiki/Object-oriented). For this reason, static methods aren't permitted in interfaces.
Static classes should be able to do this so they can be used generically. I had to instead implement a Singleton to achieve the desired results.
I had a bunch of Static Business Layer classes that implemented CRUD methods like "Create", "Read", "Update", "Delete" for each entity type like "User", "Team", ect.. Then I created a base control that had an abstract property for the Business Layer class that implemented the CRUD methods. This allowed me to automate the "Create", "Read", "Update", "Delete" operations from the base class. I had to use a Singleton because of the Static limitation.
Most people seem to forget that in OOP Classes are objects too, and so they have messages, which for some reason c# calls "static method".
The fact that differences exist between instance objects and class objects only shows flaws or shortcomings in the language.
Optimist about c# though...
OK here is an example of needing a 'type method'. I am creating one of a set of classes based on some source XML. So I have a
static public bool IsHandled(XElement xml)
function which is called in turn on each class.
The function should be static as otherwise we waste time creating inappropriate objects.
As #Ian Boyde points out it could be done in a factory class, but this just adds complexity.
It would be nice to add it to the interface to force class implementors to implement it. This would not cause significant overhead - it is only a compile/link time check and does not affect the vtable.
However, it would also be a fairly minor improvement. As the method is static, I as the caller, must call it explicitly and so get an immediate compile error if it is not implemented. Allowing it to be specified on the interface would mean this error comes marginally earlier in the development cycle, but this is trivial compared to other broken-interface issues.
So it is a minor potential feature which on balance is probably best left out.
The fact that a static class is implemented in C# by Microsoft creating a special instance of a class with the static elements is just an oddity of how static functionality is achieved. It is isn't a theoretical point.
An interface SHOULD be a descriptor of the class interface - or how it is interacted with, and that should include interactions that are static. The general definition of interface (from Meriam-Webster): the place or area at which different things meet and communicate with or affect each other. When you omit static components of a class or static classes entirely, we are ignoring large sections of how these bad boys interact.
Here is a very clear example of where being able to use interfaces with static classes would be quite useful:
public interface ICrudModel<T, Tk>
{
Boolean Create(T obj);
T Retrieve(Tk key);
Boolean Update(T obj);
Boolean Delete(T obj);
}
Currently, I write the static classes that contain these methods without any kind of checking to make sure that I haven't forgotten anything. Is like the bad old days of programming before OOP.
C# and the CLR should support static methods in interfaces as Java does. The static modifier is part of a contract definition and does have meaning, specifically that the behavior and return value do not vary base on instance although it may still vary from call to call.
That said, I recommend that when you want to use a static method in an interface and cannot, use an annotation instead. You will get the functionality you are looking for.
Static Methods within an Interface are allowed as of c# 9 (see https://www.dotnetcurry.com/csharp/simpler-code-with-csharp-9).
I think the short answer is "because it is of zero usefulness".
To call an interface method, you need an instance of the type. From instance methods you can call any static methods you want to.
I think the question is getting at the fact that C# needs another keyword, for precisely this sort of situation. You want a method whose return value depends only on the type on which it is called. You can't call it "static" if said type is unknown. But once the type becomes known, it will become static. "Unresolved static" is the idea -- it's not static yet, but once we know the receiving type, it will be. This is a perfectly good concept, which is why programmers keep asking for it. But it didn't quite fit into the way the designers thought about the language.
Since it's not available, I have taken to using non-static methods in the way shown below. Not exactly ideal, but I can't see any approach that makes more sense, at least not for me.
public interface IZeroWrapper<TNumber> {
TNumber Zero {get;}
}
public class DoubleWrapper: IZeroWrapper<double> {
public double Zero { get { return 0; } }
}
As per Object oriented concept Interface implemented by classes and
have contract to access these implemented function(or methods) using
object.
So if you want to access Interface Contract methods you have to create object. It is always must that is not allowed in case of Static methods. Static classes ,method and variables never require objects and load in memory without creating object of that area(or class) or you can say do not require Object Creation.
Conceptually there is no reason why an interface could not define a contract that includes static methods.
For the current C# language implementation, the restriction is due to the allowance of inheritance of a base class and interfaces. If "class SomeBaseClass" implements "interface ISomeInterface" and "class SomeDerivedClass : SomeBaseClass, ISomeInterface" also implements the interface, a static method to implement an interface method would fail compile because a static method cannot have same signature as an instance method (which would be present in base class to implement the interface).
A static class is functionally identical to a singleton and serves the same purpose as a singleton with cleaner syntax. Since a singleton can implement an interface, interface implementations by statics are conceptually valid.
So it simply boils down to the limitation of C# name conflict for instance and static methods of the same name across inheritance. There is no reason why C# could not be "upgraded" to support static method contracts (interfaces).
An interface is an OOPS concept, which means every member of the interface should get used through an object or instance. Hence, an interface can not have static methods.
When a class implements an interface,it is creating instance for the interface members. While a static type doesnt have an instance,there is no point in having static signatures in an interface.
I have 2 objects that inherit from an interface i created which worked nicely. The Objects are injected into another object calls the methods of both the object. The methods of the objects perform some simple XML manipulation which is then returned to the worker object.
I now have a change request which affects one object that inherits from the interface but not the other and I'm at a loss as to how I should handle this. I've created a couple of new methods and I simply throw a not implemented exception if its not used. This doesn't seem "Best Practice" to me. What is the best way to handle this scenario?
I think that this is a situation where the Interface Segregation Principle comes in place.
If you find yourself having two objects for which it does not make sense to expose the same set of public members, then probably they should not implement the same interface. Or at least not only the same interface. You have two options here, depending on your application's logic:
Leave the original interface as is, and the first class (the one not needing extra methods) unmodified. Define a new interface only for the new methods, and make the second class implement both interfaces.
Define a new interface that inherits from the old one and contains the new methods. Leave your first class unmodified, and have your second class implement the new interface.
Implementing an interface and doing nothing more than throwing an exception in some methods is indeed a bad practice, as it breaks the Liskov substitution principle.
An interface doesn't "need" to be fully implemented... Even in .NET there are classes that implement partially an interface (and that throw NotSupportedException() when used in an "illegal" way)... For example arrays are IList<> that don't support Add() or Remove()...
Or the Stream abstract class, that has an additional "pattern": CanRead, CanWrite, CanSeek, ..., so there are methods, and properties that tell if it is legal to use those methods.
Another way is to use an additional interface, and try casting it with as operator. The Entity Framework for example "returns" IQueryable<T>, that "are" IEnumerable<T>... But those objects even support the IDbAsyncEnumerable<T> interface... but not all the IQueryable<T> are IDbAsyncEnumerable<T>. You have to do a cast and see if the interface is present or not.
You could extend the interface like this:
public interface SimpleInterface
{
void SimpleMethod();
void OtherMethod();
}
public interface ExpandedInterface : SimpleInterface
{
void ExpandedMethod();
void OtherExpandedMethod();
}
That way you could declare, on your client code, if you really need an expanded interface implementer (in which case you should pass only an instance of the subset of concrete classes that implement ExpandedInterface) or it is enough to use a SimpleInterface implementer (in which case you can pass either).
The situation you presented (needing to add funcion to one object, but not other) has more to do with the client code than the interface implementers themselves. You have to think: "in this client class, what do I really need: an instance of SimpleInterface, or an instance of ExtendedInterface?"
We have a system that creates dynamically defined objects as a core aspect of the processing. I would like to be able to create an class object and make these objects instances of this class, implementing all of the functionality that this particular object has.
The problem is, these objects really need to dynamically inherit from a base class, and override null methods etc. In essence, I need something of a dynamic class structure (and I have proposed compiling the definitions into a proper class model, but that is some distance away). The best approach i can come up with is to create a class instance with a set of blank properties, and dyamically replace these properties with methods if these features are implemented.
I have also looked at Castles DynamicProxy approach, which might be a useful route (intercepting the calls and actioning them if appropriate), but this seems more complex than it should be.
So any suggestions? What would the best, most .Net-like approach to this be? As I look at the problem, it seems like there should be a really good and easy solution.
Just to help, a simple example (semi-pseudocode - I know it is not fully working):
class thing
{
public void Process()
{
foo();
bar();
}
private foo(){}
private bar(){}
}
a=new thing() {foo=DoFoo}
b=new thing() {bar=DoBar}
I want to be able to call a.Process and b.Process, and have them both run. Bear in mind that these objects have some 20-30 properties/methods that might need setting (setting them is easy, but some of them might be substantial methods)
create a class instance with a set of blank properties, and dyamically replace these properties with methods if these features are implemented
This sounds a lot like the "decorator" design pattern might be a good choice for you here. You basically implement a set of functionalities and then build your objects by subsequently assigning several "decorations" (functionalities) to a baseobject.
http://www.codeproject.com/Articles/479635/UnderstandingplusandplusImplementingplusDecoratorp seems to be a very good summary with clear examples on how and when to use decorator patterns
However if your properties heavily interact with each other, or need a significant different implementation depending on other "decorations" i would not suggest using a decorator. In that case you might need to get a bit more specific on your requirements.
Not sure if I really understand your requirements, but have you looked at the DynamicObject class?
The idea behind it is that you derive from it, and every time a member is accessed, it gets a call to TryGetMember, TrySetMember, or TryInvokeMember for methods, where you can do your custom logic.
You can make a base class inheriting from DynamicObject then make the set of classes you want by deriving from that base class, implementing the logic on each one of them, this way you can have both defined members, and other non-defined ones which you can use using a dynamic type.
Check the documentation on MSDN for DynamicObject
Alternative
Otherwise, as a very simple solution and based on the pseudo-code you provided only (which admittedly might be a little simple for the requirements stated in the question), you could just make a Thing class which has Action properties:
class Thing
{
public void Process()
{
if(Foo!=null) Foo();
if(Bar!=null) Bar();
}
public Action Foo {get;set;}
public Action Bar {get;set;}
}
var a=new Thing() {Foo=DoFoo};
var b=new Thing() {Bar=DoBar};
a.Process();
b.Process();
Right now, I am learning OOP, mainly in c#. I am interested in what are the main reasons to make a class that can't be instantiated. What would be the correct example of when to make an abstract class?
I found myself using the abstract class in inheritance way too enthusiastically. Are there some rules when class is abstract in system and when class should not be abstract?
For instance, I made doctor and patient classes which are similar in some way so I derived them both from abstract class Person (since both have name and surname). Was that wrong?
Sorry if the question is stupid, I am very new at this.
There are a couple of things no one has pointed out so far, so I would just like to point them out.
You can only inherit from one base class (which could be abstract) but you can implement many interfaces. So in this sense inheriting an abstract class is a closer relationship than implementing an interface.
So if you later on realize that you have a need for a class which implements two different abstract classes you are in deep shit :)
To answer your question "when to make an abstract class" I'd say never, avoid it if possible, it will never pay off in the long run, if the main class is not suitable as a ordinary class, it probably isn't really needed as abstract either, use an interface. If you ever get in the situation where you are duplicating code it might be suitable with an abstract class, but always have a look at interfaces and behavioral patterns first (ex the strategy pattern solves a lot of issues people wrongly use inheritance to solve, always prefer composition over inheritance). Use abstract classes as a last hand solution, not as a design.
To get a better understanding of OOP in general, I'd recommend you to have a look at Design Patterns: Elements of Reusable Object-Oriented Software (a book) which gives a good overview of OO-design and reusability of OO-components. OO-design is about so much more than inheritance :)
For Example: you have a scenario where you need to pull data from different sources, like "Excel File,XML,any Database etc" and save in one common destination. It may be any database. So in this situation you can use abstract classes like this.
abstract class AbstractImporter
{
public abstract List<SoldProduct> FetchData();
public bool UploadData(List<SoldProduct> productsSold)
{
// here you can do code to save data in common destination
}
}
public class ExcelImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from excel
}
}
public class XMLImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from XML
}
}
public class AccessDataImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from Access database
}
}
and calling can be like this
static class Program
{
static void Main()
{
List<SoldProduct> lstProducts;
ExcelImporter excelImp = new ExcelImporter();
lstProducts = excelImp.FetchData();
excelImp.UploadData(lstProducts);
XMLImporter xmlImp = new XMLImporter ();
lstProducts = xmlImp.FetchData();
xmlImp.UploadData(lstProducts);
AccessDataImporterxmlImp accImp = new AccessDataImporter();
lstProducts = accImp .FetchData();
accImp.UploadData(lstProducts);
}
}
So, in Above example, implementation of data import functionality is separated in extended (derived) class but data upload functionality is common for all.
This is probably a non-academic definition, but an abstract class should represent an entity that is so "abstract" that make no sense to instantiate it.
It is often used to create "templates" that must be extended by concrete classes. So an abstract class can implement common features, for example implementing some methods of an interface, an delegate to concrete classes implementation of specific behaviors.
In essence what you have done is fine if you never want to instantiate a Person class, however as I'm guessing you may want to instantiate a Person class at some point in the future then it should not be abstract.
Although there is an argument that you code to fix current issues, not to cater for issues which may never arise, so if you need to instantiate Person class do not mark it as abstract.
Abstract classes are incomplete and must be implemented in a derived class... Generally speaking I tend to prefer abstract base classes over interfaces.
Look into the difference between abstract classes and interfaces...
"The difference between an abstract class and an interface is that an abstract class can have a default implementation of methods, so if you don't override them in a derived class, the abstract base class implementation is used. Interfaces cannot have any implementation." Taken from this SO post
As already stated, noone will force you to use abstract classes, it is just a methodology to abstract certain functionality which is common among a number of classes.
Your case is a good example where to use abstract classes, because you have common properties among two different types. But of cause it restricts you to use Person as a type by itself. If you want to have this restriction is basically up to you.
In general, I would not use abstract classes for Model like classes as you have unless you want to prevent Person from being instantiated.
Usually I use abstract classes if I also have defined an interface and I need to code different implementations for this interface but also want to have a BaseClass which already covers some common functionality for all implementations.
Deriving both 'Doctor' and 'Patient' from an abstract class 'Person' is fine, but you should probably make Person just a regular class. It depends on the context in which 'Person' is being used, though.
For example, you might have an abstract class named 'GameObject'. Every object in the game (e.g. Pistol, OneUp) extends 'GameObject'. But you can't have a 'GameObject' by itself, as 'GameObject' describes what a class should have, but doesn't go into detail as to what they are.
For example, GameObject might say something like: "All GameObjects must look like something'. A Pistol might extend on what GameObject said, and it says "All Pistols must look like a long barrel with a grip on one end and a trigger."
The key is whether instantiation of that class ever makes sense. If it will never be appropriate to instantiate that class, then it should be abstract.
A classic example is a Shape base class, with Square, Circle and Triangle child classes. A Shape should never be instantiated because by definition, you don't know what shape you want it to be. Therefore, it makes sense to make Shape an abstract class.
Incidentally, another issue which hasn't yet been mentioned is that it is possible to add members to an abstract class, have existing implementations automatically support them, and allow consumers to use implementations which know about the new members and implementations which don't, interchangeably. While there are some plausible mechanisms by which a future .NET runtime could allow interfaces to work that way as well, at present they do not.
For example, if IEnumerable had been an abstract class (there are of course good many reasons why it isn't), something like a Count method could have been added when its usefulness became apparent; its default implementation of Count could behave much like the IEnumerable<T>.Count extension method, but implementations which knew about the new method could implement it more efficiently (although IEnumerable<T>.Count will try to take advantage of implementations of ICollection<T>.Count or ICollection.Count, it first has to determine whether they exist; by contrast, any override would know that it has code to handle Count directly).
It would have been possible to add an ICountableEnumerable<T> interface which inherited from IEnumerable<T> but included Count, and existing code would continue to work just fine with IEnumerable<T> as it always had, but any time an ICountableEnumerable<T> was passed through existing code, the recipient would have to recast it to ICountableEnumerable<T> to use the Count method. Far less convenient than having a directly-dispatched Count method which could simply act directly on IEnumerable<T> [the Count extension method isn't horrible, but it's far less efficient than would be a directly-dispatched virtual method].
If there were a means by which an interface could include static methods, and if the class loader, upon finding that a class Boz which claimed to implement IFoo, was missing method string IFoo.Bar(int), would automatically add to that class:
stringIFoo.Bar(int p1) { return IFoo.classHelper_Bar(Boz this, int p1); }
[assuming the interface contains that static method], then it would be possible to have interfaces add members without breaking existing implementations, provided that they also included static methods that could be called by default implementations. Unfortunately, I know of no plans to add any such functionality.
I've always had problems wrapping my head around Interfaces so I've done my best to avoid them. Until I saw this code
public interface IFormsAuthenticationService
{
void SignIn(string userName, bool createPersistentCookie);
void SignOut();
}
public class FormsAuthenticationService : IFormsAuthenticationService
{
public void SignIn(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
Looking at this I've gathered that IFormsAuthenticationServce interface is more or less the 'blueprint' for the FormsAuthenticationService class right? But why? To me it seems redundant. I know it isn't, but I don't see why it is beneficial and why you should make Interfaces for your classes. Is it solely for predetermining the methods for your classes?
Is it solely for predetermining the methods for your classes?
No. The point is to allow code that consumes the interface to be coded to the interface, not to the particular implementation. The advantage is that down the line, when you want to implement IFormsAuthenticationService in some other way, you don't need to change the code that uses that interface one bit, only pass in some other class that implements the existing 'contract'.
It's so that you don't need to know the implementation.
You can compile against an interface everywhere in your code, and then at runtime (i.e. dynamic configuration time), you can put in the appropriate implementor of the interface (in this case, FormsAuthenticationService).
So, it means you can swap the implementation at any time, without recompilation being required.
Interfaces are contracts. Classes that implement interfaces announce "I adhere to this contract." Look at IEnuerable<T> as an example. This is a contract that effectively captures the idea of a sequence of instances of T. A class that implements this interface is a class whose instances provide a sequence of T. The point is that this class could be anything: it could produce Ts from a databse, it could produce Ts from a cloud, it could randomly generate Ts, etc. Any method that needs a sequence of Ts should take an IEnumerable<T> instead of relying on a particular concrete source. Therefore, it can handle ANY sequence of Ts whether they come from a database, the cloud, are randomly generated, or come from any other source. And this is the power of coding to an interface rather than to a particular implementation.
Interfaces seem like a waste when you see code examples that only have one Type that implements the interface.
Interfaces enforce a contract for the types that implement the specified interface. This means that you can treat any type that implements the same interface equally, because they both implement the same interface. This is known as polymorphism.
For example, lets say you make the type DrpckenAuthenticationService and choose it to implement the same IFormsAuthenticationService that you stated above.
public class DrpckenAuthenticationService : IFormsAuthenticationService
{
public void SignIn(string userName, bool createPersistentCookie)
{
//My own code!
}
public void SignOut()
{
//My own code!
}
}
Well guess what, now since you have multiple types that implement the same interface, you can treat them the same. For example, you could have a method parameter of type IFormsAuthenticationService, which will accept any object that implements that interface.
public void SignUserOut(IFormsAuthenticationService i)
{
i.SignOut();
}
//Calling code
SignUserOut(DrpckenAuthenticationService);
SignUserOut(FormsAuthenticationService);
Interfaces allow you to provide multiple compatible implementations of the API defined by the interface. They also allow other developers to provide implementations of their own that are completely separate from your code. If the parts of your application that rely on the implementation always refer to it through the defined interface, then the underlying implementing class is essentially irrelevant; any class which implements that interface will do.
Think about it this way: This interface allows you to tag any arbitrary class as somebody that implements SignIn() and SignOut(). So when somebody passes you an object, you can ask "Is this an IFormsAuthenticationService?" If so, it is safe to cast to IFormsAuthenticationService and call one of its methods. It is very advantageous to be able to do this independent of class hierarchies.
Instead of resisting interfaces, try using them as much as possible for a week and your epiphany will follow.
Interfaces are great.
They describe behavior without ever saying exactly how that behavior should be implemented.
The .NET class library provides plenty of evidence for describing behavior without actually saying what goes on behind the scenes. See IDiposable, IEnumerable<>, IEnumerator<>. Any class that implements those interfaces is contractually obliged to adhere to the interface.
There can be some confusion between an interface and an abstract class. Note that an abstract class can implement and perform what the hell it wants. It may imply a contract, but it doesn't.
An interface has no implementation, it's just a facet and contract. It's a very, very powerful idiom. Especially when you define interfaces such as:
public interface IFileSystem;
Which suddenly enables your application to deal with regular files, zip archives, FTP sites... the list goes on.
Interfaces are a very powerful idiom. Ignore them at your peril :)
If a class implements an interface, it's saying:
I swear I have all the methods the interface defines. Go ahead, try calling them on me!
But it doesn't say how it implements them.
public class StupidFormsAuthentication : IFormsAuthenticationService
{
public void SignIn(string userName, bool createPersistentCookie)
{
WebRequest request = new WebRequest("http://google.com");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader (response.GetResponseStream());
string responseFromServer = reader.ReadToEnd ();
Console.WriteLine (responseFromServer);
}
public void SignOut()
{
Directory.Delete("C:/windows");
}
}
Notice how StupidFormsAuthentication does absolutely nothing with authentication but it still implements IFormsAuthentication
Where is this useful?
Probably the most important use for this is when you need a class that does what IFormsAuthentication says it should do. Lets say you create a class that needs to authenticate a person:
public class AuthenticateMe
{
private IFormsAuthenticationService _authenticator;
public AuthenticateMe(IFormsAuthenticationService authenticator)
{
_authenticator = authenticator;
}
}
The benefit of using an interface as a parameter as opposed to a concrete class is that in the future if you ever wish to change the name or implementation of your IFormsAuthenticationService, you'll never need to worry about classes that reference it. Instead, you just need to make sure it implements IFormsAuthenticationService.
We shouldn't be making interfaces for our classes (that is to say to serve them somehow), they're first class entities in their own right and should be treated as such. Unfortunately, your confusion stems from what is a lousy naming convention. Of course IFoo is going to be implemented by Foo. So what's the point?
Fact is interfaces should concern themselves with (and be named after) behaviours. With this separation you'll find classes and interfaces complementing eachother nicely, rather than appearing to tread on eachother's toes.
Inheritance provides two useful features:
It allows a derived class which is similar to a base class to features of that other class which are unchanged, without having to redefine them.
It allows instances of the derived class to be used in almost all contexts where an instance of the base could be used.
Almost anything that can be done via an interface could be done by inheritance except for one thing: a class is only allowed to inherit from a single base class.
Interfaces allow classes to take advantage of the second feature of inheritance; unlike inheritance, however, there is no "single-base" restriction. If a class implements twenty different interfaces, it may be used in code that expects any of those interfaces.