Sunday, February 1, 2009

On the Benefits of Learning Multiple Languages

Finally, I got to the pile of magazines I wanted to read for long time. I found this article in Visual Studio magazine. I liked the title and started reading it. The basic premise is – “Learning other programming languages can make you more fluent and give you a better understanding of the language you depend on primarily.”

So I started coding in the language I know the best – C# and wrote some code


using System;

namespace demo
{
internal class Test
{
public static void Main()
{
const int i = 2;

//static method call
Console.WriteLine(IsEven(i));

//generic delegate
Func<int, bool> f = IsEven;
Console.WriteLine(f(2));

//anonmous method + lambda
Func<int, bool> f1 = j => j%2 == 0;
Console.WriteLine(f1(2));

Console.ReadLine();
}

public static bool IsEven(int number)
{
return number > 0 ? number%2 == 0 : false;
}
}
}

Now, I wanted to convert this code to visual basic. Interestingly, I found a decent conversion method to get this thing done. I used .NET reflector. I used reflector to disassemble C# .exe and then to convert the code to VB. Reflector did a good job and produced following VB code


Friend Class Test
' Methods
Public Shared Function IsEven(ByVal number As Integer) As Boolean
Return IIf((number > 0), ((number Mod 2) = 0), False)
End Function

Public Shared Sub Main()
Console.WriteLine(Test.IsEven(2))
Dim f As Func(Of Integer, Boolean) = New Func(Of Integer, Boolean)(AddressOf Test.IsEven)
Console.WriteLine(f.Invoke(2))
Dim f1 As Func(Of Integer, Boolean) = j => ((j Mod 2) = 0)
Console.WriteLine(f1.Invoke(2))
Console.ReadLine
End Sub

End Class

The only point it tripped is on the lambda expression syntax =>. So, I had to do a little bit of Googling to find the correct VB syntax. And, finally got the VB code like


Friend Class Test
' Methods
Public Shared Function IsEven(ByVal number As Integer) As Boolean
Return IIf((number > 0), ((number Mod 2) = 0), False)
End Function

Public Shared Sub Main()

Console.WriteLine(IsEven(2))
Dim f As Func(Of Integer, Boolean) = New Func(Of Integer, Boolean)(AddressOf IsEven)
Console.WriteLine(f.Invoke(2))
Dim f1 As Func(Of Integer, Boolean) = Function(j) j Mod 2 = 0
Console.WriteLine(f1.Invoke(3))
Console.ReadLine()

End Sub
End Class

I enjoyed this exercise. In fact, in the same edition of the VS magazine, I found couple of interesting articles - What VB Devs Should Know About C# and What C# Devs Should Know About VB.

If you are involved in any migration effort from VB to C# or vice versa, or work in the mix environment with a lot of VB and C# code co-existing peacefully , then you will find these articles really useful.

No comments: