简体   繁体   中英

Converting C# knowledge to VB.NET any potential problems?

I have a team with people that are quite comfortable in C# but we got a requirement to write a project in VB.net. How hard would it be to think in C# and on the fly convert to VB? Is that doable?

Could you list the issues that we can come across?

I heard that VB.net doesn't have closures. Is that still true for .net 3.5?

If you are approaching VB.Net with the mindset of C# it's best to set the following options in the project

  • Option Strict On
  • Option Explicit On
  • Option Infer On

This essentially removes the late binding semantics of VB.Net and forces it to be a strictly typed language. This will make it closer to C# semantic wise (still not exact by any means).

VB.Net has Lambda Expression (and hence Closure) support starting with the Visual Studio 2008 / .Net Framework 3.5 release. Not expression and not Statement. Statement lambdas are not supported until VS2010 / .Net Framework 4.0. Although you can use the 4.0 compiler to downtarget 2.0 frameworks.

As C# and VB.NET uses the same framework and compile to very similar IL code, you have a lot for free. Writing Basic syntax instead is not that hard.

The C# syntax is more aimed at showing what's going on, while the VB syntax often hides away some details, so a C# programmer is already familiar with some concepts that may not at all obvious to a VB programmer. In some ways learning C# is a better way to learn how VB works than to learn VB itself...

I frequently answer VB.NET questions in different forums mostly based on my C# knowledge, and I still haven't written anything more than short test programs in VB.NET myself.

There are of course some quirks to look out for in VB. Like the / operator for example that always converts both operands to double, or the = operand that uses VB specific comparison code rather than the comparison specified for the equality operator in the .NET classes.

One area that VB.NET tends to try and cover up is working with events; others have briefly touched on some of the differences, but here's a little more on them:

VB.NET provides a WithEvents keyword for fields that raise events. If the field is declared WithEvents then you can add a Handles field.Event to the end of a method whose signature is compatible with the event; that method will automatically be a delegate of the event without needing to manually AddHandler and RemoveHandler ( += and -= ).

Private WithEvents SomeField
Public Sub SomeField_SomeEvent(sender as Object, e as EventArgs) Handles SomeField.SomeEvent
    Console.Writeline("SomeEvent occured")
End Sub

Event declarations and raising events are simplified a bit. VB.NET doesn't require that you check if an event is null prior to notifying listeners:

Public event SomeEvent as EventHandler(of SomeEventArg)
Public Sub SomeMethod()
    RaiseEvent SomeEvent(Me, new EventArgs)
End Sub

One "hidden" feature of events in VB.NET is accessing the underlying MulticastDelegate , to do something like GetInvocationList() Note: the event is named SomeEvent and the code to access the multicastdelegate calls an invisible field named SomeEventEvent :

Public event SomeEvent as EventHandler(of SomeEventArg)
Public Sub SomeMethod()
    // Note that SomeEvent's MulticastDelegate is accessed by appending
    // another "Event" to the end, this sample is redundant but accurate.
    // If the event was named ListChanged then it would be ListChangedEvent
    dim invocationList = SomeEventEvent.GetInvocationList()
End Sub

One of the biggest issues I've found is the apparent verbosity of VB. It has all these big keywords like MustInherit , NotInheritable , MustOverride , etc., where C# just has things like sealed , abstract and virtual . You have to have an End to everything ( End Sub , End Function , End While , End Namespace , End Class , etc.) And you have to explicitly mark read-only properties with the ReadOnly keyword; simply omitting the setter won't fly. Also remembering AndAlso and OrElse instead of the more intuitive (but non-short-circuiting) And and Or , and things like Is Nothing and IsNot Nothing instead of == null or != null .

None of these are necessarily problems with the language, but if you're accustomed to the relative simplicity of C#, VB code may look like a whole lot of extra stuff to you.

There were some useful articles in Visual Studio magazine back in Jan 2008.

You might also be interested in the question " what's allowed in VB that is prohibited in C# (or vice versa) "

A point which hasn't been mentioned here is that field initializers in C# run before the base constructor, while those in VB run between the base constructor and the first "real" statement of the derived-class constructor (after the base-constructor call, if any). This makes it possible for field initializers in a derived class to make use of base-class members (which may have been initialized using parameters passed to the constructor), but also means that if the base-class constructor of an object passes itself anywhere before it returns, the partially-constructed object may get used before all the field initializers have run. In C#, all of the field initializers will run before the base constructor starts execution, but none of the field initializers will be able to use the partially-constructed object.

PS--if any of the Microsoft people behind C# read this, would there be any particular difficulty adding a context-sensitive keyword for field declarations to specify whether they should be processed before or after the base constructor, or possibly have them performed by some special method that could be called from the constructor, which could be wrapped in a try-finally block (so any IDisposables thus allocated could be cleaned up) and might also be able to make use of parameters passed to the constructor?

I find this to be a handy article in highlighting the differences. I'm a vb.net programmer, and this helps me figure out c# code, so I'm sure it will work the other way!

http://www.codeproject.com/KB/dotnet/vbnet_c__difference.aspx

Just like any language (human or computer), you first learn to "translate in your head," then you eventually start "thinking" in the other language.

The quicker your team can make that leap, the better. So, do it the same way the experts tell you to learn a human language: real-world examples and immersion.

There are a few C# to VB.NET conversion utilities available online, so start by having the team write in C#, convert to VB.NET, and clean it up. (The conversion utilities vary in quality and have some limitations, especially with newer language features.)

Once they get the hang of the basic "grammar," drop them into VB.NET 100%.

I use both every day, often in different code windows at the same time, and have no problem context-switching or doing the "right thing" in each.

Apart from what Jared has already mentioned you should have no problems in doing this. The only other source of irritation is weird defaults. EG Did you know that VB.NET projects, by default hide the references node in solution explorer? (you have to select ShowAllFiles to see it).

Appreciating the age of this question, this one is probably quite well known now, but I'll add the one biggest gotcha I have seen in terms of writing VB.NET like a C# user:

Nothing does not mean null , it means default(T)

This means that...

Dim a As Integer = Nothing
Dim b As Integer? = Nothing 

...is entirely valid, and effectively means...

int a = default(int);    // 0
int? b = default(int?);  // null

John M Gant's answer touches on the fact that there are dedicated keywords for comparing to Nothing -meaning- null -- Is Nothing and IsNot Nothing but, if you forget and use = , you might get an unexpected result which is hard to track down:

Dim a As Integer? = Nothing
If a = Nothing Then Console.WriteLine("a = Nothing")
If a <> Nothing Then Console.WriteLine("a <> Nothing")
If a Is Nothing Then Console.WriteLine("a Is Nothing")
If a IsNot Nothing Then Console.WriteLine("a IsNot Nothing")

'Output:
'a Is Nothing

This one is at least caught by a compiler warnings (BC42037 and BC42038), so you might want to force those warnings to be errors in your VBPROJ file.

I don't think it would be too hard. VB.NET and C# are languages that are close to each other, only the syntax really differs. Of course it's going to take some time for your team to get used to the new language, but I don't think you'll run into big problems.

Oh, and VB.NET does have closures. It's missing a few other features from C# like the yield keyword, multi-statement lambdas and auto properties, but nothing very critical.

I think C# to VB.NET won't be too painful, it's just a case of learning a new syntax. In the current versions the capabilities of both languages are fairly closely aligned.

The other way round (VB.NET to C#) could be harder because people might be used to making use of the 'My' namespace and other things put in there to make VB6 developers feel at home.

There are some subtle differences you'll have to watch out for. For example VB.Net has no concept of short circuiting an if statement (I was corrected that apparently it does). If it just a short term project, you probably won't have a problem, but different languages do have different approaches to solving the same problem. An example of this is Python programmers talking about doing things in the "pythonic" way. They talk about this concept in the book Dreaming in Code where java programmers were trying to program java using the python syntax. It leads to taking the long way around to solving a problem. Will this happen with C# and VB.Net? It is hard to say, they both use the underlying frame work, so the differences won't be huge, but it would still help to try and learn how to use VB.NET the way it was intended.

Edit: so apparently, it does has the concept of short circuiting, but it doesn't do this by default where C# does. This just further proves the point of learning how the language functions can be beneficial in the long term.

One option if you don't feel like writing the vb.net code is to write your project in C#, compile it, and use Reflector to see what the vb.net equivalent looks like. It all compiles down to MSIL anyway!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM