Category: .Net

Solving the Towers of Hanoi puzzle in C#

4 August, 2009 (18:45) | .Net, Programming, C#, Computer Science

I thought this would be a fun little exercise to try. This puzzle is generally used to teach recursion in CS classes, but I have never actually tried to implement it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TowersOfHanoiCs
{
class Program
{
static List […]

Simple speach example in C#.

12 May, 2008 (15:57) | .Net, Snippets

This uses reflection to avoid the clerical task of adding a project reference:

System.Type t = System.Type.GetTypeFromProgID(”SAPI.SpVoice”);
object o = System.Activator.CreateInstance(t);
t.InvokeMember(”Speak”, System.Reflection.BindingFlags.InvokeMethod, null, o, new object[] { “test”, 0 });

If you don’t mind adding a reference, then the whole thing can be done in one line:

new SpeechLib.SpVoice().Speak(”This is a test”, SpeechLib.SpeechVoiceSpeakFlags.SVSFDefault);

The difference between Java’s “final” and C#’s “const”

15 February, 2008 (20:01) | .Net, Java, C#, Computer Science

Final in Java is used to declare a class that can’t be subclassed, a method that can’t be overridden, or …
A final variable means the value won’t change, but the value can still be determined at run time:

final int i;
if ( j > 0 ){
i =1;
} else {
i = […]

Does string interning in C# guarentee you only get one copy of a static value?

19 September, 2007 (22:15) | .Net, C#, Computer Science

Of course the answer is no, otherwise it wouldn’t be a very interesting post. The concept of interning is an attempt to save memory by allocating static values which match exactly to the same memory location, without regard to where they’re used in the application. But here’s in instance where it doesn’t quite […]

Get the Unix Epoch time in one line of C#

3 January, 2007 (11:52) | .Net, Snippets

int epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;

An alternate (possibly faster) method might be:
long time = (DateTime.UtcNow.Ticks - 621355968000000000) / 10000000;
Although the second method does conform to the Unmaintainable Code standard, I’d recommend sticking with the first method unless you really need those extra nanoseconds.

MD5 in one line of C# code.

2 October, 2006 (23:20) | Cryptography, .Net, Security, Snippets

Considering the popularity of using MD5 to hash passwords in a database, I’m litterally baffled as to why Microsoft didn’t include a System.Security.Cryptography.MD5() function. This isn’t quite as nice as that would be, but it gets the job done:
string hash = Convert.ToBase64String(new System.Security.Cryptography.MD5CryptoServiceProvider().
ComputeHash(System.Text.Encoding.Default.GetBytes(SomeString)));

Pretty much every other example I’ve seen are at […]