Why does the .NET framework rely on interfaces? [duplicate] - c#

This question already has answers here:
Why would I want to use Interfaces? [closed]
(19 answers)
Closed 8 years ago.
I am working on learning C# in depth. I am mostly confused by the frequent implementation of interfaces. I always read that this class implements this interface. For instance, SqlConnection class implements IDbConnection. What is the benefit for developers in this case?

the interfacing is based on object-oriented principles, e.g. see SOLID. You should not rely on implementation of other classes you're working with - it should be sufficient for you to know only what they do and what they should return. A good example with the SqlConnection would be that you may be able to change the DB you are using quite simply (to e.g. MySQL or Oracle) by changing the implementation on just one place, providing that your code is correctly using the interfaces and propagating the instances.

An interface contains definitions for a group of related functionalities that a given type must implement (a sort of Method Signature Contract). It does not, however, guarantee the specific behavior of those implementations.
Interfaces are particularily useful as they allow the programmer to include behavior from multiple sources in programming languages that do not support multiple inheritance of classes like C#.

Related

Can we replace Abstract Classes with Interface having Extension Methods? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
We are about to start a project right from scratch. As per the design discussions i am thinking to bring this topic.
Most of the times,I have seen that Abstract classes were being used just to provide some default/common behavior with some concrete methods.
So, i thought of defining those concrete methods as Extension methods for the Interface i am going to develop in place of Abstract classes.
Can someone guide me regarding my design decision. If you are not going to agree with my point please justify your argument with possible scenario/issues which we can face in case of doing so. So, that it will improve my knowledge.
Both approaches are very very different.
Using an abstract class and though abstract/virtual methods, you allow the derived classes to override a behavior which is not the case for extension method. Extension methods are extensions at the end of the day, they are not part of the type and are hard to spot when someone is examining the API and the features the type provides.
Second point, creating an extension method for a type that you create yourself is not that logical IMHO. Using a base Abstract class keeps your hierarchy clear and keeps your model open for modifications of overridden behaviors.
Extension methods were introduced in C# because a very particular requirement.
When they were designing LINQ they realized that they wouldn't want to create a new interface which would contain all known LINQ methods like Where or Select, because it would mean that any enumerable or collection implementation would need to implement it.
Above mentioned fact has an important drawback: it would need to extensively change the source code of a lot of classes from the Base Class Library and any third-party library or project implementing custom collections couldn't take advantage of LINQ at all.
Then they thought about an approach that could directly work with iterators (i.e. IEnumerator<T>) and that could be compatible with any IEnumerable<T> without having to modify any existing code but just adding new code to new assembly members.
And they invented extension methods, which would be implemented like static methods and they would act as instance members of a given type.
Since the inception of extension methods, they've been implemented in many other scenarios, but they always cover these two use cases:
I've a large code base and I want to offer a functionality to all types deriving (classes) or implementing (interfaces) some other type without having to modify them implementing a new interface across a lot of code (increasing the chance of introducing new bugs).
I don't own the source code of some project and I want to extend some types to support some new methods.
Anything outside these use cases is an abuse of extension methods.
Extension methods aren't a replacement to regular class-based object-oriented programming.
Basically you could extend every class or interface - nothing else is done with the Linq-extension methods.
However you can not define those methods directly in the interface, you allways need a static public class that contains those extensions.
To answer your questions I doubt that defining a default-behaviour within extension-methods is a good thing as it completely compromizes the actual intention of that interface. When creating an extension-method all instances of that (extented) class/interface share those methods, thus what you´re doing is to say every instance of my interface is able to be treated as my abstract class.
Having said this you should differ between the behaviour (the interface) and the actual processing (the class). Mixing both will eventually make your design quite complicated.
Next is by defining extension-mtehods you completely bypass inheritance. So what if you want to override the default-behaviour? You would be lost defining them as new or any different wewird workaround because your design was not open for inheritance at all.
Last point from my view is that you should use extension-methods for classes you don´t have control about. However when you can modify the code you´ll probably won´t use them.

Protocol vs Interface [duplicate]

This question already has answers here:
Differences between Java interfaces and Objective-C protocols?
(2 answers)
Closed 8 years ago.
I've been reading the swift documentation, and working through the playground. I have to admit I have zero knowledge of Objective-C/iOS development (outside of Xamarin at least). To my eyes, a protocol seemed identical to the C# interface.
However, I noticed whilst looking around on the web that Objective-C has a concept of both a protocol (source) and an interface (although I'm not really sure what the difference is). Swift doesn't seem to have both - just protocols.
Could someone explain, for swift, what the difference/relationship between a Protocol and a C# interface is?
Update: I appreciate that the answer might be functionally the same as the duplicates listed, but I think that, given that this is asking about a different language, that the question still has merit in it's own right. After all, new developers to swift might have no knowledge of Java (beyond Javascript, I have none). Placing an expectation on someone to have knowledge of a totally different language system in order to have the answer to their question is a bit much, isn't it!? This discussion on meta is also discussing this issue.
Objective C protocols serve basically the same purpose as interfaces in Java/ C#. Objective C interface files are different. Like C, Objective C has interface files that publicly declare the methods and properties of a class, that are then implemented in an implementation file. For example you may have an interface file of a class that looks something like this:
#interface
-(void)myMethod;
#end
then in your implementation file you actually implement the method:
-(void)myMethod{
//code
}
Swift does away with separate interface and implementation files. So it only has protocols.

preferred implementation style for factory pattern? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
what is your preferred implementation style for a factory pattern? For example, consider a website where I want to use a factory pattern to save to 2+ external systems. This is my first impression for a clean implementation:
Create a class named ExternalSystemManagerFactory
In the constructor of this class pass in an enumeration to indicate the target external system. For example: ExternalSystemManager.System1 or ExternalSystemManager.System2
Create a property on this class named ExternalSystemManager of type IExternalSystemManager
The constructor would set this property value based on the constructor argument
Create a method stub on IExternalSystemManager named SaveToExternalSystem
Create 2 concrete classes for my external systems that implement IExternalSystemManager (EsmSystem1, EsmSystem2)
Then in my client class, I could save to ExternalSystem1 like this:
new ExternalSystemManagerFactory(ExternalSystemManager.System1).ExternalSystemManager.SaveToExternalSystem();
Does this seem like a reasonable implementation? Do you see any potential issues with this implementation? Is this a fairly common implementation style or is there a general trend towards a different implementation style?
In my opinion when it comes to patterns, it typically has to do with how it "feels" when you use it. If you are comfortable with accessing your data in the way you have written it, then by all means go for it. I'm a firm believer that there really isn't a perfect way to implement a pattern and I actually avoid them unless my code blatantly has a need and they emerge naturally. So my advice is...Don't force it, but if it feel good, then do it.
The approach that you describe is ok, if it is only about two implementations. If the number of external systems that you want to access increases, you'd always have to change
the enum
the switch statement in the constructor that chooses the concrete implementation.
In the abstract factory pattern that the Gang of Four describes, you'd get rid of the enum and implement it like this:
An abstract base class/interface for the factory.
An implementation of the factory for each concrete external system.
You create the concrete factory at one spot in your code and always access it through the interface.
An advantage of this implementation is that you can easily configure which factory to create instead of using a switch statement in your code. Besides that you wouldn't have to adjust the switch statement each time you connect a new external system, it also allows you to create implementations for new systems without touching the assembly of the factory at all.
Another approach you might want to consider if you have lots of dependencies you want to create is to use an Inversion of Control Container. You register the types that should be created for an interface at the beginning of your application and ask the IOC container if you need an instance or inject it in the constructors of the classes. There are several IOC containers available, e.g. Microsoft Unity, Ninject, AutoFac, .... This will save you lots of time if you have several or huge factories.

implementing a custom cast for two types in c# [duplicate]

This question already has answers here:
C# adding implict conversions to existing types
(2 answers)
Closed 9 years ago.
I have two custom classes for which I want to implement casts between each other. I only have the DLLs of the two projects and not the code. Can I use extension methods to implement the cast or would I need to do something else?
I'd suggest that you implement your own mappers between the 2 classes or use mapping tools such as AutoMapper or ValueInjecter
You will have to use either extension methods or some other mapping. You could also use http://automapper.codeplex.com/
I don't think there is a way to do it. Anyway, do you really need the code to look like cast? Sometimes when you implement operators or casts for custom types the code may become harder to understand. I would suggest to create separate utility to convert types which would be more obvious for someone who sees the code for the first time.

Type Name aliasing in C# [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
typedef in C#?
STL like containter typedef shortcut?
I was wondering if there was an equivalent to Type aliasing from Functional Languages that I can use in C#
For example in a nice functional language like Haskell I can say something like the following to alias an existing type to a custom Type Name
type MyCustomTypeName = String
I'd like to do this as I have an API that I'm building where some of the Objects I'm using have multiple possible names in the sense they could be referred to by several terms which are interchangeable and equivalent. Presumably I could do this with inheritance but that seems somewhat clunky and then potentially breaks if people start extending the non-canonical class ie.
public class CanonicalClass {
//Full Implementation
}
public class AlternateName : CanonicalClass {
//Empty except I'll need to redefine all the constructors
//Could declare it sealed but doesn't get rid of the need to redefine constructors
}
And before anyone mentions interfaces all the Classes in question are all implementing interfaces already and there are multiple differing implementations of these interfaces.
Depending on what you're actually trying to do (give a somewhat more complete example), you may indeed need interfaces (used properly) and/or generics.

Categories