Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB vs C#: Why is this possible?

Tags:

Here is some code that troubles me every time I think about it.

Option Strict On  Module Module1      Sub Main()         For Each i As Integer In New String() {"why", "is", "this", "tolerated?"}             ' compiles just fine.         Next     End Sub  End Module 

C# simply will not allow converting strings to integers implicitly.

class Program {     static void Main(string[] args) {         foreach (int i in new string[] {"that's", "better"}) {             // will not compile, and for good reason.         }     } } 

Why does VB let us do that? I'm trying to have fun with this because I'm still relatively new here, but I'm also genuinely curious. I'm sure there are devs out there with the answer.

like image 405
scottyeatscode Avatar asked Oct 17 '14 01:10

scottyeatscode


People also ask

Is Visual Basic based on C?

Visual Basic can also be used within other Microsoft software to program small routines. Visual Basic was succeeded in 2002 by Visual Basic . NET, a vastly different language based on C#, a language with similarities to C++.

Is C# better than VB?

Even though there is less prominence of VB.NET community, but still we can say VB.NET is better than C#. 1. VB.NET uses implicit casting and makes it easier to code whereas in C# there are lot of casting and conversions needs to be done for the same lines of code.

Is VB same as C++?

Conclusion. In brief, Visual Basic refers to a programming language while Visual C++ refers to an IDE. The main difference between Visual Basic and Visual C++ is that Visual Basic is an Object Oriented Programming Language while Visual C++ is an Integrated Development Environment (IDE).


1 Answers

It appears to be a idiosyncrasy of the For Each Statement. According to the documentation it is evaluated at Runtime.

From Link:

When Option Strict is set to On, narrowing conversions ordinarily cause compiler errors. In a For Each statement, however, conversions from the elements in group to element are evaluated and performed at run time, and compiler errors caused by narrowing conversions are suppressed.

In the following example, the assignment of m as the initial value for n doesn't compile when Option Strict is on because the conversion of a Long to an Integer is a narrowing conversion. In the For Each statement, however, no compiler error is reported, even though the assignment to number requires the same conversion from Long to Integer. In the For Each statement that contains a large number, a run-time error occurs when ToInteger is applied to the large number.

like image 148
Mark Hall Avatar answered Nov 06 '22 02:11

Mark Hall