Console.WriteLine (Enum.Value) gives different results in C # and VB.Net

I am basically a C # guy, but currently writing VB.Net code.

Today I came across a completely different .Net behavior

C # code

enum Color
{
   Red,
   Green,
   Blue
}

class Demo
{
    public static void Main()
    {
        System.Console.WriteLine(Color.Red);
    }
}

Will print Red

But when this code is written in VB.Net, it prints 0.

code VB.Net

Module Module1

    Sub Main()
        System.Console.WriteLine(Color.Red)
    End Sub

End Module

Enum Color
    Red
    Green
    Blue
End Enum

Why is it so different?

+4
source share
2 answers

C # and VB.NET have different rules for resolving method overloads.

C # selects Console.WriteLine(Object), and VB.NET selects Console.WriteLine(Int32). Let's see why this is happening.

VB.NET Rules :

  • Availability. . This eliminates any overload with an access level that prevents the calling code from invoking it.

  • . , , .

  • . . - , , , . , , .
    , , .

  • .. , . , ( Strict Statement) .

  • . . . , . , , .

  • .. , , . , .

WriteLine, 3. : Object .

: . , ?

(Enum) , .

Object

, Color enum Int32 ( ) - 100% - Console.WriteLine(Int32). Int32 Object, , .


# ( # 5 spec §7.5.3.2):

A { E1, E2, ..., EN } MP MQ { P1, P2, ..., PN } { Q1, Q2, ..., QN }, MP , MQ,

  • , EX QX , EX PX
  • , EX PX , EX QX.

, (§7.5.3.4)?

C1, S T1, C2, S T2, C1 , C2, :

  • S T1, S T2
  • T1 - , T2 (§7.5.3.5)

. §7.5.3.5:

T1 T2, T1 , T2, :

  • T1 T2 , T2 T1
  • T1 - , T2 - .

, Color Object Int32. ?

  • Color Object
  • Object Color ()
  • Color Int32 ( #)
  • Int32 Color ( 0)

Spec §6.1:

:

  • .

, :

- 0 , . (§4.1.10).

(§6.1.7):

. , nullable-value, Object dynamic, System.ValueType , , nullable-value. , System.Enum.

+5

Console.WriteLine(Enum), . , VB.NET # , , , .

, , VB.NET :

   Dim example As Integer = Color.Red  '' Fine

# :

   int example = Color.Red;            // CS0266

, (int). , , , VB.NET.

, # , , , . , Console.WriteLine(Object). , .

VB.NET , "" . - , Integer . . , .

:

    System.Console.WriteLine(CObj(Color.Red))         '' or
    System.Console.WriteLine(Color.Red.ToString())
+6

All Articles