Here’s a super quick little powershell snippet to strip regions out of all C# files in a directory tree. Useful for legacy code where people hide long blocks in regions rather than encapsulate it into smaller methods/objects.

dir -recurse -filter *.cs $src | foreach ($_) {
    $file = $_.fullname
    echo $file
    (get-content $file) | where {$_ -notmatch "^.*\#(end)?region.*$" } | out-file $file
}

Run this in your solution folder and support the movement against C# regions!

August 12th, 2010 | 5 Comments

Every now and then I need to write tests that depend on the ID of a persistent object. IDs are usually private and read-only, assigned internally by your ORM, so I use a little fluent extension method to help set them via reflection.

public static class ObjectExtensions
{
    // Helper to set private ID
    public static T WithId<T>(this T obj, object id)
    {
        typeof(T)
            .GetField("id", BindingFlags.Instance | BindingFlags.NonPublic)
            .SetValue(obj, id);

        return obj;
    }
}

Tweak as desired to suit your naming conventions or base classes. Usage is as follows:

[TestFixture]
public class When_comparing_two_foos
{
    [Test]
    public void Should_not_be_the_same_if_they_have_different_ids()
    {
        var a = new Foo().WithId(4);
        var b = new Foo().WithId(42);

        a.Should().Not.Be.EqualTo(b);
    }
}
October 7th, 2009 | No Comments Yet

One of the new features of C# 3.0 is the var keyword, which can be used to implicitly declare a variable’s type. For example, instead of declaring the type, you can just write var instead, and the compiler will figure out what type name should be from the value assigned to it:

// A variable explicitly declared as a certain type.
string name = "Richard";

// A variable implicitly declared as the type being assigned to it.
var name = "Richard";

Note that a var isn’t a variant, so it’s quite different from say, a var in javascript. C# vars are strongly typed, so you can’t re-assign them with values of different types:

var name = "Richard"
name = 62; // error, can't assign an int to a string

Vars were introduced to support the use of anonymous types, which don’t have type names. For example:

var me = { Name: "Richard", Age: 22 };

But there’s nothing to stop you from using vars with regular types. In a recent article on codinghorror.com, Jeff Atwood recommends using vars “whenever and wherever it makes [your] code more concise”. Guessing from his examples, this means everywhere you possibly can.

The logic behind this is that it improves your code by eliminating the redundancy of having to write type names twice — once for the variable declaration, and again for a constructor.

There’s always a tradeoff between verbosity and conciseness, but I have an awfully hard time defending the unnecessarily verbose way objects were typically declared in C# and Java.

BufferedReader br = new BufferedReader (new FileReader(name));

Who came up with this stuff?

Is there really any doubt what type of the variable br is? Does it help anyone, ever, to require another BufferedReader on the front of that line? This has bothered me for years, but it was an itch I just couldn’t scratch. Until now.

I don’t think he’s right on this one — my initial reaction is that using var everywhere demonstrates laziness by the programmer. And I don’t mean the good sort of laziness which works smarter, not harder, but the bad sort, which can’t be bothered writing proper variable declarations.

Jeff is right though – writing the type name twice does seem a little excessive. However, as Nicholas Paldino notes, the correct way to eliminate this redundancy would be to make the type name on the right hand-side optional, not the left:

While I agree with you that redundancy is not a good thing, the better way to solve this issue would have been to do something like the following:

MyObject m = new();

Or if you are passing parameters:

Person p = new("FirstName", "LastName");

Where in the creation of a new object, the compiler infers the type from the left-hand side, and not the right.

Microsoft’s C# language reference page for var also warns about the consequences of using var everywhere.

Overuse of var can make source code less readable for others. It is recommended to use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types.

In the following example, the balance variable could now theoretically contain an Int32, Int64, Single (float), Double, Decimal, or even a ‘Balance’ object instance, depending on how the GetBalance() method works.

var balance = account.GetBalance();

This is rather confusing. Plus, unless you explicitly down cast, vars are always the concrete type being constructed. Let’s go back to Jeff’s BufferedReader example, of which he asks, “is there really any doubt what type of the variable br is?”

BufferedReader br = new BufferedReader (new FileReader(name));

Actually, yes there is, because polymorphism is used quite extensively in .NET’s IO libraries. The fact that br is being implemented with a BufferedReader is most likely irrelevant. All we need is something that satisfies a Reader base class contract. So br might actually look like this:

Reader br = new BufferedReader (new FileReader(name));

Just because a language allows you to do something, doesn’t mean it’s a good idea to do so. Sometimes new features adapt well to solving problems they weren’t designed for, but this is not one of those situations. Stick to using vars for what they were designed for!

June 21st, 2008 | 42 Comments