Working through endless “Wrestles” in CS290, I’ve come to find some common needs for many of my assignments. Because of this, I’ve started to create my own utility DLL (dynamic link library) of functions. I’ll be honest that not all of the ideas were my own, especially Jamie King’s P() method.
Extension Methods
For those who have not heard of or used extension methods, here’s a brief overview. Extension methods are simply static methods that are syntactic sugar. To create an extension method, create a static class and within it create a static method having this before your first argument.
public static class MyStaticClass
{
public static void MyExtensionMethod(this Object source)
{
}
}
After creating this, you can then use it by calling it on any instance that inherits from Object (anything) as instanceName.MyExtensionMethod(). It’s the same as calling, MyStaticClass.MyExtensionMethod(instanceName), just shorter to type and implicitly inserting the parameter, making it feel like a method of the object, rather than a static extension.
Asserter.cs
Assertion is an effective way of debugging your code. When “wrestling” with new concepts, its a great way to prove things without spewing out a bunch of console.writeline(). These extension methods give you simple Assert methods to call on any object.
using System;
using System.Diagnostics;
namespace StatenUtil
{
public static class Asserter
{
public static void AssertReferenceEquals(this Object source, Object target)
{
Debug.Assert(Debug.ReferenceEquals(source, target), "Source and target references not equal");
}
public static void AssertEquals(this Object source, Object target)
{
if (source == null)
{
Debug.Assert(target == null, "Source is null, target is not");
}
else
{
Debug.Assert(source.Equals(target), "Objects are not equal");
}
}
public static void AssertNull(this Object source)
{
Debug.Assert(source == null, "Object is not null");
}
}
}
PrintExtensions.cs
Another frequet debugging technique is to print out to the console. Adding the P() extension method can simplify the need to write Console.Writeline(). Also, added is the iteration of enumerable objects to eliminate the need to foreach over its members.
using System;
using System.Collections;
namespace StatenUtil
{
public static class PrintExtensions
{
public static void P(this Object source)
{
P(source, "{0}");
}
public static void P(this Object source, string formatString)
{
if (!(source is String) && source is IEnumerable)
{
Console.WriteLine(formatString, source);
foreach (object o in (IEnumerable)source)
o.P(" " + formatString);
return;
}
Console.WriteLine(formatString, source);
}
}
}
StatenUtil: The Future
In the future, I’ll continue to add additional features to this utility set and share them as the changes become significant. Check back often, as StatenUtil has plenty of life ahead of it. If you have comments or suggestions, please let me know.