9

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?

Piotr Czapla
  • 25,734
  • 24
  • 99
  • 122
  • 2
    it's not really worth an answer, but keeping VB.NET visually organized is more difficult than C# since the keywords are larger and of more varied length, and there's no brackets (which help with vertical space). Methods written in VB.NET and C# put side by side will typically let C#'s logic appear clearer. – STW Aug 26 '09 at 22:08
  • Why is that a requirement? That doesn't make very much sense. Can you give us more background so we aren't scratching our heads? – George Stocker Oct 07 '09 at 17:40
  • I was considering a project that had such nonfunctional requirement. – Piotr Czapla Oct 08 '09 at 06:21
  • I would disagree with yoooder - most people find vb.net more readable because it is more verbose. Im sure everybody here will disagree since c# is cooler. – ChickenMilkBomb Dec 28 '09 at 18:41

14 Answers14

14

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.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
3

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.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 2
    +1 I always tell people learning the .NET platform (especially those new to OOP) to learn C# first, and then move on to VB if necessary. Nothing wrong with VB, but for the reasons you mention C# gives you a clearer picture of what's going on in the framework IMO. – John M Gant Aug 26 '09 at 21:08
  • 2
    @jmgant: I disagree, VB.NET provides a lower barrier to entry than C# and gets you coding in the .NET world faster--although the reasons to stay in VB.NET quickly diminish. I usually advise to start with VB.NET to get up to speed, then make the jump to C# to pull the curtains back the rest of the way. – STW Aug 26 '09 at 21:44
  • 1
    @jmgant & Yoooder: I think both ways have merit, and each fits better for different people, depending on whether they want to ease into it or sink their teeth in. :) – Guffa Aug 26 '09 at 22:30
  • 2
    Good answer. I do the same as Guffa, but in reverse. I code in VB but answer C# questions on SO from time to time. Goes to show that the VB vs C# debate is futile because both languages are actually very close (and will get even closer in the future). You just cannot say that one language is bad (or good) without saying that the other also is ;-) – Meta-Knight Dec 28 '09 at 18:46
3

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
STW
  • 44,917
  • 17
  • 105
  • 161
  • The last bit has nothing to do with VB.NET per-se. That's a framework feature; there isn't even any VB-specific syntax. – Adam Robinson Dec 28 '09 at 00:29
  • 2
    @Adam: the VB.NET specific portion is appending "Event" to the event name in order to access the multicast delegate. – STW Dec 28 '09 at 18:37
2

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.

John M Gant
  • 18,970
  • 18
  • 64
  • 82
  • 5
    Yes, VB is definitely a bit more verbose, but if typing is the biggest part of your programming, you are not working with projects that are nearly challenging enough... :) – Guffa Aug 26 '09 at 21:08
  • 1
    VB.NET is chattier, but also more descriptive. If you're just starting in .NET it's nice to see "`Inherits BaseClass Implements IDisposable Implements ISomeInterface` than `: BaseClass IDisposable ISomeInterface`; especially when you're trying to get code to compile and something is simply out of order. After a while it gets to be annoying though and the shortcuts in C# become more and more appealing – STW Aug 26 '09 at 21:46
  • @Guffa +1, funny... although it's really not just the typing, it's the reading, understanding and refactoring. – John M Gant Aug 27 '09 at 12:58
  • @Guffa - nice comment. But it really is annoying. i've worked with large projects in both c# and vb.net. and the best case example i have for annoying typing is parameters for methods (aka subs and functions :)) public string SomeMethod(string var1, string var2, int var3) is easy. public Function SomeMethod(ByVal var1 As string, ByVal var2 As string, ByVal var3 As Integer) As string. Ouch. The ideas happen faster than i can type it out :) – Kamal Dec 04 '09 at 11:21
2

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)"

Community
  • 1
  • 1
MarkJ
  • 30,070
  • 5
  • 68
  • 111
2

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?

supercat
  • 77,689
  • 9
  • 166
  • 211
1

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

ScottE
  • 21,530
  • 18
  • 94
  • 131
  • Amazingly, that leaves out the AddHandler and RemoveHandler for VB.NET vs "+=" and "-=" for C#. Another thing that was rough when going to VB.NET from C# was the "Handles" keyword which followed a method in VB, subscribing to an event. – John Fisher Aug 26 '09 at 20:48
  • Good point. It's also tricky going the C# direction with AutoEventWireup and no use of 'Handles'. This is a good article explaining things. http://odetocode.com/blogs/scott/archive/2006/02/16/2914.aspx – ScottE Aug 26 '09 at 21:35
1

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.

richardtallent
  • 34,724
  • 14
  • 83
  • 123
1

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

Quibblesome
  • 25,225
  • 10
  • 61
  • 100
1

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.

jimbobmcgee
  • 1,561
  • 11
  • 34
0

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.

Meta-Knight
  • 17,626
  • 1
  • 48
  • 58
  • VB9 has one-line function closures. VB10 has the same closures as C#. – Craig Gidney Aug 26 '09 at 20:34
  • @Strilanc, Lambdas and closures are separate concepts. The closure implementation for VB.Net is unchanged between 9.0 and 10.0. The lambda implementation varies greatly though. – JaredPar Aug 26 '09 at 20:49
0

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.

Adam Ralph
  • 29,453
  • 4
  • 60
  • 67
0

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.

kemiller2002
  • 113,795
  • 27
  • 197
  • 251
  • 1
    I'm happy that short circuting was brought into discussion. Everybody in my team would expect `if x IsNot Nothing And x.method()` would not throw a null pointer exception. – Piotr Czapla Aug 26 '09 at 20:59
  • The structure of the languages are not very different, way back they have a common ancestor in ALGOL. The C# way of writing code generally translates very well to VB. – Guffa Aug 26 '09 at 21:47
  • I understand what you are saying, but that statement could be made for a lot of languages. C++, C#, Java, the list goes on and on. They are more similar than comparing to Perl, but there is a divergence. – kemiller2002 Aug 26 '09 at 23:42
0

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!

ScottE
  • 21,530
  • 18
  • 94
  • 131
  • It works, sometimes. The regenerated code is iffy at best and if you're talking about a potentially sizable class then it can be painful. – STW Aug 26 '09 at 21:48
  • @Yoooder, I've never seen this in anything I've worked with. I find it's a great learning tool. – ScottE Aug 26 '09 at 22:03
  • it's only worked for me on small samples; whenever I need to export a sizable assembly I find myself having to correct a fair amount. Perhaps it's specific to the version of the framework I'm working with – STW Aug 26 '09 at 22:31
  • Yes, I'm sure you have to make changes, especially in more complicated scenarios. For example, I'm not sure how static classes would translate into vb.net, or how optional parameters are handled in c# pre 4.0. At any rate, it's still very handy! – ScottE Aug 27 '09 at 01:19
  • @ScottE, static classes are most closely analogous to modules in VB. You can't instantiate modules, and all of their methods are automatically static (and can't be explicitly declared as such). – John M Gant Aug 27 '09 at 13:01
  • +1 to compensate for the needless downvote. This is a perfectly legitimate way to see what a corresponding bit of VB code might look like. Obviously this isn't a way of translating production code, but it's still a useful learning tool. – Adam Robinson Dec 28 '09 at 00:31