Monday, February 20, 2012

Switch Hitting

Since the middle of last year I've made the switch from VB to C#.

Mostly because every where I look for samples, training, webcasts, etc. all the code is in C#. Even Microsoft employees doing webcasts or seminars have all been using C#, without exception.

I've done my share of programming in several languages throughout school and work. (BASIC, QuickBasic, pascal, FORTRAN, C, C++, SPARC Assembly, Intel Assembly, java, VB, VB.Net, C#, SQL, HTML, JavaScript, VBScript, batch files, PLC, vhdl, plus a handful of others I dabbled in) So switching languages was no big deal to me, but now that I have switched I've found if I go back to do some things in older projects that are still in VB I code a little differently just in case I decide to convert the code to C# later.

For example, in the old days when you had a string that you wanted to get rid of leading and trailing spaces on, in VB you would go:

sTxt = Trim(sTxt)

But in C# there aren't really a lot of standalone built in functions like Trim, Split, Left, Right, etc. they are all tied directly to the datatypes and accessible as member functions and properties of the variables.
So in C# if I wrote that same line it would be:

sTxt = sTxt.Trim();

Now since C# and VB are both in the .Net world, they share the same data types and member functions, meaning in VB I can do the same code as above (without the semicolon).
So previously in VB I would write something like this:

Dim sSplit() As String
Dim nVal As Integer
Dim sTxt As String

If (InStr(SomeInput, ",", > 0) Then
    sSplit = Split(SomeInput, ",")
    If (IsNumeric(sSplit(0))) Then
        nVal = CLng(sSplit(0))
        nVal = -1
    End If
    sTxt = Trim(sSplit(1))
End If

Now I write it something like this:

If (SomeInput.indexOf(",") >= 0) Then
    sSplit = SomeInput.Split(New String() {","}, _
    If (Not(Integer.TryParse(sSplit(0), nVal))) Then
        nVal = -1
    End If
    sTxt = sSplit(1).Trim()
End If

So that to convert it to C# I really only have to change the built in keywords like If, Then, Not, etc. and add a bunch of semicolons:

if (SomeInput.IndexOf(",") >= 0)
    sSplit = SomeInput.Split(new string[] {","},
    if (!(int.TryParse(sSplit[0], nVal)))
        nVal = -1;
    sTxt = sSplit[1].Trim();

A little bit of a change in style for me after several years of coding in VB, but not difficult by any means, and it can save me tons of time later if I decide to convert an old project to C#. Since the middle of last year I've made the switch from VB to C#.

No comments:

Post a Comment