?? Operator

If you use nullable types in C# (e.g., int?, double?, boolean?, etc.) you may be interested to know that C# has a special operator for handling what to do if a value is null. It is called the null-coalescing operator. It works like this . . .

int? x = null;
int y = x ?? -1;

If x is null, then the value on the right side of the ?? will be used; otherwise, it will use the value of x to assign to y in the example above.

So, you don’t need to do things like this anymore . . .

int y = (x == null) ? x : -1;

Neat huh?

Conflicting Assemblies

In Visual Studio, when compiling solutions, you may encounter the following error message:

Found conflicts between different versions of the same dependent assembly. Please set the “AutoGenerateBindingRedirects” property to true in the project file. For more information, see http://go.microsoft.com/fwlink/?LinkId=294190.

Or you might see a similar version of this when trying to browse to an ASP.NET website that looks like:

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

To see exactly the path and the assemblies that are causing the problem, you’ll need to turn on logging for the .NET binding process. The information above in the error message is not sufficient to enable this though. Here’s the full information needed in order to see the assembly binding (from Stackoverflow):

DWORD ForceLog set value to 1
DWORD LogFailures set value to 1
DWORD LogResourceBinds set value to 1
String LogPath set value to folder for logs (e.g. C:\FusionLog\)

Make sure you have that trailing backslash in the log path.

Then, restart your application or build and inspect the details in the log file or the output from ASP.Net!

Defaults in C# 4.0 Method Parameters

C# 4.0 was released in April 11, 2010. By that point, C# was 8 years old and there were A LOT of developers out there that knew C# already and didn’t pay much attention to the changes and didn’t incorporate them into their current code. Many were able to keep chugging along happily doing what they had been doing without having to learn about the new features.

That’s too bad.

One of my favorite, 4.0 additions is named-arguments and optional-parameters. I think they are my favorites because of my stint as a Visual Basic programmer during my time between PowerBuilder and C#. You got used to not supplying parameters if you didn’t care to pass them or didn’t need them.

You can easily tell when a developer doesn’t know about this feature too. They tend to have a lot of overloading of a method that essentially hides parameters. And, they make calls to variants of the methods when they want to have defaults and not supply them. Or, they don’t want to have to supply them everywhere.

Their code will look something like this:

public void Broadcast(string group, int unitId) { . . . }

public void Broadcast(string group) { Broadcast(group, 5); }

public void Broadcast() { Broadcast(“Red Leader”); }

From above, you can see that the first method takes two parameters. If this were the only method, you’d have to supply defaults everywhere. So, in the event that you just want to pass the group and always default to 5 in the unitId when you do, you could just call the second routine. Or, if you want to default both parameters, you could call the third variation, which calls the second, which then calls the first. That’s a lot of pushing and popping on the stack just to have defaults.

After C# 4.0, these three methods can be collapsed into just this one method by simply using defaults. Here’s what it looks like

public class Broadcaster
    public static void Broadcast(string group = "Red Leader",
       int unitId = 5) { Console.WriteLine("This is {0} {1}", group, unitId); } } class Program { static void Main(string[] args) { Broadcaster.Broadcast(); Broadcaster.Broadcast(group: "Blue Leader"); Broadcaster.Broadcast(unitId: 2); } }

So, if you just wanted to supply a different unitId, you simply pass in a unitId: 6 in the method call. The group would default, and the effect is as if you called the method with the parameters “Red Leader” and 5.

Defaults make these sorts of libraries much leaner to write.

I hope this helps you.

The Map Man Says GOTO is Evil

In the days before the C# language became popular, many people coded in BASIC.

BASIC has a rather controversial statement in the family of jump statements called GOTO. The GOTO statement lets you move the flow of control to any point in the source code that you desire. It was usually used within the THEN or ELSE clause of an IF statement. But, if you had numerous nested-IFs it could be difficult—if not impossible—to look at the source code and have any idea what it was going to do. So, you had to be careful how you wrote your code. You still do.

At the time, there was some debate on the use of this statement with respect to the maintainability of source code. And, it was much frowned upon in many circles to the point where one would be judged badly for using it.

Well, this morning, as I sifted through the changes in the C# Language Specification 5.0, I came across the goto statement. I smiled and thought to myself, “They haven’t killed you yet?” I kind of like the GOTO statement. It lets you do what you want to do; however you like . . . make up your own rules . . . you can be a rebel if you like (kind of like commas, semi-colons, em-dashes and ellipses in grammar),

Then I remembered this essay, “A Case against the GO TO Statement,”   by Edsger W. Dijkstra, the creator of the algorithm for finding the shortest path from a to b in a directed graph; or in layman’s terms, the initial ancestor of the algorithm that Google maps or your GPS receiver uses when it plots how to get from your house to the grocery store within the shortest amount of time or distance—kind of a hard thing to do.

Having studied and used some of his algorithms in college, he certainly had and still has my respect. And, if you’ve ever used a GPS, he should have yours as well. He kind of knows what he’s doing wouldn’t you say?

Back in school when I came up on the essay, I gave it strong consideration when he said:

The go to statement as it stands is just too primitive, it is too much an invitation to make a mess of one’s program.

With the exception of using, say, JMPs in assembly language (the equivalent of a GOTO in BASIC), I have tried to avoid using them as much as I can for the very same reason he states above.

But, I am happy that you can still GOTO in C#. So, if you feel like being a bit of a rebel . . . GOTO for it! Just don’t over do it . . . the Map Man might come looking for you (and he knows the quickest way to get to your house!)

XPath in LINQ

To use XPath in LINQ, add a reference to System.Xml.XPath. This will make the System.Xml.XPath.Extensions come into scope. Then, you can use the XPathEvaluate() method.

ASP.NET MVC4 with Bootstrap 2.3.2

If you want to get Twitter Bootstrap 2.3.2 up and running with ASP.NET MVC4, there is a wonderful set of projects on NuGet for that. However, it’s not straight forward to get it installed. There are issues that have not been resolved due to the author’s time constraints (admittedly by him) in keeping up the NuGet project. Still, if you want to get an MVC4 Bootstrap 2.3.0 app going, this is a pretty good place to start inspite of the problems.

I have struggled to get it up and going and have noticed in my search for answers that others have as well. I have finally converged upon a sequence of steps that get it going. I’ve not found these all in one place, so, I’ve decided to document my approach here. I hope it works for you . . .

  1. In Visual Studio, create a new, empty MVC 4 application.
  2. Open the Library Package Manager console window and load the two Twitter Bootstrap MVC 4 and Sample packages
    1. “Tools | Library Package Manager | Package Manager Console”
    2. At the PM> prompt, type
         install-package twitter.bootstrap.mvc4 -Version 1.0.90
      and press [Enter] and wait for it to install.
    3. At the PM> prompt, type
         install-package twitter.bootstrap.mvc4.sample -Version 1.0.90
      and press [Enter] and wait for it to install
    4. Later versions have bugs that have not been fixed. 1.0.90 is a stable version
  3. Paths in the BootstrapBundleConfig are wrong and need to be fixed. Change it to something like this . . .

    bundles.Add(new StyleBundle(“~/content/css”).Include(

  4. The Bootstrap files need to be updated (the ones that come down in NuGet aren’t right). You’ll need to install it manually in your project.
    1. Get bootstrap 2.3.2 from here . . . click the big blue “Download Bootstrap” button.
    2. Open the download file, extract it and copy the css and js files over the existing ones in the \Content and \Scripts folders . . . watch out for the paths
  5. In the _BootstrapLayout.basic.cshtml, change the lines
            <link href=”@Styles.Url(“~/content/css”)” rel=”stylesheet”/>

OR . . .

you can just download this project with all of the above and start from there.

Patterns of Parallel Programming

I read this answer today on Stack Overflow:


to a question on parallel programming and getting as much work done as possible. The answer referenced this, very well written document from Microsoft:


In it, they describe the fundamental problems encountered in parallel programming, how they are solved and why they are solved the way they suggest. Really good, useful read.

Stephen Toub has some good books. Here’s one

var in C# . . . why?

Here is the link to Microsoft’s discussion of the var keyword in C#.

At first reading of this, it appears to be a simple way of not having to explicitly think about the types of your objects. However, it’s a little more involved than that. It’s useful for when you deal with anonymous types. What’s an anonymous type?

Here’s the link to Microsoft’s discussion of anonymous types.

Anonymous types are class types that derive directly from object, and that cannot be cast to any type exceptobject. The compiler provides a name for each anonymous type, although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type.

Here’s some code I created to play around with LINQ in the context of anonymous types . . .


        static void Main(string[] args)
            // The Three Parts of a LINQ Query: 
            //  1. Data source. 
            //int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
            var stuff = new[] {new { Number = 0, Fruit = "Apple", Birthday = new DateTime(1968, 5, 31) }, 
                             new { Number = 2, Fruit = "Orange", Birthday = new DateTime(1971, 6, 3) }};

            // 2. Query creation. 
            // stuffQuery is an IEnumerable<?> 
            var stuffQuery =
                from item in stuff
                select new { item.Number };

            // 3. Query execution. 
            foreach (var thing in stuffQuery)
                Console.WriteLine("thing: {0} ", thing.Number);
Posted in C#