Posts

Showing posts with the label Conversion

C# convert string array to integer (or something other kind of data type) array

Many times in coding you are dealing with transforming data from one type to another.  I often find myself creating integers, longs, etc from strings.  Especially in .net for some reason.  I got tired of writing tons of code to handle this.  .Net gives you a great way to convert an array from one type to another. Currently I would always end up writing a for loop iterating through the array and doing a manual copy.  It would look something like this: string[] someStringValues; int[] someIntValues = new int[someStringValues.Length]; for( int i = 0; i < someStringValues.Length; i++ ) {    someIntValues[i] = int.Parse( someIntValues[i] ); } Not horrible code, but there is a more succinct way of doing it! string[] someStringValues; int[] someIntValues = Array.ConvertAll<string, int>( someStringValues, int.Parse ); We have now moved all that code into 1 line.  With some more magic we can also move this into a generic templated solu...

Convert string to base64 string

A while back I came across the need to convert regular string text into a base64 string. .Net makes this fairly easy to do. I created a public static class and added two public static methods to encode/decode strings. Now they don't have to be static or public but I tend to make helper/utility classes that way. All of the classes being used are in the System and System.Text namespaces. /// <summary> /// Encodes the string to Base64. /// </summary> /// <param name="valueToEndcode">The value to endcode.</param> /// <returns>A base64 encoded string.</returns> public static string EncodeStringToBase64( string valueToEndcode ) { // encode the string into ascii byte array byte[] toEncodeAsBytes = ASCIIEncoding.ASCII.GetBytes( valueToEndcode ); // use the byte array to encode to a base64 string string returnValue = Convert.ToBase64String( toEncodeAsBytes ); // drop back the new encoded string value return returnValue; } /...

C# convert HTML/System.Drawing.Color

Many times I find myself having to use an HTML color that isn't defined in the System.Drawing.Color section of the framework. .Net gives you an easy way to get around this. Use the ColorTranslator.FromHtml static method in the System.Drawing namespace. System.Drawing.Color c = System.Drawing.ColorTranslator.FromHtml("#F5F7F8"); String strHtmlColor = System.Drawing.ColorTranslator.ToHtml(c);