I need a generic collection class which I can add to, and enumerate over. Since ICollection<T> inherits from IEnumerable<T>, the class really just needs to inherit from ICollection<T>. Is there a simple generic class in the BCL that just inherits ICollection<T> like a generic version of CollectionBase? If not, then what class comes closest?
I would guess List<T> which is what I've been using but i don't need to sequential aspect. Is there anything better (by which I mean [smaller memory footprint/faster access/simpler])? Bag would be perfect if it existed.
EDIT 1: In my particular instance, I'm .concating to another IEnumerable, querying it, and then displaying the results (in no particular order). I'm not attempting to make my own class. I've just needed to make a throwaway collection so many times, that I thought it would be useful to find the best throwaway to use. Because I feel I've done something similar so many times, I felt I should keep this question as generic as possible (no pun intended), I know better now.
EDIT 2: Thanks for everybody's answers, As #BlueRaja pointed out, any simple class is going to have about the same overhead, and thus I think I will be sticking with my original ways of using List<T>. Since they are all about the same, my silly reasons of "It's easier to type", and "I don't have to bring in yet another using" aren't such bad reasons.
[smaller memory footprint/faster access/simpler]
They are all going to have pretty much the same memory footprint, and if you use ICollection the interface will not change.
What really matters is which will scale best for the operations you need: Linked-list does better appending/removal (of head/tail elements), while an array-based list has random-access. There are other structures too - which you should use depends on your application.
You'll probably want to look into Collection<T>. It was designed for the express purpose of subclassing, as the documentation indicates:
Provides the base class for a generic collection.
Having said that, any of the collections are fine; I've inherited from List<T>, Stack<T> and so on; pick whichever one is closest to the functionality you actually need.
Smaller and faster all depends on what exactly you're doing and what your needs are. The only other class I might recommend is LinkedList<> which implements ICollection<>.
You could use Reflector to check the .NET FCL and see what classes use that collection. (There is a search feature that can be started by F3.)
You can also take a look at the C5 Library to see if a collection has already been implemented that meets your needs. Check out page 13 of the C5 Manual for the collection interface hierarchy.
CollectionBase existed primarily to provide a simple mechanism to create typed collections. With Generics, all collections are now typed. The vast majority of cases where extensions of CollectionBase used to be used should now be using any of the built-in collections such as List<> or LinkedList<>.
Collection<> still exists for those that need to provide a custom collection for reasons other than type (i.e., extra validation on add, or some non-standard logic). Collection<> is not nearly as commonly used as CollectionBase was and serves a much smaller need.
Related
A fellow OOP beginner here.
I just had to do an exercise, where i had to create a custom class in C#, and on the homework TODO's there was a requirement to implement the IENumerable and IENumerator interfaces, and create a custom Queue of my custom class type objects.
While i had no issues solving the problem, i still don't understand the usage of this. Instead of writing so much code to implement a custom Queue, why not simply use the already existing "Queue" from the C# Framework? Is there any performance/optimisation advantage from this ?
So, is there any gain in using MyCustomObjectQueue, instead of using Queue<'MyCustomObject'> ?
As mentioned in the comments, this is an excercise to familiarize you with the concepts. In the real world you would just about always use the existing queue implementation.
But the exercise is not pointless. Knowing how to implement IEnumerable is very valuable. IEnumerator is a bit less so, since you can use an iterator block to let the compiler do it for you.
The collections in the framework are made for generic usage, if you have some special usage patterns it can sometimes be useful to make your own variant, but this would be rather rare.
In my experience the most common cases for implementing a collection is to either wrap an existing collection to add some extra features, or implementing collections that are not provided, like a ringbuffer or heap.
I have some integrations (like Salesforce) that I would like to hide behind a product-agnostic wrapper (like a CrmService class instead of SalesforceService class).
It seems simple enough that I can just create a CrmService class and use the SalesforceService class as an implementation detail in the CrmService, however, there is one problem. The SalesforceService uses some exceptions and enums. It would be weird if my CrmService threw SalesforceExceptions or you were required to use Salesforce enums.
Any ideas how I can accomplish what I want cleanly?
EDIT: Currently for exceptions, I am catching the Salesforce one and throwing my own custom one. I'm not sure what I should do for the enums though. I guess I could map the Salesforce enums to my own provider-agnostic ones, but I'm looking for a general solution that might be cleaner than having to do this mapping. If that is my only option (to map them), then that is okay, just trying to get ideas.
The short answer is that you are on the right track, have a read through the Law of Demeter.
The fundamental notion is that a given object should assume as
little as possible about the structure or properties of anything else
(including its subcomponents), in accordance with the principle of
"information hiding".
The advantage of following the Law of Demeter is that the resulting
software tends to be more maintainable and adaptable. Since objects
are less dependent on the internal structure of other objects, object
containers can be changed without reworking their callers.
Although it may also result in having to write many wrapper
methods to propagate calls to components; in some cases, this can
add noticeable time and space overhead.
So you see you are following quite a good practise which I do generally follow myself, but it does take some effort.
And yes you will have to catch and throw your own exceptions and map enums, requests and responses, its a lot of upfront effort but if you ever have to change out Salesforce in a few years you will be regarded a hero.
As with all things software development, you need to way up the effort versus the benefit you will gain, if you think you are likely never to change out salesforce? then is it really needed? ... for you to decide.
To make use of good OOP practices, I would create a small interface ICrm with the basic members that all your CRM's have in common. This interface will include the typical methods like MakePayment(), GetPayments(), CheckOrder(), etc. Also create the Enums that you need like OrderStatus or ErrorType, for example.
Then create and implement your specific classes implementing the interface, e.g. class CrmSalesForce : ICrm. Here you can convert the specific details to this particular CRM (SalesForce in that case) to your common ICrm. Enums can be converted to string and the other way around if you have to (http://msdn.microsoft.com/en-us/library/kxydatf9(v=vs.110).aspx).
Then, as a last step, create your CrmService class and use in it Dependency Injection (http://msdn.microsoft.com/en-us/library/ff921152.aspx), that's it, pass a type of ICrm as a parameter in its constructor (or methods if you prefer to) . That way you keep your CrmService class quite cohesive and independent, so you create and use different Crm's without the need to change most of your code.
Lots of sources talks about this question but I dont understand the concept very well. IDictionary is generic, its type safety etc.
When I dig into EntityFrameworkv5 I see a property that is declared as below in the LogEntry class.
private IDictionary<string, object> extendedProperties;
The question is why they prefer IDictionary against Hashtable, hence Hashtable is also takes a key as a string and a object. Only the reason is making the property polymorphic by choosing IDictionary ?
Thanks in advance.
Nowadays, there are few reasons to use Hashtable. Dictionary<> is better than it in most respects. When it's not, you can usually find another strongly typed collection that serves your purpose even better than either.
Type-safe.
None of the severe overhead of boxing and unboxing.
Implements IDictionary<>, which is very compatible with .NET and 3rd party code.
Performs better than Hashtable in many areas. See links: Link #1, Link #2.
If you're asking why type a property as IDictionary<> instead of Dictionary<>, it's for several reasons.
It is generally considered best practice to use interfaces as often as possible, instead of regular types, especially in a framework.
It is possible to change the implementation of the interface fairly easily, but it's difficult to change the nature of a concrete class without causing compatibility problems with dependent code.
Using interfaces, you can take advantage of Covariance and Contravariance.
External code is more likely to consume the more general interface IDictionary<> than the concrete class Dictionary<>. Using IDictionary<> thus lets other developers to interact better with the property.
There are tons more, probably. These are just off the top of my head.
Well yes if they had defined extendedproperies as returning hashtable then they would have been stuck with that for all time, unless they wanted to break all the code that uses extended properties.
Whole point of the returning an Interface is it doesn't matter how the method is implemented as long as it keeps doing that.
"Only reason is making the property polymorphic" misses the point, there should be very few reasons why you shouldn't do this. If you can return an interface do return an interface, most of the time that's good design.
So most of the answers here are about comparing Dictionary to Hashtable for general purposes, not why they chose that particular implementation.
In that particular implementation, you are correct, it is using object as the return type, so the strongly typed benefits of dictionary are not available.
IMO it boils down to New vs Old, ArrayList, Hashtable etc are the older tech, and are largely disfavored in general, because they do not have a host of features (described in the other answers). Although those features are not used in this particular case, there are no strong benefits for switching back to the old tech, and it provides a better example for personal development.
So its more just a matter of "this is the way we do it now"
The HashTable is weakly typed and can only return Object. The Dictionary<> is strongly typed for whatever type you are storing in it.
I am currently populating my WPF grid using a data collection that implements ITypedList, with the contained entities implementing ICustomTypeDescriptor. All the properties are determined at runtime.
I'm wanting to implement HyperDescriptor to help speed up performance, but the example on that page more refers to known types rather than runtime properties.
I would think that I'd need to implement a custom GetProperties() method or similar to tell the HyperTypeDescriptor what properties it needs to look at, but am not sure where that should be set. I figure it's not difficult, but I'm obviously missing something.
Any tips much appreciated!
The HyperDescriptor implementation is indeed specific for compile-time properties, as it uses ILGenerator etc and caches the generated code. If you are using ICustomDescriptor you are already in a very different performance profile - for example, if your custom PropertyDescriptors work against a dictionary or hash-table as a property-bag they may already be significantly faster than raw reflection.
It may be possible to further optimise it, but I'd need to know more about the specific implementation. But it would be non-trivial work, so first satisfy yourself that this member-access is actually a bottleneck, and that you couldn't do something simple like paging or "virtual mode" first.
(clarification: I'm the author of HyperDescriptor, so I know this area well)
The advantage of using generics is that it increases the type safety - you can only put in the correct type of thing, and you get out the correct type without requiring a cast. The only reason I can think of for not using generic collections is that you need to store some arbitrary data. Am I missing something? What other reasons are there to not use generics when dealing with collections?
If you need to store arbitrary data, use List<object> (or whatever). Then it's absolutely clear that it's deliberately arbitrary.
Other than that, I wouldn't use the non-generic collections for anything. I have used IEnumerable and IList when I've been converting an object reference and didn't know the type to cast it to at compile-time - so non-generic interfaces are useful sometimes... but not the non-generic classes themselves.
The obvious other reason is working with code (possibly legacy) that does not use generic collections.
You can see this happening in .NET itself. System.Windows.Form.Control.Controls is not generic, nor is System.Web.UI.Control.Controls.
Generics are almost always the right thing to use. Note that languages like Haskell and ML essentially only allow that model: there is no default "object" or "void*" in those languages at all.
The only reasons I might not use generics are:
When the appropriate type is simply not known at compile time. Things like deserializing objects, or instantiating objects through reflection.
When the users that will be using my code aren't familiar with them (yet). Not all engineers are comfortable using them, especially in some more advanced patterns like the CRTP.
The main advantage is the is no boxing or unboxing penalty with generic collections of value types. This can be seen if you examine the il using ildasm.exe. The generic containers give better performance for value types and a smaller performance improvement for reference types.
Type variance with generics can trip you up, but mostly you should use generic collections. There isn't a really a good reason to avoid them, and all the reason in the world to avoid un-typed collections like ArrayList.
Here's one answer: The change from Hashtable to Dictionary.
One thing I think you need to consider is that a generic collection is not always a drop in replacement for a non-generic collection. For example, Dictionary<object,object> can not simply be plugged in for an instance of Hashtable. They have very different behavior in a number of scenarios that can and will break programs. Switching between these two collections forces a good programmer to examine the use cases to ensure the differences do not bite them.
The non-generic Collection in the Microsoft.VisualBasic namespace has some annoying quirks and goofiness, and is in a lot of ways pretty horrible, but it also has a unique feature: it is the only collection which exhibits sensible semantics if it's modified during an enumeration; code which does something like delete all members of a Collection which meet a certain predicate may need to be significantly rewritten if some other collection type is used.