Choose expression: proposal for a revolutionary C# construct

Notice that this post was published on April 1, 2009.

For decades, computer science students have been taught that so-called NP-hard problems do not have known efficient solutions. These problems include the infamous Travelling salesman problem, subset sum, 3SAT, and many more.

But – as is often the case – where theoretical Computer Science failed, sound software engineering practices will succeed. By using loosely-coupled OOP, agile methodologies and the model-view-controller architectural pattern, I developed a solution that someone trapped in the world of formulas and big Ohs would never dream of.

Enough with the background, and let’s take a deep dive into the intriguing design.

Read more

A neat way to express multi-clause if statements in C-based languages

I realized that there is a very clean way to express a multi-clause if statement by composing ternary conditional operators like this:

var result = 
    condition1 ? result1
    : condition2 ? result2
    : condition3 ? result4
          ...
    : conditionN ? resultN
    : default;

Read more

Fun with C# generics: down-casting to a generic type

Today, I am writing about a design problem related to C# generics that I’ve seen arise a few times. The problem occurs when we need to manipulate a generic class given a reference to its non-generic base class. For example, if a generic class Node<T> inherits from a non-generic class Node, and we are holding a Node reference to a Node<T> object, we cannot just cast the object to Node<T> because we do not have access to T.

I realize that the description is a bit abstract; let’s look at an example right away! It may look like a bit of code, but the classes are very simple and do just what you’d expect:

Read more