C# var keyword

I’m working my way through the C# 3.0 Language Enhancements videos on LearnVisualStudio.Net.  (Note:  LearnVisualStudio has many videos that are available for free from the MSDN website, but I think that you need a paid subscription to view this series.)  When I’m studying new programming concepts, I find that hearing someone talk about it helps me get it into my head in a way that reading alone doesn’t do.  I really want to learn LINQ, but it turns out that you don’t just jump into it.  Rather, you need to learn some key building blocks first.  So, today I studied the C# var keyword.

Var is just a shortcut you can use to create a variable without actually figuring out what type it is.  Instead, the compiler figures out the type for you, based on what you are assigning the variable to.

For example:

var a = 3;

is equivalent to

int a = 3;

When would you want to use var?  Infrequently, if you subscribe to the “keep your code as obvious as possible” theory.

One possible use is when you are instantiating an object using “new”.  You could argue that typing:

var b = new List<string>();

is as clear and less verbose than:

List<string> b = new List<string>();

But the real use is when you are using LINQ and it’s pretty unclear – and maybe you don’t even care  – what the actual type is.  For instance, do you know what type is returned by the following LINQ query?

string[] names = { “Turtle”,”Toad”,”Frog”,”Lizard” };
var cc = from n in names where n.StartsWith(“T”) select n;

I thought cc would be of type string[], but it is actually:


Right.  Var is looking pretty good right now, isn’t it?

The object.GetType method is useful to find out what type you actually have.  For instance:

int a = 3;
if(a.GetType() == typeof(int))
    // whatever

There you have it.  The next video in the series is “Object and Collection Initializers”.  That doesn’t sound too glamorous, but we’ll see.



C# “as” and “is” keywords

“Is” is exactly what I have been looking for.  You use it to check the type of an object.  For example:

if(a is long)

Gabe Wishnie points out that “is” is much more efficient than:

if( a.GetType() == typeof(long))

“As” is a method of performing a typecast that gives you a null pointer rather than throwing an error if the object is the wrong type.

string a = b as string


.Net BackgroundWorker class

The BackgroundWorker class is an easy way to start up a thread from the GUI to run some lengthy action in the background.  Key points are:

  • The DoWork event runs on the background thread.  You can’t interact with the GUI from there.  The ProgessChanged and RunWorkerCompleted events are raised by the background thread into the GUI thread, so that you can interact with the GUI.
  • In the DoWork event, the MSDN example tells you:
    // Do not access the form’s BackgroundWorker reference directly.
    // Instead, use the reference provided by the sender parameter.
    BackgroundWorker bw = (BackgroundWorker)sender;

    Is that just because you might use the same event for multiple threads, or is there some other reason?

  • You can run multiple background threads.
  • Question:  What is the best way to debug possible problems with the background threads?  We can use SystInternals ProcMon to see when the thread was started and exited.  We can write to event logs.  What else?

NUnit and Visual Studio

Like all my “What I learned” experiences, this may not sound like much to you, but it was interesting to me.

I attended a PhillyDotNet hands on lab session tonight  presented by Brian Donahue.  The lab was an avalance of Model View Presenter, Domain Driven Development, and unit testing techniques, with software tools such as Resharper, NUnit, and Rhino Mocks thrown in for good measure.  It was a lot to comprehend, but I managed to stumble along a few steps behind throughout. 

Here are some of the tidbits I learned:

  • You don’t have to have NUnit or Rhino installed on your computer.  The dlls were included with the sample project Brian handed out at the beginning.  Having those, I could reference them in my code, although I could not actually run the NUnit tests.  But the code compiled.
  • It was pretty easy to convert the NUnit tests over to the built-in Visual Studio unit tester – add the right reference and change [TextFixture], [Test], and [Setup] attirbutes to [TestClass], [TestMethod], and [TestInitialize()].  These are the only features of NUnit I knew to start with, and the VS tester seems to be pretty equivalent to use.
  • What I did not figure out was how to convert an NUnit testing project into a VS test project.  I mean, what properties or attributes designated it as a test project?  I ended up having to copy the .cs files from the NUnit test to the VS test project.  My questions here are:  What “type” of project was the original test project as created by Brian, and what designated the test project as something that VS recognized?

There you have it.

Using regular expressions to find the text between two delimiters

I have a string like this:  “This is a [abcd] string”.  I want to find the text between the square brackets.  Looks like a job for regular expressions!

This regular expression works:  “\[.*\]“.  Very straightforward (for a regular expression) – I like it!

Then I saw this regular expression in some question and answer forum:  “\[([^\}]+)\]“.  It works, but seems unclear.  Is that something clever or a bad piece of advice?  If I understand it correctly, it is saying:  Find the text contained in the square brackets UNLESS it contains a “}” character.  Huh?  I’m chalking it down to bad advice.

One caveat is that if I have the string “This is my [abcd][efgh] string”, I get the string within the outer brackets, that is: “[abcd][efgh]”, when I really would want “[abcd]”.  I have a feeling that this is a problem I will have to solve … but not today!

Social Bookmarking

I finally joined the social bookmarking scene.  What I want is to be able to access my bookmarks from any computer.

Digg – I hated it!  Digg has lots of flash and “hip” verbage on the website – it’s atrocious.  At a glance, I’m not interested in any of the articles others are submitting.  The emphasis is heavy on SOCIAL.  They want me to submit my site, comment on it, discuss it – bleh.  I don’t want to talk to other people, I just want a place to store my bookmarks.  I want to be in a quiet library, not Times Square.  Plus, to register my account, I had to enter age, gender, location – some heavy-handed tracking going on there.

Del.icio.us, by contrast, is quiet and serene.  Minimal information is required to register.  It installs an inoffensive toolbar with simple buttons.  It’s easy to store bookmarks, easy to view them.  It’s a winner.  My only complaint – the hard to type url.

Getting a list of SQL Server databases on the network

I found this pretty easily with an Internet search.  Copying it here so I can be sure to find it next time I want it.

 Courtesy of Dan Dittenhafer

private static List EnumSqlServers()
System.Data.DataTable sqlInstances = System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources();
List listSqlServers = new List();// Loop to load the unique server names
foreach (System.Data.DataColumn col in sqlInstances.Columns)
if (col.ColumnName == “ServerName”)
foreach (System.Data.DataRow row in sqlInstances.Rows)
if (!listSqlServers.Contains(row[col].ToString()))


Adding icons to Windows Forms

I added an icon to a Windows Form, but it didn’t display.  Why not?  Because even though Visual Studio by default creates a 32x32x16 icon, you really need a 32x32x256 icon.  Right-click on the icon editor screen to select the desired format.  Thanks Jason Black.


The Traveller’s Gift by Andy Andrews

The Traveller’s Gift is a set of 7 homilies setting life goals that will help you succeed.  The messages are things like “the buck stops here”, “seek wisdom”, “I am a person of action”, etc.  These are great goals and definately worth having impressed in your mind.  The book is easy to read, the ideas are relevant, and the religious undertones aren’t too pushy.  I enjoyed the book and would recommend it to others.

I am a little bemused by the genre, which I’ll call “inspirational management books for men.”  The formula is:  Manager is failing to lead the company out of trouble.  He doesn’t have the resources to protect his family.  He has a mystical encounter with strong leaders and learns The True Message.  He applies what he has learned to become a great leader and the pride of his family.  

Do men have such intense needs to look strong in front of others and feel like good family providers?  It’s sure not something women talk about, at least not the ones I know, at least not in that way.  Maybe I shouldn’t be surprised, but I am.

Vista, and Getting Things Done

I accomplished several useful things over the weekend.  Funny how sometimes these “to do” tasks build up and finally something happens to break the dam and I knock them off in short amount of time.


Somewhat related, The Brazen Careerist has a recent article called “Get good at finding the true barriers to getting what you want”.  She loved her yoga class, but didn’t go for a long time because she had a toenail infection and didn’t want anyone to see her feet.  Finally she forced herself to go and found that no one cared about her feet anyway.  Now that the barrier was broken, she felt happy to attend the class again.  It’s a gross story (the author has a way of doing that!) but a great point.


For me, the dam-breaker was PhillyDotNet.  Hearing Bill Wolfe calling out the development trends in his big, booming voice made me think “What am I waiting for, anyway?”  So in the course of the weekend, I:


– Upgraded my PC from 1GB to 2GB RAM. 

– Purchased an external USB hard drive (Western Digital Passport, 232 GB). 

– Moved my music library off my work PC to the hard drive.  I had a bunch of CDs that I was waiting to Rip until I got the external drive, so now I am going through them and adding some much-needed new music to my library.  New old music, because these are old CDs that I haven’t been listening to.

– Upgraded my home PC to Vista!  It worked great.  I give HP a great deal of credit for this – they had a very clear set of directions and a couple of utilties to walk me through this painlessly.  I have an HP Pavilion dv8000 laptop, and I have been very happy with it.  It is a well-designed machine.  I give Microsoft a lot of credit, too – Vista has been much maligned, but they clearly put much effort into keeping the operating system backward compatible while still moving forward, no easy feat.

– Moved my website Favorites list from the desktop to Windows Live Favorites.    That way I can easily visit all my favorite sites from any PC.  I checked out Google Toolbar to do the same thing, but you have to have Google Toolbar installed on the PC.  I’m trying to move away from installing things on my PC.  Also, the Google Toolbar looks cartoonish and kind of ugly, particularly on fancy Vista.  Did Microsoft intentionally choose a default color scheme that would clash with Google?

– Installed Virtual PC.  Created a Virtual Machine running XP.

– Over time, I am trying to move as much of my PC baggage to “the cloud” as I can.  I’m also trying to organize my files better.  “Search” seems to be the trend for finding files anymore, but I think it still pays off to have them in a logical location in the first place.


What will be next?  I need to get some Antivirus software on the PC ASAP, and then back to building my website!