Convert.To is the Devil
Sometimes I find myself doing things that I know I just shouldn’t. One of those things is using the Convert.To Methods in C#; such as :
Convert.ToInt32("A"); Convert.ToDateTime("123456");
The reason these are a bad idea should be obvious, if it isn’t then let me explain. Converting the string “A” to an Int32 just isn’t going to work correctly, more than likely, you will end up with a thrown exception. If that doesn’t happen then you will get 65, but should “A” be 65? Is that the intent of the person that input that value into your application? The point is the data isn’t stable and the rest of your program shouldn’t rely on unstable data. Below is an alternative and I think much better solution
public static class Parse { public static T To<T>(object value) { try { return (T)Convert.ChangeType(value, typeof(T)); } catch { return default(T); } } }
Above you can see that I am still using a Convert method but this one will work to convert any base type to any base type that I tell it to. Another benefit is that I can catch the error from a bad convert and log it to whatever logging mechanisms I have defined. The last benefit is I can provide a default value in case of an exception. This prevents my program from crashing and allows me to fail gracefully. Should I choose I could pass a value by reference and populate some kind of error to detect a bad value which I could then display to the user and allow them to modify their input.
*EDIT*
I have extended my Parse class to include a static extension method that allows for a default value in case of an invalid conversion.
public static T To<T>(this object value, T defaultValue) { try { return (T)Convert.ChangeType(value, typeof(T)); } catch { return defaultValue; } }
The usage for the above is fairly straight forward, here is an example
Console.WriteLine("A".To<int>(-1));
which will print -1 to the console since “A” doesn’t convert to an int in this scenario.
Making and Using an Anonymous Method in C#
There are times when a piece of code is repeated enough to warrant extracting a method but the content of the code isn’t important enough to create a separate method from the current one. In situations like this I tend to use C#’s anonymous methods just to make the code look a bit cleaner and save me from having to type the same thing over and over. It also saves some of the accidental errors from copy paste coding. Below is a simple example of a situation where this may start to be desired.
public void FirstFivePowers(int number) { int a, b, c, d, e = 0; switch (number) { case 1: a = 1; b = 2; c = 3; d = 4; e = 5; Console.WriteLine("The Powers of {0} are {1},{2},{3},{4},{5}", a, b, c, d, e); break; case 2: a = 2; b = 4; c = 8; d = 16; e = 32; Console.WriteLine("The Powers of {0} are {1},{2},{3},{4},{5}", a, b, c, d, e); break; case 3: a = 3; b = 9; c = 27; d = 81; e = 243; Console.WriteLine("The Powers of {0} are {1},{2},{3},{4},{5}", a, b, c, d, e); break; case 4: a = 4; b = 16; c = 64; d = 256; e = 1024; Console.WriteLine("The Powers of {0} are {1},{2},{3},{4},{5}", a, b, c, d, e); break; case 5: a = 5; b = 25; c = 125; d = 625; e = 3125; Console.WriteLine("The Powers of {0} are {1},{2},{3},{4},{5}", a, b, c, d, e); break; default: Console.WriteLine("Input not valid for this function"); break; } }
As you can see the Console.Writeline is copied several times and it is starting to become annoying to copy or retype each time I add to this switch statement. This is solved in the code below by using an anonymous method.
public void FirstFivePowers(int number) { Action<int, int, int, int, int> WritePowers = (a, b, c, d, e) => { Console.WriteLine("The Powers of {0} are {1},{2},{3},{4},{5}", a, b, c, d, e); }; switch (number) { case 1: WritePowers(1, 2, 3, 4, 5); break; case 2: WritePowers(2, 4, 8, 16, 32); break; case 3: WritePowers(3, 9, 27, 81, 243); break; case 4: WritePowers(4, 16, 64, 256, 1024); break; case 5: WritePowers(5, 25, 125, 625, 3125); break; default: Console.WriteLine("Input not valid for this function"); break; } }
Now this could be solved several ways, but for demonstration purposes I used the anonymous method.
NLog Exceptions
In the event that NLog is not working and you don’t know why, just add the following to your <nlog/> tag:
throwExceptions="true" internalLogFile="c:\nlogErrors.txt"
After you run something that should be logged if it didn’t work you will see the exception in the file you named.
Singleton Base Class For Making Easy Singletons
I was watching the latest videos on www.Tekpub.com and Jon Skeet made a singleton in an intersting way that I had not seen before. I have taken his code and kinda ran with it. I don’t like having to remember all the tricks to get something complicated to work so I usually find a way to hide it from myself using Inheritance or Generics. In this case I did both. Here is my SingletonBase class
public class SingletonBase<T> { private static class SingletonHolder<T1> { internal static readonly T1 instance = (T1)typeof(T1) .GetConstructors(BindingFlags.Instance | BindingFlags.CreateInstance | BindingFlags.NonPublic) .SingleOrDefault() .Invoke(null); // Empty static constructor - forces laziness static SingletonHolder() { } } public static T Instance { get { return SingletonHolder<T>.instance; } } }
And here is how you would implement it in a Singleton of your choosing:
public class TestableSingleton : SingletonBase<TestableSingleton> { private TestableSingleton() { } public int Counter { get; set; } public void DoSomething() { Counter++; } }
Nothing to it.
Converting WSDL to C# from the Visual Studio Console
The Easiest way is to open the visual studio console and change the path to the path containing the WSDL that you want to convert. Then execute the following command replacing the file names with the appropriate ones.
wsdl /l:C# /out:OutputFileName.cs InputFileName.wsdl
WHAT IS YOUR FAVORITE INANIMATE OBJECT?
Why you @tumblrbot of course!
» Asked by tumblrbot