Showing posts with label c# gotcha. Show all posts
Showing posts with label c# gotcha. Show all posts

Tuesday, August 16, 2011

Resharper FileTemplates FTW!!





Sometimes, when you are pairing you feel the need to be more precise in the way you write code. You might want to generate the same amount of code using lesser keystrokes. This has a few un-obvious advantages:
  • that your pair is not going to have to sit bored as you keep pecking on that keyboard
  • with lesser keystrokes, you’re going to write code quicker(duh),
  • with lesser keystrokes, you have fewer errors.
  • You look cooler and more sophisticated.




Even the fastest typists I know are like hulk when it comes to coding - All brawn(Like Hulk). Coding is not just typing. Its more sophisticated(Like Flash).


Normally, creating a test class in c# would involve the following steps.

  1. Navigating to the folder where you want to put your test file.
  2. RightClicking on the folder and clicking add -> Class
  3. Giving a proper name for the test class.

  4. Adding a using NUnit.Framework; line of code at the top of the file
  5. Marking the class as [TestFixture]
  6. Adding [SetUp] and [TearDown] methods
  7. Finally, you get to the test and get to the arrange, act, assert tradition.
One such feature in Resharper is File Templates and its darn useful.

To illustrate, lets try writing a basic Test Class with a basic test and see how many steps it takes.


Alt+Insert on a folder and selecting Test
 




Giving the new Test Fixture a proper name

Voilla


Friday, July 1, 2011

DBNull and null

I am deeply frustrated at this point in time. The reason is because I have been spending the last 30 minutes hung over a very careless mistake. C# has the coalesce operator that allows you to write code that looks neater when you are doing complex stuff like LINQ. The problem looked something like this - I had to read a couple of rows from the database and convert those data as properties on an object.
the code would look something like this:

object x;
int value;
if (x == null)
  value = -1; // default value
else
value = (int)x;

The coalesce operator allows you to make the code more concise by saying

int value = x ?? -1;// less code = less maintainence

but whilst reading data from a database table, if a particular cell is a null value, it is not read as a null but it is read as a System.DBNull. So, the freaking row[field] read was getting read as a DBNull. Once I noticed that this was the problem,  I coul;d fix the code, but the fix was less elegant.
More edits on this post when I find more about it.

[Edit 1]
Found this related question on Stackoverflow [here]