Friday, August 28, 2009

Simple Checksum Generation in .NET

.NET framework is a tremendous installment from MSFT. No doubt! Every day-to-day life methodologies are wrapped into a Namespace/Class form. Say, Mail Sending class (System.Net.Mail), and so on. With the release of .NET 3.0, the number of Namespace/Class simply grew and they’ll.

A major installment in .NET 3.0 was Lambda Expressions. That even reduced the Line of Codes(LOC). In a nutshell, Lambda expression converts a bunch of codes into a single line of code, which we(I) may call as one-liner codes. Hard to believe, wait!

How, it affected a programmer? Does it made their work easier or does it made them lazy? Anyway, it made me lazy a bit. Because, whenever I start to implement repeating/familiar codes, say Checking Odd/Even values, etc, I always look for one-liners. Because, I don't want to repeat the same LOC every time. But, its better to know, what’s the internal implementation of one-liner, for Performance and Optimization reasons.

Recently, I’s developing an application for one of my client, in which I’ve to implement a checksum feature for a 9-Digit UniqueID (generated from another code-block).

The checksum technique was simple. My checksum has 3-Digits;
a) 1st Digit = Total Sum (of 9 Digits)
b) 2nd Digit = Even Sum (sums up the digits in the even place)
c) 3rd Digit = Odd Sum (sums up digits in the odd place)

Please note, Chances are that the Total Sum, Even Sum or Odd Sum may have 2 Digits, which you’ve to sum up again to a single digit.

The traditional mode of generating Even Sum, Odd Sum and Total Sum deals with a lot of mathematical computations and all, which is quite tedious to repeat every time. Here comes Lambda Expression, as a handy feature in .NET 3.0.

Here is the code segment for :

a) Total Sum

   1: int totSum = uniqueId.ToString().Sum(c => c - '0');

b) Even Sum

   1: bool flag = false;
   2: int evenSum = uniqueId.ToString().Sum(c => (flag = !flag) ? 0 : c - '0');

c) Odd Sum

   1: bool flag = false;
   2: int oddSum = uniqueId.ToString().Sum(c => (flag = !flag) ? c - '0' : 0);

I bet, this is quite handy.

No comments:

Best viewed in Internet Explorer 8.