Here is another useful one I came across a while ago, don’t remember what site but thanks to whoever wrote it. This Extension Method takes the String and converts it to the Enumeration Type that is specified.
In a recent project I needed the ability to take an incoming string value and calculate its SHA1 Hash in order to tell if the value had been altered in some way. Instead of creating a special utility class to accomplish this I figured a clean solution would be to just add an extension method to the String class. Here is what I came up with.
I notices while working with a 3rd party component that the built-in ArrayList object in .Net does not have a built-in ToList() method to convert it to a generic List like various other list objects.
I actually prefer using generic lists much more than the standard collections since they provide tons more functionality. Because of the all this I decided it was about time I add an extension method to my library for converting ArrayLists to a typed generic list.
From what I have learned on a recent project is that Windows machines calculate the current date starting on 1/1/0001 where as Linux machines are calculating their time off of what is called the “Start of Epoch” which turns our to be 1/1/1970. I guess we could call it an Epoch year with all the disco and bellbottom pants!
When using Time Stamps across operating system boundaries it is always a good idea to use UTC time (Universal Time) so that you don’t have to mess with time zones. But as I came to find out, that is not enough, you also have to calculate that time stamp from the same origin date.
Below is how you accomplish this in C#:
DateTime startOfEpoch = new DateTime(1970, 1, 1);long milliseconds = (long)(DateTime.UtcNow - startOfEpoch).TotalMilliseconds;
By default the ICloneable interface defines a Clone() method which returns an object of type Object and therefore is not a type safe action. To make your implementation of the ICloneable interface type safe for the following. By adding a typed Clone() method to your class and then adding an Explicit implementation of the ICloneable.Clone() interface method which returns the results of your Clone() method the returned object will be typed correctly.
Unfortunately the built in C# generic list does not have a Clone() method. If you need to clone a list for manipulation purposes you can always use an extension method and add a Clone() method yourself. Below is an Extension Method for Cloning a generic list in C#: