.Net, Coding, ReSharper, Tips And Tricks, Visual Studio

Shortcut Key to Comment code in VS and SQL Server Management Studio

When we learn any programming language, one of the firsCtrl+Ct thing  we discover is the syntax how to comment our code.  Some of you probably already have been using this shortcut key for awhile.

Select multiple lines of code and press Ctrl+K,Ctrl+C, and you hard work is going to be ignored. To reverse just press Ctrl+K,Ctrl+U

These keystrokes will comment/uncomment your code only with line comment like // in C# or — in SQL.  I’m not aware how to comment code with block comment (/**/) without using a plug-in for VS.

One more thing.  If you need to comment/uncomment a single line, you don’t need to select the whole line.  Just move the cursor to any position on the line you want to comment, and let you fingers press the magic combination.

If you like me (there’s nothing wrong to be different from me) and use ReSharper, than you would like to use Ctrl+Alt+/ with line comment and Ctrl+Shift+/ with block comment.

kick it on DotNetKicks.com

.Net, C#, Coding, Nullable Types

How big is null in Nullable types?

I use often Nullable types in my code.  However, when today I was debugging my code I was surprised to learn that the expression bellow equals to false:

   1: int? n1 = null;
   2: int? n2 = null;
   3: if (n1 <= n2)
   4:     Console.WriteLine("not going to happen");

I decided to dig deeper to see what the reason for this behavior.

I learned that when you have a Nullable type variable that is null (int? n1 = null) in relation comparison expression, the expression is always false.  By relation comparison I mean binary comparison with one of following operators: <, >, <= , =>.

Let me try to explain why this happens.   Let assume that we have two Nullable integers n1 and n2.  n1 is null and n2 has value of 5.  When you compare (n1 < n2), behind the scene the following comparison happens:

    (n1.GetValueOrDefault() < n2.GetValueOrDefault()) && 
    (n1.HasValue & n2.HasValue)

n1.GetValueOrDefault() will return 0.

n2.GetValueOrDefault() will return 5.

That means the first part of our expression will be true because 0 is less than 5.  However the second part of our expression will be translated into (false & true) which equals to false.  So the first expression is true and the second one is false that means that the whole expression is false too.

That explains why any relation comparison with null value will be false.

kick it on DotNetKicks.com

.Net, C#, Coding, GetHashTable, VS2005, VS2008

Explaining GetHashCode method.

Every object you ever created or used in .NET has GetHashCode method along with Equals, GetType, and ToString methods.  This method is an instance method of an Object class from which any other class derives.


GetHashCode() method returns an integer that identifies an object instance.  I also can repeat MSDN documentation but you can read it on your own.

You would want to override this method along with Equals() method in your class if the object of your class is going to be used as a key in Hashtable.

The best way to explain it is to show an example. In I was using class Point as an example.  I’m going to continue with this class.  So let assume that we have class like this:

   1: public class Point
   2: {
   3:   private readonly int _x;
   4:   private readonly int _y;
   6:   public Point(int x, int y)
   7:   {
   8:     _x = x;
   9:     _y = y;
  10:   }
  11: }

Next we want to use Point as a key in a Hashtable.  Remember that the key of the Hasthable must be unique.  In the code bellow we have two identical keys (line 2 & 4). We should expect ArgumentException.

   1: Hashtable hashtable = new Hashtable();
   2: hashtable.Add(new Point(2, 3), "Point 1");
   3: hashtable.Add(new Point(5, 3), "Point 2");
   4: hashtable.Add(new Point(2, 3), "Point 3");

However, no exception was thrown.  There are two reasons why exception is not thrown:

  1. Equals() method that is also an instance method of Object class will always indicate that Point in line 2 and line 4 are different. This expected because two objects have different references.
  2. GetHashCode() method returns different number for these objects.

Try to execute code bellow:

   1: static void Main(string[] args)
   2:  {
   3:    var point1 = new Point(2, 3);
   4:    var point2 = new Point(2, 3);
   5:    Console.WriteLine("point1 Hash: {0}"
   6:         , point1.GetHashCode());
   7:    Console.WriteLine("point2 Hash: {0}"
   8:         , point2.GetHashCode());
   9:    Console.WriteLine("point1 equal to point2: {0}"
  10:         , point1.Equals(point2));
  11:  }

You will get output similar to this one:

point1 Hash: 58225482
point2 Hash: 54267293
point1 equal to point2: False

You can see that we got different hash codes.

To solve this problem we override Equal() and GetHashCode() in our Point class.

First we override Equals() method:

   1: public override bool Equals(object obj)
   2: {
   3:   if (ReferenceEquals(null, obj)) return false;
   4:   if (ReferenceEquals(this, obj)) return true;
   5:   return ((Point)obj)._x == _x && ((Point)obj)._y == _y;
   6: }

You can see that I use ReferenceEquals() method that is static method of Object class.  It checks if the specified objects are the same.

Next we override GetHashCode() method:

   1: public override int GetHashCode()
   2: {
   3:   unchecked
   4:   {
   5:     return (_x * 397) ^ _y;
   6:   }
   7: }

The whole Point would look like this:

   1: public class Point
   2: {
   3:   private readonly int _x;
   4:   private readonly int _y;
   6:   public Point(int x, int y)
   7:   {
   8:     _x = x;
   9:     _y = y;
  10:   }
  12:   public override bool Equals(object obj)
  13:   {
  14:     if (ReferenceEquals(null, obj)) return false;
  15:     if (ReferenceEquals(this, obj)) return true;
  16:     return ((Point)obj)._x == _x && ((Point)obj)._y == _y;
  17:   }
  19:   public override int GetHashCode()
  20:   {
  21:     unchecked
  22:     {
  23:       return (_x * 397) ^ _y;
  24:     }
  25:   }
  26: }

Now if you try to execute the application the output should look exactly like this:

point1 Hash: 793
point2 Hash: 793
point1 equal to point2: True

Also if we try to add new Point(2, 3) twice, we get an ArgumentException as expected.

kick it on DotNetKicks.com

.Net, C#, Coding, DateTime

Take control of DateTime’s ToString() method.

DateTime_ToString Today I had to write to the database a string that satisfies  following format: DDMMYYYY-CountryCode.  For example if DateTime object equal to 06/19/2008 and country code is USA, the value written to the database must be “06192008-USA“. 

The best way I found to do that is to use ToString() method of DateTime object with custom date and time format.

someDate.ToString("MMddyyy-") + CountryCode;

NOTE: In the format above I used two ‘M’s and two ‘d’s.  If only one ‘M’ and one ‘d’ was used, no month or date would be padded with zero.

someDate.ToString("Mdyyy-") + CountryCode;

The output for the code above would be “6192008-USA” assuming that the date is 06/19/2008 and the country code is USA.

UPDATE: I had to change the lines of code above because it had a bug.  Thanks to Alexey Romanov for pointing it out.  I put one line of code for the world to see and it was buggy.

The previous code looked like this:

someDate.ToString(String.Format("MMddyyy-{0}"), CountryCode);

Let assume that CountryCode is MEX.  In this case it’s the same as:


Remember that “M” is a special character for DateTime object.  The output for this code would be “06192008-6EX“.  It definitely is a problem.

.Net, C#, Coding, MbUnit, Rhino.Mocks, TDD

Mock DataTable

Today I had to work with some legacy code.  It was originally written in Delphi and then converted line by line to C#.  Before changing anything in the code I decided to create unit tests and make sure that I have 100% coverage.

One of the thing I had to do in my unit test is to mock DataTable.  Here are the steps I made during mocking.

  1. Create needed columns in a DataTable.
  2. Create a new DataRow.
  3. Assign values to the row.
  4. Finally add the row to the DataTable.

Repeat steps 2- 4 for each row you want to add to your DataTable.

Here’s the example:

   1: [Test]
   2: public void HolidayTest()
   3: {
   4:   MockRepository mocks = new MockRepository();
   5:   ICompanyDAL dalMock = mocks.CreateMock<ICompanyDAL>();
   6:   // Create DataTable
   7:   DataTable fakeHolidays = new DataTable();
   8:   // 1. Add Columns
   9:   fakeHolidays.Columns.Add("Holiday", typeof (DateTime));
  10:   fakeHolidays.Columns.Add("Name", typeof(string));
  11:   // 2. Create new DataRow
  12:   DataRow dayRow = fakeHolidays.NewRow();
  13:   // 3. Assign values to the row
  14:   dayRow["Holiday"] = DateTime.Parse("07/04/2008");
  15:   dayRow["Name"] = "Independence Day";
  16:   // 4. Add the row to the DataTable
  17:   fakeHolidays.Rows.Add(dayRow);
  18:   _pgDate.CompanyDal = dalMock;
  19:   using (mocks.Record())
  20:   {
  21:     Expect.Call(dalMock.GetHolidays()).Return(fakeHolidays);
  22:   }
  23:   using (mocks.Playback())
  24:   {
  25:     DataTable holidays = _pgDate.Holidays;
  26:     Assert.GreaterThan(holidays.Rows.Count, 0);
  27:   }
  28: }

I used Rhino.Mocks as my mocking framework in the example above.

kick it on DotNetKicks.com

.Net, C#, Coding, Generics, XML

GetAttribute Generics way.

As developers we often need to work with Xml.  In my case I found myself writing code like this one:
   1: public void Main()
   2: {
   3:   string name;
   4:   bool required;
   5:   XmlDocument _xmlDoc = new XmlDocument();
   6:   _xmlDoc.LoadXml("<column name=\"colName\" required=\"true\"/>");
   7:   if (_xmlDoc.DocumentElement.HasAttribute("name"))
   8:     name = _xmlDoc.DocumentElement.GetAttribute("name");
   9:   if (_xmlDoc.DocumentElement.HasAttribute("required"))
  10:     required = Convert.ToBoolean(_xmlDoc.DocumentElement.GetAttribute("required"));
  11: }
I hated the fact that I have to for every attribute use two lines in my Main function.  Below you can see refactored code.
Note: You will need to pass XmlNamespaceManager if you’re using namespaces.
   1: public void Main()
   2: {
   3:   XmlDocument _xmlDoc = new XmlDocument();
   4:   _xmlDoc.LoadXml("<column name=\"colName\" required=\"true\"/>");
   5:   string name = GetAttribute<string>(_xmlDoc.DocumentElement, "name");
   6:   bool required = GetAttribute<bool>(_xmlDoc.DocumentElement, "required");
   7: }
   1: private T GetAttribute<T>(XmlElement columnElement, string attributeName)
   2:   where T : IConvertible
   3: {
   4:   if (columnElement.HasAttribute(attributeName))
   5:     return (T) Convert.ChangeType(columnElement.GetAttribute(attributeName), typeof (T));
   6:   return default(T);
   7: }
I hope you’ll find it useful.

kick it on DotNetKicks.com

.Net, Coding, TDD

Testing internals members with InternalsVisibleTo attribute.

I posted previously about testing non-public members with MbUnit.  I recently found out about InternalsVisibleTo attribute by reading Roy Osherove‘s book The Art of Unit Testing.

To use this attribute, your test assembly must be strong-named.  Then you put InternalsVisibleTo attribute with public key of test assembly into AssemblyInfo.cs file of assembly under test.

 1: [assembly: InternalsVisibleTo("MyAssembly.Tests, PublicKey=XXX")]

I created an Assembly Helper tool that creates the syntax for you.  The tool is working (or should work) with following languages:

  • C#AssemblyHelper
  • Visual Basic
  • Delphi
  • MS C++
  • Chrome

You can get the tool from here.

Steps to use InternalsVisibleTo attribute with the tool.

Let assume that you have Assm_A and Assm_ATests.

  1. Sign Assm_A and Assm_ATests with a Strong Name. You can read about that here.
  2. Compile your assemblies.
  3. Launch Assembly Helper tool .
  4. Select desired language and press on ‘Get Assemblies’ button and navigate to Assm_ATests.dll.
  5. Copy the text into AssemblyInfo file of Assm_A assembly.

Now your tests can access internals members of the assembly under test.

Note: With Assembly Helper tool you can select multiple assemblies at once.

kick it on DotNetKicks.com