I need simple example to use ISerializable,IEnumerable,IList with Generics efficiently.
Also wish to know what are all the other Interfaces we can use along with Generics.
Update :
The task i need to perform is using these interfaces
I have to serialize the custom Types
Collect them in Generic object
Iterate them to find the match
This question is very broad.
Note that the interfaces you've listed are not all about the same thing.
ISerializable is not generic, and deals with serialization of objects to streams or similar.
IEnumerable is about being able to enumerating over a collection or something that produces a stream of elements.
IList is an interface that is typically implemented by such a collection.
It would help us helping you if you could narrow down your question somewhat. As your question stands now, it's more like "I need to know everything there is to know about cars".
As for "all other interfaces that can be used with generics", have you looked at the MSDN Documentation for the .NET framework classes?
I have a feeling that this question is a homework question...but I'll bite with a little information.
Generics != Interfaces. Basically you can use any interface that you want with Generics, it is one of the more powerful parts of generics, by using interfaces that you create, you can then define generic methods that process multiple concrete implementations by limiting the generic type to objects that implement a specific interface.
Related
This question already has answers here:
Default Interface Methods. What is deep meaningful difference now, between abstract class and interface?
(6 answers)
Closed 4 years ago.
It seems to me like the C# 8.0 feature, default interface member implementation, essentially allows one to create implementations at the interface level. Pairing that with the fact that a class can implement multiple interfaces, it seems eerily close to a multiple inheritance structure for classes. As far as I understand, this seems to be quite opposite to the core of the design of the language.
Where does this discrepancy stem from and what room does this leave for actual abstract classes to occupy?
This question has been suggested as an answer to mine and while it is useful, it doesn't exactly answer my question. To be more precise:
I always assumed that single inheritance is one of the core principles of C#'s design, which is why the decision to implement this feature is surprising to me, and I would be interested to know where it stems from (C#-specifically).
The linked question does not answer what room it leaves for abstract classes.
I always assumed that single inheritance is one of the core principles of C#'s design
This is just not accurate. Single inheritance is a means to design goal, but not a goal in itself.
It's like saying the automatic transmission is a core design principle for car makers, when the actual goal is making the car easier and safer. And looking the car market, manual transmissions still thrive in both the low end (because they're cheaper) and the high end (performance sports cars) of the market, where they are good fit for purpose. Many models in those areas can still be had with either type of transmission.
The actual design goal in C# leading to single inheritance is more about safety and correctness with regards to memory access and overload resolution. Multiple inheritance is difficult to verify mathematically for these things compared to single inheritance. But as they find elegant solutions, C# designers have added a number of features that stretch the bounds of single inheritance. Beyond interfaces, we have partial classes, generics (and later co/contravariance), and delegate members that all trend this direction.
In this case, the default implementation is effective in safely providing a weak multiple inheritance because the inherited functionality doesn't cascade down the inheritance tree from two directions. You can't create a conflict by inheriting two different classes with differing interface implementations; you are limited to either your own class implementation, the default implementation, or the single implementation available via inheritance.
Note that default interface implementation does not allow for multiple inheritance, at least not in the sense that was a problem for C++. The reason multiple inheritance is a problem in C++ is that when a class inherits from multiple classes that have methods with equal signatures, it can become ambiguous as to which implementation is desired. With default interface implementation, that ambiguity is impossible because the class itself does not implement the method. An object must be cast to the interface in order to call the implemented methods. So multiple methods with the same signature may be called on the same instance, but you must explicitly tell the compiler which method you are executing.
The linked post answers your first question to a good extent.
As for:
The linked question does not answer what room it leaves for abstract
classes.
While it may read and sound similar interface default method implementation certainly does not replace abstract classes nor does it make them redundant, the very big reason being:
an interface cannot define class level fields/variables whereas an abstract class can have state.
There are some other differences although not as big as the aforementioned, which you can find in various blogs/posts:
https://dotnetcoretutorials.com/2018/03/25/proposed-default-interface-methods-in-c-8/
https://www.infoq.com/articles/default-interface-methods-cs8
etc.
I am trying to understand generics in a semantic way. For instance, abstract classes seemed to snap into place for me when I read people refer to them as structures that can set policy. Interfaces snapped when I read people refer to them as collaboration contracts.
What are some good ways to think about generics that might help me to differentiate them from other OO structures and write more intelligent APIs?
Think of generic classes as stencils to make other classes (similarly, generic functions are stencils for making other functions). Type parameters serve as openings in your stencils: by plugging in a concrete type into them, you make the generic class or the generic function into a real class or function. The type parameters "stick through" the designated holes in the stencil, producing a complete definition.
It seems you want to approach your understanding from a top-down perspective. "What is it" in a qualitative sense and then derive the real meaning from there. Isn't it easier to simply learn what these different constructs do rather than trying to come up with labels? i.e. approach it from a bottom-up perspective and infer your own qualitative descriptions from what you've now already understood firsthand.
Abstract classes require you to implement a property or method and can't be instantiated. What distinguishes it from an interface? It requires subclasses to choose yours as its only base class. Interfaces face no such restriction but require you to define its entire behavior in the implementation, rather than relying on some of the behavior to be defined in the base class.
Similarly, generics allow you to introduce types as variables that can be specified by the caller. The utility of this is analogous to method parameters in general, just taken to a higher level. In other words, method parameters allow you to vary the implementation based on some input specified by the caller. Generic parameters allow you to vary the implementation based on some (other) input (i.e. types) specified by the caller.
Surely it's clear why List<T> is more useful than ArrayList. I'm not really sure why metaphors are really helpful for understanding why.
You could view them as wrappers around object types. You are creating functions that will do something for whatever type of object it is instantiated for, so it's like a template that will perform the same work for multiple types of objects.
Microsoft's introduction to generics might have some good descriptions as well
http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx
While I think I understand why inline XML documentation (i.e. using three slashes - ///) isn't working for me, I'd like to get some guidance on how to work around my "problem".
I have an interface, and two derived classes. One derived class is for simulation, and the other is for talking to real hardware.
It's very likely that the hardware implementation would do something special that the simulator doesn't need to do. I have XML documentation for the hardware methods, and not for the simulator. However, when I hover over the method name, I don't get documentation in the tooltip at all, presumably because the XML docs aren't associated with the interface.
This certainly makes sense, and I plan to just put my documentation in the interface instead and live with it. I am still curious, though... how does everyone else do this? Is there some magical way to make the tooltip aggregate all of the valid XML docs? In other words, since the compiler doesn't know which derived class is being used, is there a way for it to show XML docs for all classes that implement this interface?
This won't solve all your problems but GhostDoc can quickly insert documentation into a derived class using the base class documentation. It's worth taking a look anyway if you're doing XML documentation.
Since you are programming to an interface, there is not a way to pass through the XML documentation from the implementation. The separation means that the two "sides" don't know about each other. Like you said, you could have two different implementations of that interface. In that case, you would have a conflict. That isn't a big deal for two, but what about 200? Besides, the point of using an interface is that you don't care how it is implemented. You know that when you call use an interface, the implementation will follow the contract. Use the XML comments on the interface to describe the contract, not the implementation of the contract.
I can feel your pain on this one and I'm not sure that there is a better solution.
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Interfaces: Why cant I seem to grasp them?
What is the purpose of interfaces in C#?
How would they enable extendable,modular design in c#,Java?
As far as my experience with the interfaces is concerned ,we used in a gridview scenario where columns values are brought from disparate objects.
(e.g:
List<IPub> list = new List<IPub>();
gridview.DataSource = list;
gridview.DataBind();
IPub has 4 methods which is implemented by 4 or 5 disparate classes.
)
What are the cases they come in handy compared to their class counterparts,apart from above?
I heard Java creator despised of interfaces or saying like "If i were a given a chance to design java again;I would never make interfaces into the language".
Does this applies to C# as well?
What implications made him to say that ?
I am feeling like i never understood interfaces completely.
Please somebody take pains to explain.
EDIT: Here is the Goslings quote, see the Java section
Interfaces can be considered as "can-do", whilst abstract/base classes can be considered as "is-a".
So a dog is-a animal, so you'd used a base class.
A dog can-do a poo, so poo would be a method on an interface which other animals might implement.. (crap example)
Reading my OO book the other day it posited that concrete instances should be avoided and good OO coders always program to an interface or base-class.
With that in mind it might be worth picking up a copy of a good OO / patterns book, such as head first design patterns
you should see the answers here or here or here or here
An interface provides a way to use something without having to worry about how that thing is implemented.
If you have an interface ITextGetter with a method GetText(string textKey) which you are using, you don't know if where the text comes from, all you know is that when you ask for the text with a particular key, you get the text. If you write you app using this interface then you can use different classes which all implement the interface to get the text without having to change your app. This makes it easy to switch from file based text getting to database based or webservice based text getting without having to change any of the code that uses the interface
Interfaces are a sort of contract: if some class implements some interface, then that class guarantees to have certain methods. You could have the same when you inherit from some baseclass, but you can't always do that. In that case an interface is handy to implement a sort of multiple inheritance.
Interfaces are there so that you don't need to specify a whole lot of functional code about something. You just need to know what it does. It's kinda like if you need to hire a family car.
You need to know
A) its a car that drives and
B) it has a family sized boot.
You don't need to know about how the car works, how the engine works. You just need to do know it can do A) and B). That's the purpose of an interface.
Within C# we don't allow multiple inheritance, (i.e. having more than 1 base class), so if you want to define the behaviour of more than 1 interface you can't do it with classes. If multiple inheritance existed there would be the option of using multiple base classes to do this.
Well, back when java was being developed there was a thing called "Multiple inheritance" where classes could be derived from two (or more) different classes.
So for example, you had a "Vehicle" class and a "Animal" class you could have a "Horse" class that derived from both.
The problem was, what if you wanted to derive a class from two classes that had a function name in common? You couldn't really, there would be two underlying implementations of the function.
So for example the Vehicle and Animal classes might have a "move()" function. Well, if you don't override that yourself, then what happens when you call horse.move()? It's undefined! Either one could get called!
So, in Java, you can only derive from one class. But what if you really need a class that is compatible with more then one type? Like if you have, for example a database connection that needs to derive a base class to work with the DB but also needs to be able to be managed like a resource with a close() function.
Okay, so they created 'Interfaces'. When you implement an interface, you don't have to worry about competing code underneath because you have to implement them yourself.
It's generally agreed that multiple inheritance is a "considered harmful" (like GOTO), and interfaces are a way of getting the benefits without the downsides. But, nowadays there are other ways to do that. Such as "DuckTyping" where as long as classes implement the feature name, they are good to go.
Also, java now can do nested classes, so if you need your class to be derived from two classes, you can make an inner class that derives from the second class.
Different methods have their pluses and minuses, but interfaces are not the only want to get around the problems of multiple inheritance today.
Interfaces give you a way to effectively have some sort of multiple inheritance (you can't inherit from more than one abstract base class). If you ask yourself the question why would you prohibit multiple class inheritance, just read relevant chapter from one of Bjarne Stroustroup's books (on C++), where you will how overcomplicated it gets.
On the other note, when you are using unit testing, pretty much every interface you create will have at least 2 implementations - the real one and a mocked one for the tests.
I'm implementing an AVL binary tree data structure in C# .NET 2.0 (possibly moving to 3.5). I've got it to the point where it is passing my initial unit tests without needing to implement any framework level interfaces.
But now, just looking through the FCL I see a whole bunch of interfaces, both non-generic and generic that I could implement to ensure my class plays nicely with language features and other data structures.
At the moment the only obvious choice (to me at least) is one of the Enumeration style interfaces to allow a caller to use the tree in a foreach loop and possibly with Linq later on. But which one (or more)?
Here are the interfaces I'm considering at present:
IEnumerable and IEnumerable<T>
IEnumerator and IEnumerator<T>
IComparable and IComparable<T>
IComparer and IComparer<T>
ICollection and ICollection<T>
IEquatable and IEquatable<T>
IEqualityComparer and IEqualityComparer<T>
ICloneable
IConvertible
Are there any published guidelines, either online or in book form, that provide recommendations regarding which framework interfaces to implement and when?
Obviously for some interfaces, if you don't want to provide that functionality, just don't implement the entire interface. But it appears there are certain conventions in the FCL classes (such as Collection classes) that perhaps we should also follow when building custom data structures.
Ideally the recommendations would provide guidance on such questions as when to use IComparer or IEqualityComparer, IEnumerable or IEnumerator? Or, if you implement a generic interface, should you also implement the non-geneic interface? etc..
Alternatively, if you have guidance to offer based on your own experiences, that would be equally useful.
You should be aware that some of those interfaces inherit from each other (ICollection<T> and IEnumberable<T>) and the generic versions of interfaces generally require the implententation their non-generic versions. IEnumerator and IEnumerable are connected (an IEnumerable traditionally creates an IEnumerator to do the enumeration)
Implementing IComparable<T> is on a collection is fraught with danger (are you comparing the members in the collection?), and IComparer<T> is a helper interface for sorting methods.
ICloneable is a bit outdated - but it's meant to enable creating a deep copy (which, again, is fraught with danger for a collection.
I'd take issue with your
Obviously for some interfaces, if you don't want to provide that functionality, just don't implement them.
If you implement an interface, you should implement all the members of it. (see Liskov Substitution Principle)
Implementing IConvertible for a collection also seems strange - you might perfer to implement ISerializable.
The MSDN Documentation for the interfaces is a bit terse, but you can always google them to see how they work.
The definite guide is Framework Design Guidelines.
It gives Do, Do Not and consider recommendations. A lot of it is also available in MSDN.
I don't think you'll find a one-size-fits-all answer to this, as the implementation of these interfaces depends on how you expect your class to be used.
All these interfaces are provided to allow use of a class from within the existing BCL or the language itself. So, as you say, IEnumerable allows use of the class in a foreach loop.
Implementing each of these depends on the way that your library might be used. For instance, ICloneable is directly appropriate to users of remoting and sometimes users of ORMs. If your class makes sense in that environment then you'll help your users by implementing it.
Put another way: who's going to use your class? What BCL framework methods would you expect them to use?
(Also, many of the generic interfaces themselves implement non-generic versions, e.g. IEnumerable implements IEnumerable, and IEnumerator implements IEnumerator.)
You just implement the ones that you want your class to have, i.e.
If you want to be able to enumerate items, then implement IEnumerable and IEnumerable<T> instead of inventing your own methods.
If you want to be able to deep-copy a tree, then implement ICloneable instead of inventing your own method.
If you want to be able to compare trees for value equality, then implement all the equality interfaces.
And so on. Other points:
Some interfaces should be implemented in a specific manner so as to avoid "surprising" behaviour in code that calls them. The equality interfaces in particular must be 100% consistent with each other and the System.Object virtual equality methods.
When there is a generic and non-generic version of the same interface, it is always useful to implement both.