Warum ist in "Dim x = 1" x ein System.Int32?
Eines der neuen Features von VB9 und C# 3.0 sind "Implicitly Typed Local Variables". Bei diesem Feature leitet sich der Typ einer Variablen bei der Deklaration aus dem zugewiesenen Ausdruck ab. Verdeutlichen soll dies ein kleines Beispiel:
In diesem Zusammenhang kommt immer wieder die Frage auf woher der Compiler „weiß“ um welchen Datentyp es sich handelt. Warum ist beispielsweise x in obigem Beispiel ein System.Int32 und kein System.Int16 oder System.Int64? Ein Blick in die Visual Basic Language Specification klärt diese Frage:
„The type of a literal is determined by its value or by the following type character. If no type character is specified, values in the range of the Integer type are typed as Integer; values outside the range for Integer are typed as Long. If an integer literal's type is of insufficient size to hold the integer literal, a compile-time error results.“
Mit Hilfe eines Suffixes kann ein Datentyp allerdings explizit definiert werden.
Dim x = 1S ' makes x a Short Dim x = 1I ' makes x an Integer - the default for smaller integers Dim x = 1L ' makes x a Long - the default for larger integers
Dim x = 1.0F ' makes x a float (Single) Dim x = 1.0R ' makes x a real (Double) Dim x = 1D ' makes x a Decimal
Dim x = "1"c ' makes x a Char (as opposed to string) Dim x = #12/31/1905# ' makes x a Date |
Schöne Grüße
Daniel
P.S.: Timothy Ng hat zwei brilliante Artikel zum dem Thema "Type inference in Visual Basic" geschrieben (Type inference in Visual Basic (part 1) und Type inference in Visual Basic (part 2)).