Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Other Discussions
  3. Clever Code
  4. Converting code from C#.NET to VB.NET

Converting code from C#.NET to VB.NET

Scheduled Pinned Locked Moved Clever Code
csharphelp
33 Posts 20 Posters 3 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P petersgyoung

    Agree! Translation tool is not always reliable. A better translation of (int)f to VB.Net is Ctype(f, Integer). I do not think CInt() and Math.Floor are exact translation. Early this year, I translated the C# code of a book "Learning WCF" for O'Reilly into VB.Net. I did not use any translation tool at all. The reason is that when I do not know how to translate and try translation tools, they cannot give me the answer too.

    petersgyoung

    D Offline
    D Offline
    Daniel Grunwald
    wrote on last edited by
    #23

    CInt() and CType(, Integer) are equivalent, both are rounding. Even System.Convert.ToInt32 is using the VB semantics and rounds. (int)Math.Floor() is the best translation I could find so far, so I'll implement that in the next version of the SharpDevelop converter. Does anyone know a converter that gets this right? Even Reflector is decompiling (int)a incorrectly to CInt().

    P 1 Reply Last reply
    0
    • D Daniel Grunwald

      CInt() and CType(, Integer) are equivalent, both are rounding. Even System.Convert.ToInt32 is using the VB semantics and rounds. (int)Math.Floor() is the best translation I could find so far, so I'll implement that in the next version of the SharpDevelop converter. Does anyone know a converter that gets this right? Even Reflector is decompiling (int)a incorrectly to CInt().

      P Offline
      P Offline
      petersgyoung
      wrote on last edited by
      #24

      CInt() and Math.Floor are functions. CType(, Integer) and (int) are casting. You can easily substitute Integer with other types, e.g. CType(x, String) is (string)x, CType(x, DateTime) is (DateTime)x, etc. Unfortunately, VB and C# are using different rules for casting decimal to integer!

      petersgyoung

      D 1 Reply Last reply
      0
      • P petersgyoung

        CInt() and Math.Floor are functions. CType(, Integer) and (int) are casting. You can easily substitute Integer with other types, e.g. CType(x, String) is (string)x, CType(x, DateTime) is (DateTime)x, etc. Unfortunately, VB and C# are using different rules for casting decimal to integer!

        petersgyoung

        D Offline
        D Offline
        Daniel Grunwald
        wrote on last edited by
        #25

        CInt() is not a function, it's a cast operator and completely equivalent to CType(, Integer). However, VB uses different rules for casting, so the correct translation of (int) is to NOT use the cast operator in VB but do something that produces the same result as C#'s cast. The best alternative I found so far is Math.Floor.

        P 1 Reply Last reply
        0
        • D Daniel Grunwald

          CInt() is not a function, it's a cast operator and completely equivalent to CType(, Integer). However, VB uses different rules for casting, so the correct translation of (int) is to NOT use the cast operator in VB but do something that produces the same result as C#'s cast. The best alternative I found so far is Math.Floor.

          P Offline
          P Offline
          petersgyoung
          wrote on last edited by
          #26

          CInt() is a function that uses CType(, Integer) to return integer value for backward compatibility (VB6 function). I don't mean you cannot use Math.Floor. Before you do that, consider this: when you translate C# code to VB, all casting change to Math.Floor; and when you translate the translated VB back to C#, you cannot translate all Math.Floor back to casting. When you translate VB code to C#, you cannot use Math.Celling nor Math.Floor. VB is doing a better job in casting decimal to integer. I prefer casting 3.99 to 4 rather than casting it to 3.

          petersgyoung

          D 1 Reply Last reply
          0
          • P petersgyoung

            CInt() is a function that uses CType(, Integer) to return integer value for backward compatibility (VB6 function). I don't mean you cannot use Math.Floor. Before you do that, consider this: when you translate C# code to VB, all casting change to Math.Floor; and when you translate the translated VB back to C#, you cannot translate all Math.Floor back to casting. When you translate VB code to C#, you cannot use Math.Celling nor Math.Floor. VB is doing a better job in casting decimal to integer. I prefer casting 3.99 to 4 rather than casting it to 3.

            petersgyoung

            D Offline
            D Offline
            Daniel Grunwald
            wrote on last edited by
            #27

            CInt is not a function. It's an operator just like CType,TryCast,etc. Take a look at the VB specification. Or take a look at these programs: This one compiles:

            Module Program
            Sub Main()
            Dim d1 as Converter(Of Object, Integer) = AddressOf MyCInt
            End Sub

            Function MyCInt(o As Object) As Integer
            	return CType(o, Integer)
            End Function
            

            End Module

            But this one fails with a syntax error:

            Module Program
            Sub Main()
            Dim d1 as Converter(Of Object, Integer) = AddressOf CInt
            End Sub
            End Module

            Of course the conversion logic for VB->C# needs to use Convert.ToInt32() or Math.Round(). Of course not ALL Math.Floor() calls can be converted to casts, but I think all instances of "CInt(Math.Floor(x))" could be replaced with "(int)x".

            P 1 Reply Last reply
            0
            • D Daniel Grunwald

              CInt is not a function. It's an operator just like CType,TryCast,etc. Take a look at the VB specification. Or take a look at these programs: This one compiles:

              Module Program
              Sub Main()
              Dim d1 as Converter(Of Object, Integer) = AddressOf MyCInt
              End Sub

              Function MyCInt(o As Object) As Integer
              	return CType(o, Integer)
              End Function
              

              End Module

              But this one fails with a syntax error:

              Module Program
              Sub Main()
              Dim d1 as Converter(Of Object, Integer) = AddressOf CInt
              End Sub
              End Module

              Of course the conversion logic for VB->C# needs to use Convert.ToInt32() or Math.Round(). Of course not ALL Math.Floor() calls can be converted to casts, but I think all instances of "CInt(Math.Floor(x))" could be replaced with "(int)x".

              P Offline
              P Offline
              petersgyoung
              wrote on last edited by
              #28

              Thank you very much. You might be correct. But my point is that it is the responsibility of the programmer to make sure that he does not rely on casting to trim decimal if he wants to convert his codes to some other languages in the future. He needs to use Math.Floor() in his C# code. In fact, VB is a more forgiving language than C#. CType("3.4", Integer) is legal in VB, by (int)"3.4" is not.

              petersgyoung

              D 1 Reply Last reply
              0
              • P petersgyoung

                Thank you very much. You might be correct. But my point is that it is the responsibility of the programmer to make sure that he does not rely on casting to trim decimal if he wants to convert his codes to some other languages in the future. He needs to use Math.Floor() in his C# code. In fact, VB is a more forgiving language than C#. CType("3.4", Integer) is legal in VB, by (int)"3.4" is not.

                petersgyoung

                D Offline
                D Offline
                Daniel Grunwald
                wrote on last edited by
                #29

                petersgyoung wrote:

                But my point is that it is the responsibility of the programmer to make sure that he does not rely on casting to trim decimal if he wants to convert his codes to some other languages in the future.

                No. If the program is valid in C#, the converter should either report an error ("Program not convertable") or convert it into a VB program that does the same as the C# program. The converter should not introduce any subtle bugs. All converters I know (including the one I've written for SharpDevelop 2.x) are incorrect. They don't analyze semantics, so they are unusable for any mildly complex program. That doesn't mean that one shouldn't use casts in C# code because someone might convert the program later; it means that we need a better converter.

                petersgyoung wrote:

                In fact, VB is a more forgiving language than C#. CType("3.4", Integer) is legal in VB, by (int)"3.4" is not.

                That's why a correct converter must convert CType("3.4", Integer) to Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger("3.4").

                1 Reply Last reply
                0
                • C ClockMeister

                  Yeah, me too. C# is not intrinsically any better than VB.Net is - the syntax is just different. I have a business-rules engine that I maintain and enhance and it's ALL in VB.Net now. I would not have C# - it would make even more complicated the concepts I find relatively simple to implement in VB. I chose VB to get into Windows about 10 years ago - and I still choose it as the best all-'round language. I don't have to waste mental bandwidth dealing with multiple dialects whether I'm working with VB6, VBScript, VBA or VB.Net. That's OK, let the C# bigots continue flaming. Us VB guys will continue to get the job done. No big deal. -CB ;)

                  C Offline
                  C Offline
                  Chris Losinger
                  wrote on last edited by
                  #30

                  CodeBubba wrote:

                  Us VB guys will continue to get the job done.

                  you said something about 'bigots'. would you care to rephrase that ?

                  image processing toolkits | batch image processing

                  C 1 Reply Last reply
                  0
                  • C Chris Losinger

                    CodeBubba wrote:

                    Us VB guys will continue to get the job done.

                    you said something about 'bigots'. would you care to rephrase that ?

                    image processing toolkits | batch image processing

                    C Offline
                    C Offline
                    ClockMeister
                    wrote on last edited by
                    #31

                    Hi Chris, Rephrase? Nope - I said what I meant. I've run into a lot of developers online that exhibit bigoted behavior toward anyone who chooses something other than C# for the .Net platform. My comment was directed only toward those who exhibit such poor manners, not C# developers in general. I use C# myself when I *have* to but if I have any choice I use VB. Take Care, -CB :)

                    1 Reply Last reply
                    0
                    • T The_Mega_ZZTer

                      Last week I was converting a code project from this site to VB.NET for use in my project, using SharpDevelop's built-in tool. I discovered a couple of problems with it that do not generate compiler errors (compiler errors are easy to spot and fix): 1) In C# you can assign multiple variables the same value like so:

                      var1 = var2 = var3 = value;

                      It gets translated to:

                      var1 = var2 = var3 = value

                      Which has a completely different meaning in VB.NET! = is used for both assignment and comparison. In this statement, only the left value is assignment, and the others are comparison! This means that the only value that changes is var1, probably to FALSE or 0 instead of value (it could also be TRUE or -1. Exercise for the reader to figure out how). 2) Let's say in C# we have:

                      float f = 0.75; int i = (int)f;

                      Translates into:

                      Dim f as Single = 0.75
                      Dim i as Integer = CInt(f)

                      Which looks ok, until we check the value of i. It's 0 at the end of the C# code, but 1 at the end of the VB.NET code! This is because casting to an int in C# rounds floats down, but in VB.NET it rounds to the nearest integer. This may or may not cause problems, based on what the code is doing and how important it is to get an exact number. When you do end up with unacceptable rounding errors, you can simply replace the offending CInt with Math.Floor, which replicates C#'s behavior.

                      T Offline
                      T Offline
                      thrakazog
                      wrote on last edited by
                      #32

                      I'm currently working on a project going the other way round. VB.net to C#. Half way through I'm really starting to wonder why company wanted this. When you convert from one .net language to another you achieve different, not necessarily better. So, I'm starting with a working vb.net project and when I'm done we'll have working c# project. The projects are otherwise identical. All of our developers can work in vb.net or c#. So I guess the ROI for the hours I spend converting is right about zero.

                      1 Reply Last reply
                      0
                      • E Emilio Garavaglia

                        Well, the technical answer is that casting is not rounding. What you say about rounding is a math definition, that can be accessed by an appropriate math function of the math library or namespace or whatever in many languages. Casting is an operation whose semantics depend on the level of efficiency the designer of the languages had in mind while designing compilers. Probably -IMHO- VB designers attempted to let expressions closer to math appearance, (VB derives from the 80's BASIC that inherits the idea of expressions from the 70's FORTRAN that was designed to help scientist to write formulas in programs) while C# inherits the C idea of "the fastest way to convert for the processor", that is "truncate the fractional part". The key point behind of this, is that "converting between languages" is not only a matter of "syntax" but also of "semantics". So, it cannot be done automatically without any analysis of what an expression stands for.

                        2 bugs found. > recompile ... 65534 bugs found. :doh:

                        U Offline
                        U Offline
                        uvw
                        wrote on last edited by
                        #33

                        Good explaining. Every language has its own set of features and nuances. When we learn (and teach) a language, it is esseential to know how the language came about. As many agree, VB came as a quick tool to enable windows programming. Way back in 1995, just when Win95 was being pushed in to the work station area, I had a question, how do I implement my shell scripts in Windows. Some one from Microsoft answered, try VB. That was how I got interested in VB. In fact, Microsoft it self learnt many things about inter process communication after the success of VBX(OCX). Remember, Microsoft talked so much about embedded documents earlier. VBX proved a new way of looking at data exchange. I worked on C for almost 10 years and then shifted to VB. I have been with it for the last 11 years! Recently I started learning C# and find it a good tool to overcome some of the problems I face in VB. I have font servers written in VB, IPC protocol implementations in VB, printer driver like things in VB. But I see fresh air in C# (my company is named C-Quad, named way before C# was conceived). The network centric orientation of C# is unparalleled in any other language, with its roots deep in XDR specs from SUN! I dont know if Microsoft talks about it. I see a connection. I have moved from Fortran IV to Pascal to C to VB but skimmed over Java and VC++. Display Postscript, Motif and may other things inclusive. I still have a heart to learn C# for what it is worth. Of course most of my work will be done in VB.

                        UVW

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • World
                        • Users
                        • Groups