[
  {
    "path": ".gitattributes",
    "content": "* text=auto\n"
  },
  {
    "path": "CODE-OF-CONDUCT.md",
    "content": "# Code of Conduct\n\nThis project has adopted the code of conduct defined by the Contributor Covenant\nto clarify expected behavior in our community.\n\nFor more information, see the [.NET Foundation Code of Conduct](https://dotnetfoundation.org/code-of-conduct).\n"
  },
  {
    "path": "Language-Version-History.md",
    "content": "# Features Added in VB Language Versions\n\n*NOTE:* See how to [specify the language version for your project here](https://docs.microsoft.com/dotnet/visual-basic/language-reference/configure-language-version)\n\n## Visual Studio 2022, .NET 6\n\n- [CallerArgumentExpression](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/caller-argument-expression.md): Note that this feature isn't gated under a language version. It's available for compilers that shipped starting with Visual Studio 2022 version 17.0.\n\n## VB 15.0 (Visual Studio 2017)\n\n- [Tuples](https://github.com/dotnet/roslyn/blob/master/docs/features/tuples.md)\n- [Binary Literals](https://github.com/dotnet/csharplang/blob/master/proposals/csharp-7.0/binary-literals.md)\n- [Digit Separators](https://github.com/dotnet/csharplang/blob/master/proposals/csharp-7.0/digit-separators.md)\n\n## VB 15.3 (Visual Studio 2017 version 15.3)\n\n- [Inferred tuple element names](https://github.com/dotnet/csharplang/blob/master/proposals/csharp-7.1/infer-tuple-names.md)\n\n## VB 15.5 (Visual Studio 2017 version 15.5)\n\n- [Non-trailing named arguments](https://github.com/dotnet/csharplang/blob/master/proposals/csharp-7.2/non-trailing-named-arguments.md)\n- [Private Protected accessibility](https://github.com/dotnet/csharplang/blob/master/proposals/csharp-7.2/private-protected.md)\n- [Digit separator after base specifier](https://github.com/dotnet/csharplang/blob/master/proposals/csharp-7.2/leading-separator.md)\n\n## VB 17.13 (Visual Studio 2022 version 17.13)\n\n- Recognizing 'unmanaged' constraint\n- [Overload Resolution Priority](https://github.com/dotnet/vblang/blob/main/proposals/overload-resolution-priority.md)\n"
  },
  {
    "path": "README.md",
    "content": "# Visual Basic .NET Language Design\n\nWelcome to the official repo for Visual Basic .NET language design.\n\n* Full Language Specification: [Markdown](spec)\n* List of proposals can be found in the [proposals folder](proposals).\n* Archives of notes from design meetings, etc., can be found in the [meetings folder](meetings).\n\nIf you discover bugs or deficiencies in the above, please leave an issue to raise them, or even better: a pull request to fix them.\n\nFor *new feature proposals*, however, please raise them for [discussion](https://github.com/dotnet/vblang/labels/Discussion), and *only* submit a proposal as a pull request if invited to do so by a member of the Language Design Team (a \"champion\").\n\n## Discussion\n\nDiscussion pertaining to language features takes place in the form of issues in this repo, under the [Discussion label](https://github.com/dotnet/vblang/labels/Discussion).\n\nIf you want to suggest a feature, discuss current design notes or proposals, etc., please [open a new issue](https://github.com/dotnet/vblang/issues/new), and it will be tagged Discussion.\n\nGitHub is not ideal for discussions, but it is beneficial to have language features discussed nearby to where the design artifacts are. Comment threads that are short and stay on topic are much more likely to be read. If you leave comment number fifty, chances are that only a few people will read it. To make discussions easier to navigate and benefit from, please observe a few rules of thumb:\n\n- Discussion should be relevant to Visual Basic .NET language design. Issues that are not will be summarily closed.\n- Choose a descriptive title for the issue, that clearly communicates the scope of discussion.\n- Stick to the topic of the issue title. If a comment is tangential, start a new issue and link back.\n- If a comment goes into detail on a subtopic, also consider starting a new issue and linking back.\n- Is your comment useful for others to read, or can it be adequately expressed with an emoji reaction to an existing comment?\n\n## Design Process\n\nVisual Basic .NET is designed by the Visual Basic .NET Language Design Team (LDT).\n\n1. To submit, support, and discuss ideas please use the [Discussion label](https://github.com/dotnet/vblang/labels/Discussion).\n\n2. Ideas that the LDT feel could potentially make it into the language should be turned into [proposals](proposals), based on this [template](proposals/proposal-template.md), either by members of the LDT or by community members by invitation from the LDT. The lifetime of a proposal is described in [proposals/README.md](proposals/README.md). A good proposal should:\n    * Fit with the general theme and aesthetic of the language.\n    * Not introduce subtly alternate syntax for existing features.\n    * Add a lot of value for a clear set of users.\n    * Not add significantly to the complexity of the language, especially for new users.  \n\n3. A prototype owner (who may or may not be proposal owner) should implement a prototype in their own fork of the [Roslyn repo](https://github.com/dotnet/roslyn) and share it with the design team and community for feedback. A prototype must meet the following bar:\n\t* Parsing (if applicable) should be resilient to experimentation--typing should not cause crashes.\n\t* Include minimal tests demonstrating the feature at work end-to-end.\n\t* Include minimal IDE support (keyword coloring, formatting, completion).\n\n4. Once a prototype has proven out the proposal and the proposal has been _approved-in-principle_ by the design team, a feature owner (who may or may not be proposal or prototype owner(s)) implemented in a feature branch of the [Roslyn repo](https://github.com/dotnet/roslyn). The bar for implementation quality can be found [here](https://github.com/dotnet/roslyn).\n\n5. Design changes during the proposal or feature implementation phase should be fed back into the original proposal as a PR describing the nature of the change and the rationale.\n\n6. A PR should be submitted amending the formal language specification with the new feature or behavior.\n\n7. Once a feature is implemented and merged into shipping branch of Roslyn and the appropriate changes merged into the language specification, the proposal should be archived under a folder corresponding to the version of the language in which it was included, e.g. [VB 15.1 proposals](proposals/adopted/vb15.1)). Rejected proposals are archived under the [rejected folder](proposals/rejected).\n\n## Language Design Meetings\n\nLanguage Design Meetings (LDMs) are held by the LDT and occasional invited guests, and are documented in Design Meeting Notes in the [meetings](meetings) folder, organized in folders by year. The lifetime of a design meeting note is described in [meetings/README.md](meetings/README.md). LDMs are where decisions about future Visual Basic .NET versions are made, including which proposals do work on, how to evolve the proposals, and whether and when to adopt them.\n\n## Implementation\n\nThe reference implementation of the Visual Basic .NET language can be found in the [Roslyn repository](https://github.com/dotnet/roslyn). Until recently, that was also where language design artifacts were tracked. Please allow a little time as we move over active proposals.\n\n**DISCLAIMER**: An active proposal is under active consideration for inclusion into a future version of the Visual Basic .NET programming language but is not in any way guaranteed to ultimately be included in the next or any version of the language. A proposal may be postponed or rejected at any time during any phase of the above process based on feedback from the design team, community, code reviewers, or testing.\n"
  },
  {
    "path": "meetings/2014/LDM-2014-02-10.md",
    "content": "VB Language Design Meeting 2014-02-10\n\n# Strict Module\n\nC# lets you have \"static class\" but VB only has \"Module\" which lifts all its members into the namespace. Discussion on this was prompted by a comment of MVP Jan Záruba (Đonny) who said\n> I use Partial Private Sub New to achieve the same effect as in C# with static class. The advantage of this compared to Module is that static class does not \"pollute\" namespaces with it's members (and I also cannot have generic module anyway).\"\n\nĐonny encountered a known and approved Roslyn breaking change, where VS2013 let you write \"private partial sub new\", but Roslyn doesn't. This is by design. But the question is, what could he and other users do?\n\nLanguage designer Anthony D. Green looked into it:\n> Today VB’s modules behave very much like F#’s modules when the AutoOpen attribute is applied. I’m proposing adding a modifier “Explicit” to modules which will go the other way. Additionally, we’d considered changing the codegen of VB Modules to exactly match those of C# (both abstract and sealed) so that they could be recognized by C# in Dev10. Unfortunately this turned out to be a breaking change due to a bug in the XmlSerializer. With my proposal we could consider changing the metadata representation to match C# and could also map C# static classes back to Explicit Modules. If C# does end up accepting the static import feature but retains the restriction to static classes it’ll be important to have a way for VB code to easily create such things – otherwise C# won’t be able to consume them (e.g. the Roslyn VB SyntaxFactory module).\n\n## IL\n\nC# static classes are currently emitted as `.class private abstract auto ansi sealed beforefieldinit`\nVB modules are currently emitted as `[StandardModule] .class private auto ansi sealed`\n\n## Language design\n\n* How do you declare something whose name is hidden and whose members are lifted to the enclosing namespace?\n** VB: <HideModuleName>\n** C#: not available\n** F#: not available\n* How do you declare something where people have to qualify member access, unless they specifically import them all?\n** VB: **NOT POSSIBLE, BUT DESIRABLE**\n** C#: new C#/Roslyn feature, \"static usings\"\n** F#: this is the default\n* How do you declare something which *always* requires qualification to access members?\n** VB: not available\n** C#: this is the default\n** F#: [<RequiresQualification>]\n\nThere's a clear VB parity gap here, which has been asked-for many times on user-voice and connect.\n\nAnthony's proposal is for \"static classes\", no more, no less. The question is (1) whether to allow it, (2) whether to call it \"explicit module\" or \"shared class\" or something.\n\nRESOLUTION: yes, we should allow it.\n\n## Syntax\n\nWe need a new keyword or keyword pair. Here are the candidates we came up with.\n\n**Strict Module**\nMustQualify Module\nExplicit Module\nOpaque Module\nMustQualifyMember Module\nClosed Module\nProtected Module\nPrivate Module\nStatic Module\nGreedy Module\nShared Module\nShared Class\nNamespace Module\n\nRESOLUTION: We'll use \"strict module\" as the best of a bad bunch. We're open to suggestions for better names.\n\n## Semantics\n\nThe metadata we emit for \"Strict Module\" should be the same as the metadata for C# static classes.\n\nQ. Generics? We could say \"strict modules\" can be generic. Note: you also can't have generic modules in VB. \nRESOLUTION: Strict modules CAN be generic; however generic modules CANNOT contain extension methods.\n\nQ. Nesting? Currently VB modules can't be nested. C# static classes can be nested.\nRESOLUTION: Strict modules cannot be nested.\n\nQ. For C#/Roslyn new feature, when they import static types, will they also allow importing VB modules?\nRESOLUTION: up to C#\n\nQ. How about VB importing C# static classes?\nRESOLUTION: Currently, VB can import C#'s static classes, and if they come with [StandardModule] then we auto-open. We will continue to do this. NOTE: THIS IS A BREAKING CHANGE: e.g. you will no longer be able to declare variables of type \"Console\". Doesn't seem a very bad breaking change.\n\nQ. What about <HideModuleName>?\nA. Intellisense will ignore this attribute on strict modules.\n"
  },
  {
    "path": "meetings/2014/LDM-2014-02-17.md",
    "content": "VB Language Design Meeting 2014-02-17\n\nROLL-UP OF PROPOSED FEATURES.\n\n*Please don't reply to this post with comments on individual language features. That will get out of hand because there are so many of them. If you have comments on an individual feature, please create a new post for it. If the feature's also in C#, then cross-post to the \"C# language design\" topic.*\n\nWe spent this meeting on a complete roll-up of all the Dev14 ideas that have been floated and designed so far. This isn't a commitment that we will have time to finish designing or finish implementing them. It's just where we are at the moment.\n\nThe notes from this meeting are deliberately \"RAW\". I haven't spent time to type them up neatly. My goal is to get all language notes out in the open, where the public can see them, with as little process or hindrance as possible. I figure it's better to publish early and iterate (and fix typos), rather than publish late. If you see anything that seems wrong or you disagree with, please first seek clarification rather than taking these notes as Microsoft's definitive statement on anything.\n\nYou might notice that I've written the date in ISO format, \"2014-02-17\". This is in honor of a new VB language feature that has already been implemented, \"year-first date literals\".\n\n# 1. Improved XML doc-comments.\n*Approved. Already in Main. Parity with C#.*\nThese are now supported to the same extent as C#, e.g. crefs and paramrefs are parsed correctly by the language. (The IDE team also added a much richer IDE experience will full syntax colorization, quick-info and rename support.\n![Image](http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-06-codeplex/5353.xml.png)\n\n# 2. Comments after implicit line-contuations.\n*Approved. Already in Main. VB-specific.*\nComments are allowed after implicit line-continuation characters. Here are examples which failed to compile before, but now work:\n\n``` vb\nDim invites = {\"Jim\",   ' got to invite him!\n               \"Marcy\", ' Jim's wife\n               \"Jones\"}\n\nDim addrs = From i In invites     ' go through list\n            Let addr = Lookup(i)  ' look it up\n            Select i,addr\n```\n\n# 3. #Region anywhere\n* Approved. Already in Main. Parity with C#.*\n\n\"#Region\" is allowed within method bodies and can cross method bodies.\n\n``` vb\nFunction Range(min%, max%) As IEnumerable(Of Integer)\n    If min > max Then Throw New ArgumentException\n#Region \"validation\"\n    Return Helper(min, max)\nEnd Function\n\nPrivate Iterator Function Helper(min%, max%) As IEnumerable(Of Integer)\n#End Region\n    For i = min To max\n        Yield i\n    Next\nEnd Function\n```\n\n# 4. Implement readonly props with readwrite props.\n* Approved. Already in Main. Parity with C#.*\n\nThe following code used to give an error saying that C.p doesn't match I.p and hence can't implement it. But now it's okay. (Also, you can implement writeonly props with readonly props)\n\n``` vb\n    Interface I\n        ReadOnly Property p As Integer\n    End Interface\n\n    Class C : Implements I\n        Public Property p As Integer Implements I.p\n            Get\n            End Get\n            Set(value As Integer)\n            End Set\n        End Property\n    End Class\n```\n\n# 5. Overloads Overrides\n* Approved. Already in Main. Interop with C#.*\n\nPreviously, VB libraries had to write both modifiers \"Overrides Overloads\" to play nice with C# users. Now, \"Overrides\" members are also implicitly Overloads.\n\n\n# 6. Allow CObj in attributes\n* Approved. Already in Main. Parity with C#.*\n\nThe following code used to give an error that CObj(...) wasn't a constant. But it is, so we no longer give the error.\n``` vb\n   <DefaultValue(CObj(1))>\n```\n\n\n# 7. TypeOf IsNot\n* Approved. Already in Main. VB-specific.*\n\nYou used to have to write it the long way:\n``` vb\n   If Not TypeOf sender Is Button Then\n```\nNow you can write it more readably:\n``` vb\n   If TypeOf sender IsNot Button Then\n```\n\nYou could already use the \"IsNot\" operator previously, but only for reference comparisons e.g. \"If sender IsNot Nothing Then\"...\n\n\n# 8. Readonly autoprops\n* Approved, but design-questions remain. This has been prototyped. Aligns with C# vNext \"getter-only and initialized autoprops\" feature.*\n\nWe all know that we want this, but we don't know exactly what we want... Here’s an example:\n``` vb\n   ReadOnly Property p As Integer = 15\n   ReadOnly Property q As Integer\n\n   Sub New(q As Integer)\n      Me.q = q\n   End Sub\n```\n\nIt’s clear that “ReadOnly” means that the property itself only has a getter. That’s the only thing we’re agreed upon at the moment…\n\nOutstanding questions:\n1. Should the backing fields be visible in the designer, or hidden like they are now?\n2. Is the backing field ReadOnly like C#, or mutable like a current autoprop?\n3. Can you assign to a ReadOnly autoprop in the constructor (implicitly an assignment to the backing field) just like you can assign to a ReadOnly field in the constructor?\n\nNote1: The CLR allows an assignment-to-readonly instruction at any time, but it has no effect after the constructor has finished. The CLR allows assignment-to-readonly by reflection at any time.\n\nNote2: Why would you want to assign to a ReadOnly in the constructor rather than just in the property’s initializer? … Maybe it’s because you need some control-flow logic to figure out what to assign, e.g. a For loop. Maybe it’s because you assign based on arguments that were passed to the constructor – although this latter case is addressed by primary constructors.\n\nHere is some previous public feedback on the topic: http://blogs.msdn.com/b/lucian/archive/2010/01/30/core9-readonly-auto-properties.aspx\n\nHere are three mutually incompatible visions of the feature:\n\nPROPOSAL “A”: ReadOnly autoprop is like ReadOnly field. We are minimizing the code you need to type to get readonly properties.\nBacking field is hidden from intellisense, the backing field is ReadOnly, and you can assign to a ReadOnly autoprop in the constructor. (This is like C#’s current proposal, except C# proposal doesn’t allow assignment in the constructor).\n\nPROPOSAL “B”: ReadOnly autoprop is like existing autoprop but without setter. We are sticking closely to the status quo, not doing anything special.\nBacking field is hidden from intellisense, the backing field is ReadWrite, and you can’t assign to the autoprop in the constructor. (Note: this proposal is pretty weak unless there are primary constructors. Also, the existing VB snippets for readonly properties use mutable backing fields).\n\nPROPOSAL “C”: Backing fields should become first-class and well-known. They’re VB’s answer to “{get; private set}” from C#.\nBacking field is shown in intellisense, the backing field is ReadWrite, and you can’t assign to the autoprop in the constructor; but you can assign to the backing field.\n\n\nMVP feedback: Bill McCarthy, Jan Zaruba, Joacim Andersson, Klaus Loffelman all voted in favor of proposal “C”. No one voiced any other preferences. We have implemented proposal \"C\" in the preview, and are open to further feedback.\n\n\n# 9. International date literals\n* Approved. Already in prototype. VB-specific.*\n\nDesign is merely to offer ISO syntax for the range of things that are covered by existing date literals for DateTime (so: no timezone, no milliseconds, no DateTimeOffset). The format for dates is YYYY-MM-DD, and they must have the full number of digits.\n``` vb\n   Dim d = #2013-06-12#\n   Dim d = #2013-06-12 15:17:23#\n```\n\nQ0. What about the horrible hacks that Anthony discovered, about how the IDE compiler allows two-digit dates (but command-line doesn't), and … ???\n\nQ1. Do you allow #2014-02-04 24:00# as well as #2014-02-05 00:00# ?\nA1. The current DateTime constructor does not allow you to pass “24” for the hours. And the current VB literal doesn’t allow 24:00 as a time. So we should disallow this.\n\nQ2. Do these always produce a datetime with .Kind = DateTimeKind.Unspecified?\nA2. Yes, since current VB DateTime constants always do.\n\nQ3. Do we intend to come up with a solution for declaring an optional parameter with value “DateTime.MaxValue”? Currently you can’t, because “DateTime.MaxValue” isn’t a constant, and there’s no way to write DateTime.MaxValue in the VB datetime literal format.\nA3. No, no solution.\n\nQ4. Can we have the existing DateTime separators, or merely the ISO separator (-) ?\n\nQ5. Do we allow AM/PM or do we require 24 hour clock?\n\n\nPROPOSAL “A”. This feature is just \"existing DateTime literals but with four-digit year first\"\nQ4 = allow existing separators, Q5 = allow AM/PM\n\nPROPOSAL “B”: This feature is about unambiguous universal (hyphen, year-first) notation for the date which was the part that SUFFERED, but just use existing time syntax for the rest. (votes in favor: Aleksey, Klaus, Lucian)\nQ4 = require hyphen; Q5 = allow AM/PM\n\nPROPOSAL “C”: This feature is \"subset of ISO syntax for those things encompassed by current DateTime literals. (votes in favor: Neal, Dustin, Anthony) Everyone knows ISO syntax. They won’t need to stop to wonder whether #2010/10/11# means November 10th or October 11th (although there are no cultures in the world where it means November 10th).\nQ4 = require hyphen, Q5 = disallow AM/PM\n\nWe could also accept AM/PM, but (1) the prettylister prints into ISO format, and (2) we give a warning.\n\nRESOLUTION: proposal \"A\", based on discussion from 2014-02-04. Do you see what I did there? :)\n\n# 10. Digit group separators\n*Approved, but needs further language design decisions. Already in preview. Aligns with C# vNext feature \"digit grouping\"\n\nWe settled on spaces as separators per ISO recommendations, but C# preferred underscores (like Java), so we should revisit that difference.\n``` vb\n   Dim x = &B1110 0001 1010 1111\n   Dim x = &B1110_0001_1010_1111_SB\n```\n\nDesign: this is a token-level thing. You can’t have line-continuations (implicit or explicit). For spaces, we’d only allow a single space. Not sure what we’d do with underscores. You can put the separator anywhere you want, including after &H and &O and &B, except after the &.\n\nCurrent experimental prototype allows space, underscore and backtick. Note: old calculators in the 1970s used backticks! No one likes the backtick (apart from Klaus).\n\nPROPOSAL 1a: the only separator allowed is underscore.\n\nPROPOSAL 1b: allow both space and underscore.\n\nPROPOSAL 2: separator is allowed before the type suffix\n\nPROPOSAL 3: not allowed more than one underscore in a row\n\nOpen question: should you be allowed a separator before the numeric-type-suffix? E.g.\n   Dim x = &B 1110 S\n\n\n# 11. Binary literals\n*Approved. Already in preview. Aligns with C# vNext feature \"binary literals\" *\n\nIt will be nice for enum literals. F# has them. We would ask the debugger to consider displaying stuff in binary as well, but that’s lower priority.\n``` vb\n   Dim x = &B11100101\n```\n\nNote: Integer.TryParse is a language-neutral .NET Framework function, that should not be augmented just for sake of new language-syntax. So we wouldn't want to make it work with the above syntax.\n\n# 12. Multiline strings\n*Approved. Already in preview. Parity with C#. *\n\n``` vb\n   Dim x = \"Hello\n   World\"\n```\nWe will use the normal quotes. We are happy that the pretty-lister inserts them in pairs in Roslyn (so the remainder of the file doesn't blink on and off too much).\n\nNote: the pretty-lister should not auto-indent the next line when you press ENTER. (C# doesn't either)\n\nQ. Does a newline emit CRLF?\nA. It's whatever is in the source file. That's how C# works.\n\nWe allow any characters up until an unpaired \" (or all the other string-starting-and-closing quote characters are currently allowed).\n\nQ. Do we allow multiline string literals in preprocessor directives?\nA. No. Neither Roslyn nor Native allow implicit line continuations in preprocessor directives. (although they sadly allow explicit line continuations).\n\n\n# 12. Select Case Typeof\n*Approved, but needs further language design decisions. Already in preview. VB-specific.*\n\nAnthony's basic idea, which is in the preview:\n``` vb\nSelect Case sender\n   Case 3 : ...\n   Case < 4 : ...\n   Case As UIElement : ...   ' now works\n   Case b As Button : ...    ' now works\n   Case t As TextBlock: ... ' now works\n   Case As UIElement, As Integer : ...    ' okay in Design1\n   Case 3, As String : ...                ' okay in Design1\n   Case ex As Exception When ex.i<7 : ... ' not supported\n   Case c As Control, d As DropDown : ... ' error.\n   Case AsNot Integer: ...                ' not supported \nEnd Case\n```\n\nQuestions arising from the prototyping effort:\n* Value types\n* When clauses - Should they apply to each clause or each Case? Should they be generalized to any kind of Case clause? Should they be removed? Should we add a Continue Select as an alternative?\n\n**Design1**: \"As String\" is just a normal case, like the other cases in VB, and indeed you can combine them and jump into them. \"x As String\" is different: it must be the only condition on the Case line, and doesn't admit inbound jumps (similar to how For blocks don't admit inbound jumps). The scope of the variable declaration is just that case clause, and follows the same principles as other blocks which define variables like ForEach.\n``` vb\n   Case 3, As String : ...\n   Case b As Button : ...\n```\n\n**Design2**: both \"As String and \"x As String cannot be comma-combined with other case clauses, and neither admits inbound jumps. The motive is to safeguard a possible future use of comma in pattern-matching. (Unfortunate, since VB doesn't have \"case fall-through\", and so likes to use comma to combine cases).\n\n**Concern**: It feels like generics will be important. How to implement them though? Answer: this is impossible in the current CLR without reflection, and we wouldn’t want a language feature that depended on reflection. Therefore this scenario is out of consideration.\n``` vb\n   Case As IEnumerable(Of T) : fred(Of T)(Nothing)\n```\n\nConcern: We have to make sure that anything we support now will be compatible with a hypothetical future that allows richer pattern-matching. So let's design that hypothetical future right now even though we won't implement it. Pattern-matching is odd in a language without algebraic datatypes, because there's no inbuilt canonical way to decompose an object. Possibilities are (1) only do decomposition on types with primary constructors; (2) decompose based on property names; (3) like Scala a type has a canonical \"Unapply\" method which says how to decompose; it might be an extension method and might be overloaded by type or arity; (4) like F# have active patterns.\n\nIn our investigation of pattern-matching, we're heavily swayed by Martin Odersky's paper http://www.scala-lang.org/node/112\n\n\nAnthony's advanced idea:\n``` vb\nDim x = sender Matches Dim ui As UIElement When ui.Tag = \"a\"\n\nSelect Case sender\n   Case Matches Dim b As Button : ...\nEnd Select\n```\n\n```\nExpr ::= … | expr Matches M [when boolean-expr]\nM ::= * | Dim v | Dim v As T | MatchFunction(M, …)\n```\nScope: the scope of each introduced \"v\" is the containing statement. So, it works in \"If\" and \"Case\", but it doesn't help with \"Dim x = e Matches Dim v\"\n\nOPTION1: can we allow arbitrary Boolean expressions inside M? Still can't see it.\n\nOPTION2: can we remove \"Dim\", and make the parentheses on MatchFunction compulsory? i.e.\n```\nexpr ::= … | e match M1\nM1 ::= M2 [where Boolean-expr]\nM2 ::= * | Dim v | [Dim] v As T | MatchFunction(M1, …) \n```\nOPTION3: Should we also we also allow `M2 ::= … | v As MatchFunction(M1, …)`\n\n\n## TO RECAPTURE the basic question we're trying to address...\nHow difficult is it to match Tree(Leaf(2), Leaf(3))\n\n## OPEN QUESTIONS:\n\n(1) How exactly will MatchFunction bind? It would be nice to have a \"matcher\" object that we can dispatch on. It would be nice to dispatch on Integer.TryParse. Or maybe each active pattern should be explicitly indicated with an attribute (like extension methods).\n\n(2) The whole idea here is to match against the runtime type of expr. How does that even work when invoking MatchFunctions? Overload resolution? It suggests putting overload resolution into the late-binder, which we don't like.\n\n\n\n# 14. Await in Catch and Finally blocks\n*Approved. Aligns with C# vNext feature*\n\nWe'll leave the design work to C# LDM, and do exactly the same.\n\n\n# 15. Type inference for constructors of generic types.\n*Approved. Aligns with C# vNext feature*\n\n``` vb\n   Dim x As New List({1,2,3})\n   Dim x = New List({1,2,3})\n```\nWe'll use just the same semantics as C#.\n\nNote: it doesn't help common cases that I run into, e.g.\n``` vb\nFunction f() As Tuple(Of Integer, String)\n   If condition Then Return New Tuple(Nothing, Nothing)\n   Return New Tuple(5, \"hello\")\nEnd Function\n```\n\nBut it's better than nothing, and brings more regularity into the language.\n\n\n# 16. <field:attr> on autoprops\n*Approved. Aligns with C# vNext feature \"field target on autoprops\" *\n``` vb\n   <field:attr> property x As Integer\n   <field:attr> event e As Action\n```\nStylistic guidance will be to use <field:NonSerializable> on events even though the field target isn't needed. No further semantic design work needed.\n\n\n# 17. Allow scalar query expressions to clash names.\n*Approved. Parity with C#*\n\nThere are two parts of the approved design....\n``` vb\nDim args As String()\nDim q = From arg In args Select arg.ToString()\n' BC36606: Range variable name cannot match the name of a member of the 'Object' class\n```\n\nDesign1: Improve error message so it says “Inferred range variable name ‘ToString’ cannot conflict with blahblahblah”.\n\nDesign2: If the last Select is followed only by the innocuous clauses (Distinct, Skip, Take) and if the Select has only one item, then skip name generation entirely.\n\n# 18. Introduce \"Null\" literal\n* Rejected on 2014-01-06. It would have had parity with C# \"inference is aware of null\" feature. *\n\nHere is the problem statement:\n\n*“I don’t know what Nothing means.”* I wrote the following code, expecting that Nothing would mean a nullable integer, but it came back as the integer 0. \n``` vb\n10:   Dim x = If(False, 0, Nothing)\n```\n\n*“Nothing doesn’t mean what I think it means.”* I wrote the following code, expecting that by specifying the type, it would know to use a nullable nothing. But it didn’t.\n``` vb\n20:   Dim x As Integer? = If(True, 0, Nothing)\n```\n\n*“No one else knows what Nothing means.”* MSDN articles always say “Use null (Nothing in VB),” but that’s not really correct. Nothing is more like default(T), and VB lacks null.\n\n\n## PROPOSAL “B”: INTRODUCE NULL INTO THE LANGUAGE\nThe basic problem is that Nothing was a bad primitive from the get-go, and C#’s “null” was a better primitive. We should encourage people, as best-practice, to use “null”. It would work as follows.\n\nSyntax: if we are parsing an expression and encounter the simple name “Null” and it doesn’t bind to any namespace, type or variable, and doesn’t have qualification or indexing or dictionary-lookup operators after it, then treat it as “Null”.\n\nSemantics: Null is identical to Nothing, except for the following rules:\n\n1. It is an error to interpret Null in a context expecting a non-nullable value type. So, “Dim x As Integer = Null” is an error, but “Dim x As Integer? = Null” is okay.\n\n2. Even though Null has no inherent type of its own (i.e. Null doesn’t suggest its own type to dominant-type algorithm), nevertheless \"Dim x = Null\" infers type Object for x. This is similar to the existing rule that \"Dim x = Nothing\" infers Object even with Option Strict On.\n\n3. If the compiler needs to determine dominant-type-of-set-of-expressions, and one of those expressions is a naked Null literal, then when gathering the set of inherent types of all those expressions, replace each non-nullable-value-type candidate “T” with Nullable(Of T).\n\nExample: \"Dim x = If(b,5,Null)\" previously gathered only one inherent type \"Integer\" as a candidate for dominant-type-inference. From rule [3] it will instead gather “Integer?” as a candidate. Both expressions can be interpreted as Integer?, so that succeeds.\n\nExample: “Dim x = {1,2,Null}” previously gathered only one inherent type “Integer” as a candidate for dominant-type-inference. From rule [3] it will instead gather Integer? as a candidate, and it works.\n\nExample: “Dim x = {1, “hello”, Null}” previously gathered Integer and String as candidates. From rule [3] it will instead gather Integer?, String as candidates. There is no dominant type amongst these two, so it falls back to Warning: Object Inferred.\n\nExample: “Dim x = {1L, 2, Null}” previously gathered Integer and Long. From rule [3] it will gather Integer? and Long?. The dominant type amongst these two is Long?, which is what it will pick.\n\nIncidentally, the VB compiler up to VS2013 already recognizes syntactic “null” in the same way, in order to produce a special-case error:\n![Image](http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-06-codeplex/5481.null.png)\n\nWe did consider “Nothing?” instead of “Null”. That has the slight advantage that Nothing is already a reserved word in VB. However, it looks strange, and will leave people even more confused. We also considered “Nuffink” :) and rejected it -- it’s not all dour-faced diligence in the VB LDM!\n\n\n# 19. Smarter name resolution\n* Approved. Already in Main. VB-specific. *\n\nFull notes are recorded in the minutes of the VB LDM 2013-12-13. I haven't typed them up onto codeplex yet. If you want me to, please request them.\n\n``` vb\nImport NA     ' contains only the type NA.N1.T\nImport NB     ' contains only the type NB.N1.U\nDim x As N1.T ' let this resolve to NA.N1.T\n\nDim x As ComponentModel.INotifyPropertyChanged\n' In Console is okay, but in Winforms apps it is ambiguous\n' between System.ComponentModel and System.Windows.Forms.ComponentModel\n' Note: System.ComponentModel isn’t project-imported on most project types\n' so the full qualification might be expected.\n\nThreading.Thread.Sleep(1000)\n' In Console and Winforms this is okay, but in WPF aps it is ambiguous\n' between System.Threading and System.Windows.Threading\n' Note: System.Threading isn’t project-imported on most project types\n' so the full qualification might be expected.\n\nDim y As Xml.Linq.Xdocument\n' If you import System.Security.Cryptography, this becomes ambiguous\n' between System.Xml and System.Security.Cryptography.Xml\n' Note: System.Xml isn’t project-imported on phone/silverlight,\n' so the full qualification might be expected.\n\nDiagnostics.Debug.WriteLine()\n' In Silverlight/Phone this works, but in WinRT aps it is ambiguous\n' between System.Diagnostics and Windows.Foundation.Diagnostics\n' Note: System.Diagnostics isn’t project-imported on phone/silverlight,\n' so the full qualification might be expected.\n```\n\n# 20. Partial modules and interfaces\n* Approved. Aligns with C# vNext feature \"allow partial anywhere\" *\n``` vb\n   Partial Module Module1\n   End Module\n```\nPartial methods inside will be allowed; they will just drop out. We can't think of any design gotchas. This was a request from the Roslyn implementors.\n\n\n# 21. Params IEnumerable\n* Approved. Aligns with C# vNext feature. *\n\n``` vb\n   Sub f(ParamArray x As IEnumerable(Of Integer))\n```\nNo further design work needed.\n\n\n# 22. Private Protected.\n* Approved, but syntax needs to be settled. Aligns with C# vNext feature.*\n\nDesign option 1: like C#\n``` vb\n   Private Protected Sub f()\n\n   Friend Property p As T\n     Get\n     Private Protected Set\n   End Property\n```\n\nDesign option 2: not like C#, but it is conceptually cleaner. VB should naturally be more verbose where verbosity is actively useful.\n``` vb\n   Protected And Friend Sub f()\n\n   Friend Property p As T\n     Get\n     Protected Set\n       ' means anyone in the assembly can see it,\n       ' but only those who also derive can set it\n   End Property\n\n   Protected Property p As T\n     Get\n     Friend Set\n       ' means it's a protected property, but\n       ' only my assembly can set it\n   End Property\n```\n\nRESOLUTION: Please see meeting notes from 2014-03, where we opted for \"Design 3\". (I haven't typed up those notes yet. If you'd like to see them, let me know -- lwischik).\n\n\n# 23. TryCast for nullable value types\n* Approved. Parity with C#.*\n\nTryCast will allow a target type that's either Reference type or a nullable type. It will work exactly as in C#. Note that TryCast bypasses the latebinder.\n``` vb\n   Dim obj As Object = 1\n   Dim x = TryCast(obj,Integer?)\n```\n\n# 24. Override events\n* Approved in principle, but still needs design work. This is a parity issue for BCL and other frameworks*\n\nNote: it is CLS-compliant for the BCL to do this. The only CLS restrictions around “abstract” are with generics.\n\nCurrently C# lets you\n1.\tDefine an interface with an event. \n2.\tImplement the interface by providing that event\n3.\tDefine an abstract class with a MustOverride event\n4.\tInherit from that class and override the event\n5.\tDefine a class with an Overridable event\n6.\t(there’s a C# bug when you try to inherit from that class and override the event, but there are workarounds)\n\nVB lets you do (1) and (2). This means that VB users are shut out from any library which uses (3) or (5): VB users are unable to inherit from the class.\nIn .NET4, the BCL folk have changed a few classes to include MustOverride events. For instance, Inherits System.Windows.Documents.Serialization.SerializerWriter. The only VB workaround is mock-type injection voodoo. (e.g. also the VS Editor folks, writing in C#, had done this themselves).\n\nVB's lacuna was just an oversight.\n\nProposal at hand is (3) let you define an abstract class with MustOverride event, (4) let you inherit from that class and override the event, (5) let you define a class with an overridable event.\n\n\n# 25. Allow MyBase in structures\n* Approved, but low priority. VB-specific. *\n\nThe example is MyBase.GetHashCode(). It should behave like you'd expect, like C# does.\n\nNB. Structure \"GetHashCode\" finds the first instance field and calls GetHashCode on it, using reflection \n\n\n# 26. Allow delegates in object initializers\n* Approved in principle if C# goes ahead with the same feature, but needs further work on syntax*\n\n``` vb\nDim x As New C With {.Name = \"x\", .Notify += delegate}\nDim x As New C With {.Name = \"x\", AddHandler .Notify, delegate }\nDim x As New C With {.Name = \"x\", .Notify = delegate }\nDim x As New C With {.Name = \"x\", .Notify := delegate }\n```\n\nWe're not sure what syntax to use…\n+= is the C# syntax and resonates with our proposal to add += for delegates, even though the feature only allows you to sign up a single delegate\n= is the XAML syntax, and nice and short. If the constructor of C had already signed up a delegate, it'd be weird! It's also nice not to add new syntax.\n:= is the named-argument syntax\n\nNOTE: maybe there are problems to be solved at the same time for nested collection initializers, and of course lightweight-dynamic initialization. C# lets you use assignment for collection-initializers:\nvar x = new Order { .Items = {1,2,3} }\nThis gets the value of \"Items\" and then does a collection-initializer on it. We can't do this. But it shows there exists in C# a precedent where = really means Add.\n\n\n# 29. Allow With and From together\n* Approved, but low priority. VB-specific. *\n\nThis is just cleaning up the language. Design is that \"With\" comes first and \"From\" comes next.\n``` vb\n   Dim x As New List(Of Int) With {.Capacity=10} From {1,2}\n```\n\n# 30. Extern alias for assemblies\n* Undecided.*\n\nWe have a design doc for this, but it's a lot of work, and seems low-priority.\n\n# 31. Combine delegates with +=\n* Approved in principle, but need design work. Parity with C#. *\n\n``` vb\n   m_ClickEventHandler += value\n   m_ClickEventHandler -= handler\n```\nSemantics will be exactly as for C#. However we will not also allow \"event += value\" as a synonym for \"AddHandler event, value\".\n\nSTILL TO DO: figure out exact semantics for \"+\"\n``` vb\nm_ClickEventHandler = m_CLickEventHandler + value\n```\nSTILL TO DO: figure out (for this as for all new features) how much should make it into the late-binder?\n\n\n# 32. String interpolation\n* Undecided *\n\n``` vb\n   Dim x = $\"hello \\{e.Name}\"\n```\n\nWe have detailed notes from this from VB LDM 2013-12-09. It's a complicated topic. If you'd like me to type up the notes, let me know. -- lwischik\n\n\n\n# 42. Out parameters and implicit Out parameter declaration\n* Approved in principle, but needs design work. Aligns with C# \"out vars\" feature.*\n\n``` vb\n   ' Callsite:\n   If Integer.TryParse(s, Out [Dim] x [As Integer]) Then ...\n\n   ' Declaration-site:\n   Function TryParse(s As String, Out x As Integer) As Boolean\n```\n\nThe declaration-site will be emitted as <Out> Byref. However if you merely write <Out> Byref then it will be treated as a ByRef rather than as an Out, because the compiler doesn't generally crack attributes in source code.\n\nThe declaration method will default-initialize all Out parameters on entry (this can be optimized away by the compiler). Warnings will be emitted for both use-before-assign and return-without-assign.\n\nOn the callsite, for back-compat, you don't need an \"Out/Output\" keyword to match an out parameter. However, you do need the keyword in order to declare the variable inline, and if you use the keyword then it is an error to pass it something that's not an lvalue.\n\nOutstanding questions:\n\n* What should the scope of \"x\" be? C# LDM is also wrestling with this, and the answers are sometimes unexpected.\n\n* Should the pretty-lister insert \"Out\" as you type a function invocation?\n\n* Callsite syntax: should it be \"Out\" or \"Output\"? Should we use rules similar to the existing \"For\" where you don't need Dim, and instead a new variable is implicitly declared if there's an \"As\" clause or if it doesn't bind an existing name?\n\n* Is this synergy with \"For\" a step too far? Given that the scope of the out in statements will bleed outside. Shouldn't we help people avoid the dangerous situation?\n\n\n# 34. Declaration expressions\n* Rejected. This would have had parity with C# vNext feature. *\n\nThis is a generalization of Out Dim, to allow variables to be declared in any expression.\n\n``` vb\nConsole.WriteLine(Dim x As Integer = GetValue(), x + 2)\nConsole.WriteLine(x+1)\n\nIf (Dim c = TryCast(x, String)) IsNot Nothing Then ...\nvar z = (var x=LengthyGetX(); var y = LengthyGetY(); x*x+y*y);\n\nIf (Let c = TryCast(x, String) in c) IsNot Nothing Then\n\nvar z = Let x = LengthGetX()\n        Let y = LengthyGetY()\n        Returns x*x + y*y\n\nIf (Let c = TryCast(x,String)) IsNot Nothing\n\nvar z = Let x = LengthGetX()\n        Let y = x+LengthyGetY()\n        Select x*x + y*y ' DO NOT want x to escape scope\n```\n\n\"Select\"? Yield? Returns? In?\n\n``` vb\nvar z = Let x = LengthGetX(),\n        y = x+LengthyGetY()\n        Yield x*x + y*y ' DO NOT want x to escape scope\n\nInteger.TryParse(\"15\", Out x)\nConsole.WriteLine(x) ' REALLY DO WANT x to escape scope\n```\n\nC# is using the same mechanism for both \"out vars\" and the \"let\" construct. Maybe that's why C# scope isn't always obvious?\n\nQ. Does the keyword \"Let\" cause ambiguities if we're using this inside query expressions? Note that \"Let\" is bad for query expressions.\n\nNote: one thing that makes sense for C# is that C# already allowed assignment into expressions, and so assigning to a new-variable is a sensible extension. But VB has never allowed assignment in expressions, so it doesn't naturally go that far.\n\nRESOLUTION: None of this feels naturally \"VB\"ish. We're happy if VB sticks merely to Out parameters and implicit declaration of Out arguments.\n\n\n# 35. Expression sequences\n* Rejected. Would have had parity with C# vNext feature. *\n\nThe C# goal is to allow multiple expressions. \"An expression can be of the form (expr1; expr2; expr3) which has the end result \"expr3\" but it evaluates (and discards) the preceding expressions in the list.\"\n\nVB proposal:\n``` vb\nDim x = (Console.WriteLine(\"log\") : 15)\nDim x = Do Console.WriteLine(\"log\") In 15\n```\nan expression can have the form \"Do statementlist In expr\" which has the end result \"expr\" but it performs the preceding statementlist first.\n\n``` vb\nDim z = Do Dim x = sideeffect() : Dim y = sideeffect() In x+y\n\nDim z = Do\n                 Dim x = sideeffects()\n           In 15\n\nDim x = Function()\n                 Console.WriteLine(\"log\") : Return 15\n              End Function.Invoke()\n```\n\nRESOLUTION: If we don't have declaration expressions, then there's little value in expression-sequences. It might make sense to combine the two into a \"Let\" operator, but that doesn't feel very VBish.\n\n# 37. Implicit Interfaces\n* Tentatively approved, but still needs design work. Parity with C#. *\n\nOne typical scenario for it is code-generators and partial classes.\n\n``` vb\nClass C : implements IDisposable\n   Sub Dispose() : End Sub\nEnd Class\n```\n\nProposal is to allow you to avoid use of \"Implements\" keyword. Note that C# also lets inherited members implement interface members. We might not do the same.\n\nBut would there be breaking changes? … yes if the base case implements stuff. Here's the example:\n\n``` vb\nClass A\n   Sub Dispose() : End Sub\nEnd Class\n\nClass B : Implements IDisposable\n   Sub Dispose() Implements IDisposable.Dispose\n   End Sub\nEnd Class\n\nClass C : Inherits B : Implements IDisposable\n   ' Q. does C implement IDisposable.Dispose over again, or rely on base class?\n  ' Currently works fine, relying on B's implementation of IDisposable\n  Sub Dispose() : End Sub\nEnd Class\n\nClass D  : Inherits A : Implements IDisposable\n   ' Q. Does C implement IDisposable.Dispose via the base class, or not?\n   ' Currently an error\nEnd Class\n\nClass E : Inherits B : Implements IDisposable\n  Sub Dispose() : End Sub\n   ' Q. does E implement IDisposable.Dispose via its method, or rely on base class?\n  ' Currently works fine, but it does NOT use E's \"dispose\" to implement the interface\nEnd Class\n```\n\nProposal1: If existing VB fails to come up with a method that implements the interface member, THEN we look for an implicit implementation of it. (Worry: if someone modifies the base class to now implement the interface method, then the derived class will no longer be implicitly implementing it. But note that it's already the case that base-class-authors can do a whole load of things that mess up your code.) If something gets hijacked, then give a warning.\n\nProblem: principle is that \"adding interface-implementation to a base case should not be a breaking change\". The above proposal would violate this principle. (Actually, the principle isn't fully upheld already. Consider a class \"X\"\n``` vb\nSub f(dummy As Y) ' X has a narrowing conversion to Y\nSub f(dummy As I)\n```\nIn the first release, it would implicitly pick the first overload. But if someone now changes X to implement I, then it would pick a different overload. So we don't believe that the principle is fully upheld. Maybe the principle is a smaller one. \"If a new interface is added, and an existing class is changed to implement that interface, then it won't be a breaking change\".\n\n\nNB. Here's a \"bridge-method\" oddity:\n``` vb\nclass B { public void Dispose(); }\nclass C : B, IDisposable {}\n// in C#, the CLR likes interface implementations to be virtual, so C# compiler creates a bridge method.\n```\n\nProposal2: we'll look up implicitly by name, and always prefer the most derived type. But we'll add a warning when you would be hijacking code that already compiles. It's a warning, one that won't arise in typical case. (Note: you'd already have had to use Overloads/Shadows)\nExample:\n``` c#\nclass A : IDisposable { Dispose }\nclass B : A {Dispose}\nClass C : B, IDisposable {}\n```\nThis code currently works, and does not hijack.\nProposal would change it so that C emits a warning and picks up the new one.\n\n\nProposal3: use new syntax, and copy the feature wholesale from C#.\n``` vb\nClass B\n   Implicitly Implements I1\n   Auto Implements I2 \n   Implicitly I3\n   Implicit I4\nEnd Class\n```\n' As with C#, it will use explicit implements if they're present, and if absent then it will start looking in the most derived type. Hijacking will be impossible. NB. Vladimir points out that the C# implementation doesn't quite match the C# spec.\n\nRESOLUTION: Yes. Use Proposal3. We will look for a keyword combination that seems nice.\n\nNote: it's a weird situation that the more desirable syntax \"Implicitly Implements\" is more verbose than the less desirable traditional syntax \"Implements\". There may be IDE codespit ameliorations.\n\nNB. Like in C#, a single method can implement the same named member from multiple interfaces. (currently can with the Implements keyword).\n\nQ. How discoverable will it be?\n\nQ. Currently VB requires explicit interface implementation to have exactly the same optional parameter defaults. Should we adopt C# rules here? or VB? Note that C# came from a history that the camel's nose was already in the tent. Oh, and what if there are multiple interfaces with different default values?\n\nRESOLUTION: Stick with current VB rules, and if they complain, we can look into it then. And refactoring makes C# a bit dangerous. Note: we should match based on signature, and then give an error if the defaults don't match.\n\n\n# 38. GetName operator\n* Tentatively approved, but there are design issues. Parity with C# vNext \"nameof\" feature. *\n\nHere are some sketch syntaxes we played around with...\n\n``` vb\nDim name = nameof(Point.X)\nDim name = GetName(Point.X(Of ,).Y)  ' we prefer GetName\n\nDIm name = nameof(System.Action)\n\nDim TextProperty As DependencyProperty = DependencyProperty.Register(GetName(Text), GetType(String), GetType(MyClass))\n\nPublic Property Text As String\n   Get\n     Return CStr(GetValue(TextProperty))\n   End Get\n   Set\n      SetValue(TextProperty)\n   End Set\nEnd Property\n\nSub f(x As String)\n   If x Is Nothing Then Throw New ArgumentException(GetName(x))\nEnd Sub\n```\n\nThe C# proposal is straightforward: the argument to nameof is an (optional type-or-namespace-followed-by-dot) and then an identifier. The result is the string of that identifier.\n\nIn VB we prefer \"GetName\" to \"NameOf\".\n\n\nQ. Will it return the casing as you passed it to GetName, or will it return the casing as defined in metadata? What if there are two different casings in metadata? What if there are two different casings in metadata and they disagree with the argument to GetName? - Answer: it's an error. You'll have to fall back to a string literal.\n\nQ. In VB can we refer to the constructor \"New\"? - No, there's never any need for it.\n\nQ. Can \"Point\" be ambiguous? What if \"Point\" is a namespace, and member \"X\" exists in multiple modules inside that namespace?\n\nProposal1: \"Point\" (the prefix) must be unambiguous, but it's fine for \"X\" to refer to a method-group or a property-group or a unique thing. This is the current name lookup rules.\n\nQ. Should we allow unbound generic types, similar to GetType?\nA. Yes.\n\nQ. Can we use type keywords like \"Integer\" and \"Boolean\"? (same question for C#).\n\nQ. If we GetName() on an alias, does it refer to the underlying metadata name? Presumably yes! \n\n\nGENERAL FEEDBACK: Concern from Aleksey and IDE team about overloads and dealing with ambiguity. E.g. when you do find-all-references, or rename-refactor on an overloaded thing, then it's not clear which of the overloads \"nameof(...)\" operator is referring to (hence not clear whether it should be renamed). And the Roslyn APIs that return reference-counts -- how should they deal with it?\n\nTWO WAYS TO SPEC THIS:\n(1) GetName( BLARGH . Identifier ) where GetType(BLARGH) is valid\n(2) GetName( current name lookup rules ) and the name lookup must be successful. (but need it also be unambiguous?)\n\n\n# 39. Extension statics\n\nThis topic has been discussed offline. Let me (lwischik) know if you'd like me to type up the notes.\n\n# 40. Expression-bodied function members\n* Rejected. Would have had parity with C# vNext feature.*\n\nIn C# it'll look like this:\n``` csharp\npublic int R => Math.Sqrt(X*X + Y*Y);  // readonly autoprop\nint M(int i) => i+1;  // methods\nstatic operator int(C x) => (int)x.field; // conversions\nstatic operator +(C x,C y) => new C(x.field + y.field);\n```\n\nC#: all of these things are expressions, but statement-expression is a kind of expression, so they allow all statement-expressions as well (including void-returning statement expressions).\n\nIs there anything to do in VB?\n\nVB single-line lambdas:\n``` vb\n   Dim x = Function(y) y+15\n   Dim z = Sub(y) Console.WriteLine(y)\n\nClass C\n  Public Square(x As Integer) x*x\nEnd Class\n```\n\nProposal 1: allow more things on a single line... We're already part way there (Roslyn now no longer requires \"End\" to start a line). It just requires allowing Sub() and other things to have a colon following them.\n\n``` vb\n   Dim lambda = Sub() : Return 5 : End Sub\n   Sub method() : Console.WriteLine(\"oops\") : End Sub\n   Property p As Integer\n     Get : Return _p : End Get\n     Set : _p = value : End Set\n   End Property\n```\n\n(Q. are there any ambiguities between multiline lambdas inside methods? Follow-up with Tomas/Anthony for more…)\n\n\nProposal 2: Invent a special-case syntax single-line functions, methods, operators and readonly autoprops.\n``` vb\n  Function f() As Integer : Return 15\n  Sub g() : Console.WriteLine(\"hello\")\n  Sub ToDo() : Throw New NotImplementedException()\n  Shared Operator +(x As C, y As C) As Integer : Return x.i + y.i\n  ReadOnly Property p As Integer : Return 5\n```\n* Note: this prevents Proposal1, which is a bit of a shame! Unless you come up with the rule that \"End Sub\" is optional, like ; is in javascript.\n\nQ. What if I put three statements? would I still need \"end sub\" ?\n``` vb\n   Sub g2() : x=15 : y=17\n       Console.WriteLine(x+y) \n\n  Function f() As Integer = 15\n  Sub g() = Console.WriteLine(\"hello\")\n  Shared Operator +(x As C, y As C) As Integer = x.i + y.i\n  ReadOnly Property p As Integer = 5  ' doesn't work\n\n  Function f() As Integer := 15\n  Sub g() := Console.WriteLine(\"hello\")\n  Shared Operator +(x As C, y As C) As Integer := x.i + y.i\n  ReadOnly Property p As Integer := 5\n\n  Function f() As Integer 15\n  Sub g() Console.WriteLine(\"hello\")\n  Shared Operator +(x As C, y As C) As Integer x.i + y.i\n  ReadOnly Property p As Integer 5\n\n  Function f() As Integer Return 15\n  Sub g() Console.WriteLine(\"hello\")\n  Shared Operator +(x As C, y As C) As Integer Return x.i + y.i\n  ReadOnly Property p As Integer Return 5\n```\n   \n\nProposal 3: Only solve it for autoprops, but use a new keyword:\n``` vb\n  Computed Property p As Integer = x\n```\n\n* This looks confusing! It looks more complicated than what it's actually doing.\n* REJECTED proposal 3.\n\n\nVB already has\n``` vb\n   Property p As Integer = GetFoo() + 17  ' this is done at initialization-time\n```\n\n\nRESOLUTION: We're proud not to do anything. None of the proposals buy that much, and none are that special.\n\n\n# 41. Primary constructors.\n* Rejected for VB. Would have had parity with C# vNext feature. *\n\nThe notes are offline. Let me (lwischik) know if you'd like me to type them up.\n\n\n# 43. Literal type suffixes for Byte and SByte.\n* Approved.*\n\n``` vb\nDim x = 15L\nDim x = &HFACEL\n```\n\nLiterals are NOT target-typed in VB. They are integers (unless with type suffix).\n\nByte is the only numeric type in VB which lacks a suffix. The reason it lacks it is because the obvious choice \"B\" is already taken by hex digit.\n\nByte is unusual - it's the only numeric type where the default is \"unsigned\". e.g. \"Integer\" means \"Signed Integer\" but \"Byte\" means \"Unsigned Byte\".\n\nRESOLUTION: yes. Use \"SB\" and \"UB\". That will avoid the confusion of the previous paragraph. (other contenders were \"Y and SY\" like F#, or \"Y and UY\").\n\n\nQ. Can you write \"Dim x As Integer = &H00000000000000000000FACE ?\nLikewise can you write \"Dim x = &H0FUB\"\n\nQ. Can you have extra \"1\"s? e.g. Dim x As Signed Byte = &B111111111111110 SB ? The point is that leading 1s are not significant for signed binaries. \n\nSuspect the current rule is \"any leading bits you specify had better be zero\". That's a decent enough rule. We could get even more strict (\"don't have more leading zeros\") but that would be inconsistent.\n\n\nThis feature was triggered by a request of MVP Bill McCarthy, who wrote:\n\nSo If I want to force a binary number to Int16, I can use the type suffix:\n``` vb\n   Dim i As Int16 = &B 1000 0000 0000 0000S\n```\n\nWithout the S this would fail as the literal would be an overflow for Int16.  First off, I think it would be nice if the S could be spaced, eg:\n``` vb\n   Dim i As Int16 = &B 1000 0000 0000 0000 S\n```\n\nAnd it'd be nice if there was an error correction suggestion that suggested the S suffix.\n\nAnd finally, for signed bytes, could we perhaps have a SB suffix, eg:\n``` vb\n   Const  b as SByte = &B 1000 0000 SB\n```\n\nThe following workaround just doesn't do it for me:\n``` vb\n   Const b As SByte = CSByte(&B 1111 1111 1000 0000S)\n```\n\nMVP Cory Smith wrote:\nI do agree that if you specify the  SByte, it should attempt to do the appropriate conversion without requiring the following:\n``` vb\n   Dim s As SByte = CSByte(&B00010001)\n```\n\nEspecially if this works:\n``` vb\n   Dim b As Byte = &B00010001\n```\n\nHere’s another option:\n``` vb\n   Dim s As SByte = 1\n```\n\nThis works as well, so shouldn't any string literal work?  I'm just guessing that this was missed somewhere along the way and is an unintended bug in the current implementation.  My expectation would be that the implicit conversions for any literal would work like any other literal whether it is a number or a &B.\n\n# 44. Dictionary member initializers\n* Under discussion. Parity with C# vNext feature.\n\n\nCurrently VB lets you write dictionary-lookup expressions\n``` vb\n   Dim x = y!name   ’ becomes this C# thing y[“name”]\n```\n\nC# is considering the following:\n``` cs\nvar expr = new Exception(\"oops\");\nvar x = new JSON{\n     $foo = 15,\n     [\"bar\"] = 17,\n     [expr] = 9 }\n```\n\nProposal is to allow such things in VB object initializers. Here are possibilities...\n``` vb\n1: Dim x = New C With { .member = \"hello\" } ' existing members\n2: Dim x = New C With { !name = “hello” }  ' dictionaries\n\n3: Dim x = New C With { (expr) = \"hello\" } ' dictionaries\n4: Dim x = New C With { !(expr) = \"hello\" } ' a bit goofy? only consider this if second form turns out ambiguous\n5: Dim x = New C With { .(expr) = \"hello\" }\n\n6: Dim x = New C With { .Item(3) = \"hello\" } ' It's what you'd write if it were in a With block.\n\nDim $temp = new C\n$temp(\"name\") = ...\n$temp(expr) = ...\n```\n\nOption 4:  ! means default-property-access always. We could backport ! to generally mean \"default property access\" everywhere, including expressions and With blocks.\n\nCON4: !x=3 and !(x)=3 now mean different things\n\nPRO: People ask for a way to indicate indexing rather than invocation. They've often asked for []\n\nOption 3: we currently have a.member, a!name, a(index) so everything that comes after the \"a\" is valid also inside the initializer. NB. requires the thing to be an LVALUE, i.e. no xml-members, no invocation.\n\nCON: Can't use this in a With block on the right hand side, e.g. \"With d : Dim a = .y : Dim b = (z) : End With\"\n\nOption 5: We are omitting the default property name.\n\n\nRESOLUTION: We like 1, 2 and 4.\nRESOLUTION: 6 is also fine, for uniformity, but is lower priority.\n\n\n\nQ. Should we allow .$ as an alias for ! in VB?\nA. No. Let's leave it to the intellisense to help people find it\n\n\n\n# 46. Dictionary literals\n* Haven't got to this. Don't think it's worth it.*\n\nCurrently VB has excellent support for array literals. But people want dictionary literals, and are forced to use anonymous-types with reflection. For instance, they write\n\n``` vb\n   InitializeMvc(New With { .arg1=“hello”, .arg2=“world”})\n   Dim s = “hello \\{name}”.Format(New With {.name=“fred”})\n```\n\nThe first example is a typical MVC idiom, where anonymous types are used instead of named arguments, for cases where named arguments aren’t flexible enough. The second example is similar how Python does string interpolation. Both cases require reflection to get at the members of the anonymous object, which is a pain.\n\nLook at how array literals work...\n``` vb\nSub f(Of T)(x As IEnumerable(Of T))\nf( {1,2,3} ) ' today this picks up Integer as a hint for T\n```\n\nProposal is to allow a new form of dictionary literal:\n``` vb\n   Dim x = New With { arg1 := “hello”, arg2 := “world”}\n```\n\nTypical scenario is, as above, where the keys of the dictionary are strings that should be compared with the normal InvariantCulture comparison (since they’re used like parameter names rather than human-language strings). It’s not clear however what the type of the dictionary should be, and how it will work with type inference. For instance,\n\n``` vb\n   Sub f(x As Dictionary(Of String, Object))\n   ...\n   Dim y = New With { arg1 := 1, arg2 := 2 }\n   f(New With { arg1 := 1, arg2 := 2 })\n```\n\nWe’d expect “y” to be inferred as Dictionary(Of String,Integer) or IDictionary or ReadOnlyDictionary or something like that. However, we’d expect the call to “f” to be compatible with the parameter type.\n\nHere are some sketched syntaxes to see if they look any good...\n\n``` vb\nDim x = New With { arg1 := \"hello\" }\nDim x = { arg1 := \"hello\" }\nDim x = { (1+2) := \"hello\" }\nDim x = { arg1 = \"hello\" }\nWith fred\n   Dim x = { !arg1 = \"hello\" }\nEnd With\n\nInitializeMvc( { !arg1 := \"hello\", … } )\n```\n\nQ. If we have dictionary literals, what would they generate?\n\nA. If type context implements IDictionary<U,V> then use U for key and V for value, otherwise infer from dominant type of expressions - all like we do with array literals.\n\nQ. What is the compile-time type of the dictionary-literal expression?\nA. IDictionary<U,V>\n\nQ. What is the run-time type of it?\nA. Dictionary<U,V>\n\n\n# 46. Fix the ternary If operator\n* Under consideration. \n\nThe basic problem is that when people see a ternary If operator with a type context\n``` vb\n   Dim x As Integer? = If(True, 0, Nothing)\n```\nthen they expect it to mean this:\n``` vb\n   Dim x As Integer? : If True Then x = 0 Else x = Nothing\n```\nProposal is that we should fix this for them as follows. When interpreting If(x,y,z) in a context in which the desired type is known, then interpret both y and z in the context of that type.\n\nNote that it will be a breaking change. We decided in LDMs in years past that this would nevertheless be good for the language.\n\nWe must seek wider input on what people think about this. Once Roslyn goes open-source, it'll be great to open up to general public feedback.\n\n\n# 47. More nullable support\n* Approved. VB-specific. Completes the nullable story.\n\n``` vb\nDim y = CInt?(5)\n```\n\nThe issue is about Intrinsic nullable conversion operators (e.g. CInt?(<expression>))\n\nShould we add them? If so, what does `CInt?(5)` mean?\n\nProposal 1: `If(<a string> Is Nothing, Nothing, CInt(<a string>)`\nProposal 2: `If(Integer.TryParse(<a string>, result), result, Nothing)?`\nProposal 3: `CType(s, Integer?)`\n\nRESOLUTION: Yes, proposal 3.\n\n\n# 50. Allow As clause on Select clause range variables.\n* Under consideration. VB-specific.\n\nProposal: allow an “As Clause” on query Select clause range variable declarations. Maybe also on Anonymous-type member declarations too.\n\nFor example,\n``` vb\nDim x = From y As String In list\n               Let q As Integer = foo()\n               Select x As String = foo()\n```\n\nCurrently you can specify \"As\" in Let clause, and it does an implicit conversion.\n\nPROPOSAL: allow you to specify \"As\" in Select when introducing a new variable (\"range variable\") with an initializer.\n\nQ. Can you use it after Aggregate? after GroupBy?\n\nRESOLUTION: Anthony will flesh out the other LINQ places where As would go.\n\n\n# 51. More implicit line continuations\n* Still under design. VB-specific.\n\nProposal: allow implicit line-continuations in these places:\n* Before “Then” in If … Then statements\n* Before “Implements” and “Handles” clauses\n* Others?\n\nHere are some examples...\n\n``` vb\nIf x\nThen Return 15\n\nIf x\nThen\n   Return 15\nEnd If\n\nIf x AndAlso\n   y AndAlso\n   z\nThen\n  Return 15\nEnd If\n```\n\nWe generally like the implicit LC before the Then token. The prettylister would put \"Then\" aligned with the \"If\" and \"EndIf\".  But if you omit the Then token (an omission only allowed with multiline ifs), then what? ...? Needs more investigation.\n\n\n# 52. Allow Handles to be combined with Implements\n* Not yet considered\n\n\n# 53. Negative binary literals\n* Not yet considered\n\nProposal: If the type of the literal is a signed and has all bits explicitly specified we can create a negative number just like we do for hex literals today so\n``` vb\n&B 1000 0000 SB = -128\n```\n\n\n# 54. ?. operator, which does null-check before proceeding\n* Approved, but needs more design-work\n\nWe want to write\n``` vb\n  Dim x = customer?.Name\n```\nwhich would mean something like\n``` vb\n   Dim x As String = If(customer Is Nothing, Nothing, customer.Name)\n```\nexcept it would put \"customer\" into a temporary variable (to avoid evaluating it twice, and to avoid race conditions)\n\n\nThis is a huge topic. I will write up a separate set of notes. There is big debate about what happens if you have several things in sequence, e.g.\n``` vb\nDim x = customer?.Name.Length\n```\n\nProposal1: If you used ?. somewhere in the sequence, then you *MUST* continue to use it for every subsequent dot, otherwise it's a compile-time error. This boils down to ?. being a LEFT-ASSOCIATIVE operator, with everything that entails.\n\nProposal2: In the above example, you are allowed to write \"Name.Length\", with the intended meaning that you the programmer KNOW that if customer is non-null then (because of invariants in your code) you know that customer.Name is also non-null, and you wish to avoid the runtime cost of doing a null-check on it. This boils down to ?. being a RIGHT-ASSOCIATIVE operator, with everything that entails.\n\n\nWe also in VB expect to allow `x?(y)` which does a null-check on x prior to indexing or invoking it. (C# would only `x?[y]` or `x?.Invoke()` -- it would not allow `x?()` for conditionally invoking delegates).\n\n\nQ. Which language operators should have \"null-checking\" versions of them? We've already seen the null-checking member-access operator `x?.y` and the null-checking indexing-or-invoking operator `x?(y)`. Are there any others?\n\nWe had wondered if there is ever need for a null-checking conversion operator, i.e. one that does a null-check prior to doing the conversion. Normally it's not needed, since users who write their own user-defined-conversions can roll the null-check into those. So the question is whether it's needed for intrinsic conversions. The only intrinsic conversion that might benefit from a null-check is `Integer? -> String`. This is the only intrinsic conversion which can throw a NullReferenceException.\n\nPROPOSAL 1: Allow null-checking conversion operator, for this one case.\n\nPROPOSAL 2: Change behavior of `Integer? -> String` intrinsic conversion, so it gives you an empty string if the input is null.\n\nRESOLUTION: Rejected proposal 1 because it's too niche. Proposal 2 is decent, but low priority.\n\n\n---\n---\n\nOn Apr 4, 2014 at 5:16 PM @AdamSpeight2008 wrote:\n\nRe: __46. Dictionary literals__\n\nInstead of a Dictionary literal, I think it could be better to implement a Key-Value Pair literal instead.  (Think JSON)\nA Key-Value Pair Literal  ```{ \"A\" : 1 }```  \nThis re utilises the Expression / Statement Continuation Character in VB.net and Array Literals.\n\nIn C#  ```:``` is only used in _(as far I can tell)_\n\n```\n cond ? trueExpr : falseExpr  ' Inline IF\n class B : A                  ' Inheritance\n```\n\nboth of which are contextually different so I can't see another contextual definition being a problem.\n\nThis would in essence make a Dictionary Literal just a collection of Key-Value Pairs. Eg\n\n```vb\nDim myDict = { { \"A\" : 1 } , {\"B\" : 2 } , { \"C\" : 3 } }\n```\n\nIs then translated into the following code.\n```\nDim myDict As New Dictionary(Of String, Integer)(  { ( \"A\" : 1 ) , ( \"B\" : 2 ) , ( \"C\" : 3 ) } \n```\n\nThis then only needs a overload for the constructor that takes an ```IEnumerable(Of IKeyValuePair(Of K, V))```.\n\nThe compiler could also check at compile-time that the dictionary initialisation is valid. Eg Are the Keys Unique.\n\n---\n\nOn May 14, 2014 at 9:51 PM @AdamSpeight2008 wrote:\n\nAllow ```With``` on the ```Case Else``` clause\nwould permit the following style of coding\n\n```vb\n            Select Case flags \n              Case CharFlags.White       : ' stay in FollowingWhite\n              Case CharFlags.CR          : state = AccumulatorState.CR\n              Case CharFlags.LF          : state = AccumulatorState.Done\n                                           terminatorLength = 1\n                                           Exit While\n              Case Else When (flags And (CharFlags.Complex Or CharFlags.IdentOnly)) <> 0\n                                         : state = AccumulatorState.Bad\n                                           Exit While\n              Case Else                  : state = AccumulatorState.Done\n                                           Exit While\n            End Select\n```\n\nrather than current (less elegant work around)\n```vb\n            Select Case flags \n              Case CharFlags.White       : ' stay in FollowingWhite\n              Case CharFlags.CR          : state = AccumulatorState.CR\n              Case CharFlags.LF          : state = AccumulatorState.Done\n                                           terminatorLength = 1\n                                           Exit While\n              Case Else\n                 If (flags And (CharFlags.Complex Or CharFlags.IdentOnly)) <> 0 Then\n                    state = AccumulatorState.Bad\n                    Exit While\n                 End If\n                 state = AccumulatorState.Done\n                 Exit While\n            End Select\n```\n\nAlso allow the ```When``` to the preceded with an implicit line continuation. So that if can be placed /  aligned underneath the relevant ```Case``` clause.\nThis will improve the readability and formatting.\n\n```vb\n              Select Case baseCorTypeId \n                Case SpecialType.System_Enum                                   :  result = TypeKind.Enum ' Enum\n                Case SpecialType.System_MulticastDelegate                      :  result = TypeKind.Delegate   ' Delegate\n                Case SpecialType.System_Delegate\n                  When Me.SpecialType <> SpecialType.System_MulticastDelegate  :  result = TypeKind.Delegate ' Delegate\n                Case SpecialType.System_ValueType\n                   When Me.SpecialType <> SpecialType.System_Enum              :  result = TypeKind.Structure ' Struct \n                Case baseCorTypeId\n                    When Me.Arity = 0 AndAlso\n                         Me.ContainingType Is Nothing AndAlso\n                         ContainingPEModule.Module.HasAttribute(Me.m_Handle, AttributeDescription.StandardModuleAttribute)\n                                                                               :  result = TypeKind.Module\n              End Select \n```\n\n_Note: The code is from my roslyn fork_\n\n---\n\nOn May 17, 2014 at 1:51 PM @AdamSpeight2008 wrote:\n\nThe ```When``` clause should bind to each ```caseClause``` and not the entire collection of ```caseClause``` of that ```caseStatement```\n\n__Composition__\n``` \n Case  caseClause_1 , caseClause_2   When BoolExpr   :  caseActionExpr\n      | caseClause | | caseClause | | whenClause  |    |              |\n      +------------+ +------------+-+-------------+    +--------------+\n                     | caseClauseWithCondition    |\n                     +----------------------------+\n|----------------------------------------------------------------------|\n| caseStatement                                                        |\n+----------------------------------------------------------------------+\n\n```\n\n__Usage example__\n\n```vb\nSelect Case x\n  Case Is < 0  : Throw someException\n  Case 0 When a_Cond,\n       1 When b_Cond     : Return \"Result A\" \n  Case 2 When a_Cond     : Return \"Result B\"\n  Case Else When b_Cond  : Return \"Result C\"\n  Case Else\n    Return \"Other\"\nEnd Select\n\nEnd Select\n```\n\nwould be functionally equivalent to the following ```If ... ElseIf ... Else ... End If``` construct \n```\nIf ( x = 0 ) Then\n  Throw SomeException\nElseIf ( (x = 0) AndAlso ( a_cond ) ) OrElse\n       ( (x = 1) AndAlso ( b_cond ) ) Then\n  Return \"Result A\"\nElseIf ( (x = 0) AndAlso ( a_cond ) ) Then\n  Return \"Result B\"\nElse\n  If ( b_cond ) Then\n    Return \"Result C\"\n  Else \n    Return \"Other\"\n  End If\nEnd If\n```\n\n---\n\n"
  },
  {
    "path": "meetings/2014/LDM-2014-03-12.md",
    "content": "# ProtectedAndFriend, ProtectedOrFriend\n\n## BACKGROUND\n\nThe CLI includes two access modifiers \"FamilyAndAssembly\" (which allows access to derived types that are in the same assembly) and \"FamilyOrAssembly\" (which allows access to types if they are derived, and also allows access to types if they are in the same assembly). The concepts are explained well here: http://stackoverflow.com/questions/22856215/what-is-the-meaning-of-the-planned-private-protected-c-sharp-access-modifier\n\n## REQUEST\nVB and C# already have syntax for FamilyOrAssembly (\"Protected Friend\"). Please add syntax to allow VB to express FamilyAndAssembly.\n\n## RESOLUTION\nVB will add two new access modifiers, which are exact transliterations of the CLI keywords...\n\n``` vb\nProtectedAndFriend\nProtectedOrFriend\n```\n\nThe pretty-lister will not turn \"Protected Friend\" into \"ProtectedOrFriend\". However, if the user types \"private protected\" (or whatever syntax C# chooses) then it will pretty-list the entire file into C#. JOKE. No it won't. But it may pretty-list the C# syntax into \"ProtectedAndFriend\".\n\nHere are some code samples:\n\n``` vb\n   ProtectedAndFriend Sub f()\n\n   Friend Property p As T\n     Get\n     Protected Set\n       ' means anyone in the assembly can see it,\n       ' but only those who also derive can set it\n   End Property\n\n   Protected Property p As T\n     Get\n     Friend Set\n       ' means it's a protected property, but\n       ' only my assembly can set it\n   End Property\n```\n\n## DISCUSSION\nAlex wrote, \"Around Private Protected, I really feel like we make a mistake if we choose our VB syntax with the arbitrary choice that C# made so that it could look like C++.  We should embrace this as one of those times where VB’s trend towards verbosity leads naturally to a design whose meaning is obvious at first glance. We don’t want to get stuck in a design rut where we’re OK with C# being clearer than VB where terseness pays off, but not vice versa where verbosity pays off – by definition, then, VB will always be less clear than C#.\"\n\nNeal observed that the sense of \"And/Or\" is confusing. It might be a logical And of the permissions, or a logical And of the restrictions. Nevertheless, the CLI has chosen a canonical sense, and we're copying it.\n\n## OTHER DESIGNS CONSIDERED\n\n``` c#\nprivate protected\nprotected if internal\ninternal && protected  // also \"internal || protected\"\ninternal and protected  // also \"internal or protected\"\ninternalAndProtected  // also \"internalOrProtected\"\n```\n``` vb\nProtectedAndFriend  ' also \"ProtectedOrFriend\"\nProtected And Friend  ' also \"Protected Or Friend\"\nProtectedFriend   ' rejected because it's just one space away from \"Protected Friend\"\nFamilyAndAssembly  ' also \"FamilyOrAssembly\"\nPrivate Protected\nProtected OnlyIn Friend\nProtected But Friend\nProtected If Friend\nProtected When Friend\nProtected Xor Friend  ' just a joke... :)\n```\n\n\n# Faster CInt(Double)\n\n## Background\n\n``` c#\ndouble d = 10.5;\nint x = (int)d;\n```\n``` vb\nDim x = CInt(d)\n```\n\nThe VB version is slower than C#. Indeed, any time we call CInt, the compiler always codegens a call to Math.Round. Even CInt(Math.Round(x)) gets compiled into Math.Round(Math.Round(x)).\n\n## Request\nPlease allow us to write fast integer casts in VB.\n\n## Resolution\n\n**Part 1**: Any time the compiler generates an implicit call to Math.Round (i.e. as part of `CInt, CLong, CULong, CUint`), and if the argument of that implicit call is one of a list of math functions known to return a whole number, then omit the outer call to Math.Round. The list of known math functions is: `Round(d), Round(d,MidpointRounding), Truncate(d), Floor(d), Ceiling(d), VisualBasic.Fix(d), VisualBasic.Int(d)`.\n\n\n**Part 2**: If the user writes `CInt(Math.Truncate(d))` then we will emit `conv.i4` or `conv.ovf.i4` dependent on the current project-level \"check-overflow\" settings. (TODO: verify that `conv.i4` has exact same semantics as `CInt(Math.Truncate)`, including negative values, superlarge doubles and exceptions, NaN, Infinity). Also do likewise for `conv.i1, conv.i2, conv.i4, conv.i8` and for their unsigned versions, and for both checked and unchecked versions.\n\n\n## Discussion\n\nThis is a compiler optimization, pure and simple. It adds no new syntax or concepts or library functions. We identify targeted scenarios and generate optimal IL in those cases where semantics would not be affected. This seemed the cleanest approach. Specifically, it seemed better than adding any of the following syntaxes:\n``` vb\nDirectCast(d, Integer)\n(Integer)d\nVB.FastCast(d)\nd As Integer\n```\n\nWill it be better to special-case just one of these combinations? e.g. conv.i4 on CInt(Truncate(double))? Or is it better to just do all of them? Default answer: \"yes do all of them\", and only scale back if the compiler-dev comes back and says it's too hard.\n\nThere are other possible concerns, e.g. what happens if it turns out that the semantics of conv.i4 are actually different from ALL of the Math.Round-like functions? What if it turns out that it's really hard to implement every case? What if expression-trees throw a wrench in the works? Well, when devs set about implementing the feature, then we can come back to check.\n\n"
  },
  {
    "path": "meetings/2014/LDM-2014-04-01.md",
    "content": "# Null propagating operator ?.\n\nThe `?.` operator is the second-highest voted request on UserVoice\nhttp://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/3990187-add-operator-to-c\n\nWe've discussed it in C# and VB Language Design Meeting. Mads has written up detailed notes [here](https://roslyn.codeplex.com/discussions/540281) and [here](https://roslyn.codeplex.com/discussions/540514). Some questions still remain, so I'm starting a thread for general discussion of this feature.\n\nThe core idea is to save you having to write code like this all the time, with null-checks:\n``` cs\nvar temp = GetCustomer();\nstring name = (temp == null) ? null : temp.name;\n```\n\nInstead you'd write this:\n``` cs\nvar temp = GetCustomer()?.name;\n```\n\n## How does ?. behave in sequences?\n\nQ. How does it behave if you have several of these things in sequence? There are two possibilities on the table:\n* *Left-associative*\n* *Right-associative*\n\n\n\n``` cs\nclass Customer1\n{\n    public readonly ExtraRef extraRef = new ExtraRef();\n}\n\nclass ExtraRef\n{\n    public readonly string name = \"fred\";\n}\n\nCustomer1 GetCustomer1()\n{\n    return (RND.Next() > 0.5) ? null : new Customer1();\n}\n\nint? len1a = GetCustomer1()?.extraRef?.name?.Length;\nint? len1b = GetCustomer1()?.extraRef.name.Length;\n```\n\nWhat do you expect about `len1a` and `len1b`? [**edit** - initially I wrote the following out wrong. I've fixed them.]\n\n* len1a - this is the same for both *left-associative* and *right-associative* -- it performs a null-check on GetCustomer1(), and if that succeeds, then it will perform null-check on extraRef and name.\n* len1b - under *left-associative* it is a **compile-time error**. But under right-associative, it performs a null-check on GetCustomer1(), and then **skips** the null-check on extraRef and name.\n\nNote: I constructed this example so that, if GetCustomer1() returns non-null, then I as the programmer know (from readonliness) that extraRef and name will both be non-null. The question is, is there some way to communicate this fact to the compiler, to avoid superfluous null-checks? **Left-associative says there isn't; right-associative says there is.**\n\n(I benchmarked about a 5% perf overhead of doing those extra null-checks in the case where GetCustomer1() returns non-null)\n\n\n``` cs\nclass  Customer2\n{\n    public readonly ExtraStruct extraStruct = new ExtraStruct {age=29};\n}\n\nstruct ExtraStruct\n{\n    public int age;\n}\n\nCustomer2 GetCustomer2()\n{\n    return (RND.Next() > 0.5) ? null : new Customer2();\n}\n\nint? age2a = GetCustomer2()?.extraStruct?.age;\nint? age2b = GetCustomer2()?.extraStruct.age;\n```\n\nWhat do you expect about `age2a` and `age2b` ?\n\n* age2a (how you must write it under *left-associative*) - this performs a null-check on GetCustomer2() and if this succeeds then, thanks to **compiler-optimization** and despite what's written, it knows it can skip the null-check on extraStruct.\n* age2b (how you must write it under *right-associative*) - this performs a null-check on GetCustomer2() and if this succeeds then, **because of how you wrote it**, it skips the null-check on extraStruct.\n\nHere, extraStruct is a structure and can never be null. So it doesn't make sense to null-check it. Should this fact be expressed as a compiler optimization in `age2a`? Or should it be expressed in syntax in `age2b`?\n\n\n``` cs\nvar x = GetCustomer1()?.extraRef?.name?.Length\n==>\nvar explainingVariable = GetCustomer1()?.extraRef;\nvar x = explainingVariable?.name?.Length;\n```\n\n* Is this a valid refactoring?\n  * *left-associative* : it is a valid refactoring \n  * *right-associative* : it's an invalid refactoring\n* How would you add parentheses to make the order explicit?\n  * *left-associative* : `x = ((GetCustomer1()?.extraRef)?.name)?.Length`\n  * *right-associative* : `x = GetCustomer1()?.(extraRef?.(name?.Length))`\n\nYou can see why we call them left-associative vs right-associative. It has to do with how you'd put parentheses into the expressions if you were writing them out explicitly.\n\nIncidentally, there are other places where you can't just introduce an explaining variable. For instance, in `var y = a * b + c * d`, you can't just introduce an explaining variable for the first three parts `var ev = a * b + c; var y = ev * d;`. In this case though it's because of precedence, not because of associativity.\n\n[NOTE: that &#43; is meant to be a PLUS sign. I don't know what's up with the markdown...]\n\nEric Lippert wrote a great blog on the associativity of the ?? operator: http://blog.coverity.com/2013/10/23/null-coalescing-bugs/#.Uzurzo1OV3Q\n\n\n## Some other idioms with ?.\n\n``` cs\n// Call Dispose only if x is non-null:\nx?.Dispose(); \n\n\n// Trigger an event only if it's non-null\n// (not needed in VB, since this is already built into RaiseEvent statement)\nevent EventHandler OnFired;\nvoid Fire()\n{\n    OnFired?.Invoke(this, new EventArgs());\n}\n```\n\n\n## Codegen for ?.\n\nI asked some CLR experts about what assembly code would be generated by the JIT for the ?. operator, and filled in some details from my hazy memory of OS architecture...\n\nThe question was, where does NullReferenceException currently get generated? When you do `GetCustomer1().extraRef`, and GetCustomer1() happens to return null, and so it fires a NullReferenceException, does that happen because the JIT implicitly generates a null-check?\n\nNo. The answer is that the NullReferenceException is generated at a lower level. More specifically, in between CPU and RAM there’s a chip called \"Memory Management Unit (MMU) / Page Table\". Every single time a thread accesses an address in the process’s virtual address-space, the MMU looks up the address in that page table to find where the address is in physical memory. If the virtual address isn’t yet mapped to a page of memory, then the MMU generates a page-fault which the OS has to handle, e.g. by paging in from disk. The CLR reserves addresses at the bottom of virtual address space but never actually pages them in. If ever an instruction tries to look up any address there, then the MMU generates a fault, and the CLR responds to it by generating a NullReferenceException.\n\nThe codegen for `x?.y` would probably be something like this...\n```\nmov rax, X\ntest rax, rax\nbeq :lbl\nmov rax, [rax + k]\n:lbl \n```\n\n[Note: that &#43; is meant to be a PLUS sign. I don't know what's up with the markdown...]\n\n\n"
  },
  {
    "path": "meetings/2014/LDM-2014-04-02.md",
    "content": "# String interpolation\nString interpolation is one of the top ten requests on uservoice - http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2312991-string-interpolations-in-c\n\nWe've been discussing the feature back and forth in C# and VB language design meetings. This thread starts with a summary of the points raised from the Visual Basic Language Design Meeting of 2013-12-09, combined with comments from MVPs, but I'm hoping that everyone who's interested in the topic can add their thoughts and suggestions to the thread. (I switch back-and-forth between C# and VB syntax, which is how we did our discussions...)\n\nSo far the consensus seems to be a resounding \"meh\" because the proposed designs seem to miss the mark, and the feature isn't as important as other potential new features. Here's a writeup of all our notes so far, so we can have a wider discussion with the general public.\n\n## Examples\nHere are some examples in C# and VB:\n\n``` cs\nvar x = \"It measures \\{distance:0.00}m\";\n```\n``` vb\nDim filepath = $\"{drive}:\\{path}\\{file}.{ext}\"\nDim query = $\"{url}?arg1={x}&arg2={y}\"\nDim csv_line = $\"{name},{dollars}{vbCrLf}\"\n```\n\nString interpolation would be syntactic sugar for a call to String.Format:\n\n``` cs\nvar x = \"It measures \\{distance:0.00}m\";\n==>\nvar x = String.Format(\"It measures {0:00}m \", distance);\n```\n\n## Motivation\n\nWhy string interpolation? Isn't String.Format already good enough? More generally, what is the real problem that string-interpolation tries to solve? Here are some possible answers, both good and bad. I think we haven’t yet got a crisp good answer to this question. Some possible answers:\n\n1. It is a full replacement from String.Format, with culture and everything, to solve the mess that you find when there are too many positional arguments (see examples below)\n2. It provides a quick-and-dirty way to do string concatenation in the invariant-culture for use in composing strings together to pass to other APIs\n3. It provides an easy way to stick in identifiers\n4. It is an easier way to teach Coding 101 – don’t want to start beginners on String.Format\n5. All the other cool languages have it. (bad reason)\n\n\n## Motive 1: a replacement for String.Format\nProposal: \"String interpolation is a replacement for String.Format, for cases where the \"positional\" arguments {…} of String.Format are confusing to read.\" As a motivating example, the following code has a few bugs (missing space before {5}, and the orders have got mixed up) and it's not really human-readable…\n\n``` vb\nDim x = String.Format(\"Robot {1} reporting{0}  {3} levels are {2}{0}\" &\n                      \"{5} levels are {4}\",\n                      vbCrLf, name, coolant.name, coolant.level,\n                      reactor.name, reactor.level)\n```\n\nIsn't normal string concatenation already good enough? Again, sometimes it's confusing. The bug here is that there's a missing vbCrLf at the end of the second line:\n\n``` vb\nDim z = \"Robot \" & name & \" reporting \" & vbCrLf &\n        \"  \" & coolant.name & \"levels are \" & coolant.value &\n        \"  \" & reactor.name & \" levels are \" & reactor.value\n```\n\nOne curious proposal is to allow string concatenation just by omitting the & in VB (or + in C#), just as is currently the case in C for string literals. But this seems pretty limited -- wouldn't allow for format specifiers, would only work for expressions with string literals before and after them, might close the language off to context-specific keywords in the future, and doesn't look very readable.\n\n\nString interpolation could be neater and easier to debug than either String.Format or concatenation...\n``` vb\n    Dim y = $\"Robot {name} reporting\n{coolant.name} levels are {coolant.level}\n{reactor.name} levels are {reactor.level}\"\n```\n\nHowever, this example is fishy. Most professional programmers won't be writing user-facing strings in code. Instead they'll be storing those strings in resources (.resw, .resx or .xlf) for reasons of localization. So there doesn't seem much use for string interpolation here.\n\n\n## Motive 2: a quick-and-dirty way to do construct strings for APIs.\n``` vb\nDim filepath = $\"{drive}:\\{path}\\{file}.{ext}\"\nDim query = $\"{url}?arg1={x}&arg2={y}\"\nDim csv_line = $\"{name},{dollars}{vbCrLf}\"\n```\n\nThese examples seem to work nicely with string interpolation, but we'd be opening up potential security holes when people construct strings without sanitizing them first. That's a worry.\n\nSome open questions about string interpolation...\n\n## Q. Default culture?\nWhat should the default culture be for string interpolation?\n* String.Format uses CultureInfo.CurrentCulture by default\n* It feels like InvariantCulture would be a better bet if users are typically using string-interpolation as a way to construct strings to pass to APIs.\n* CurrentCulture would be make more sense only if (1) people use it mainly for UI strings, (2) and they’re not localizing their UI by storing strings in .resw\n* CurrentCulture also makes sense if the feature feels really close to String.Format.\n\n## Q. Specify culture?\nShould users be able to specify the culture to be used?\n* The Javascript proposal (next post) would allow this, since you could call\n``` vb\nDim s = FmtInvariantCulture`hello {x}`\nDim s = FmtCurrentCulture`hello {x}`\n```\n* If we want to use a prefix for string interpolation `var x = $\"hello\";`, then that provides a place where culture could be specified `var x = ${culture}\"hello\";`\n* Alternatively, culture could be specified at the end, e.g.\n``` cs\nvar x = \"hello \\{x}\"(CultureInfo.CurrentCulture);\n```\n``` vb\nDim x = $\"hello {x}\"(CultureInfo.CurrentCulture)\n```\n* MVP Bill McCarthy suggested this interesting syntax:\n``` vb\nDim x = $\"hello {x}\" Using CultureInfo.CurrentCulture\n```\n\n## Q. Perf of String.Format ?\nWhat kind of compiler optimizations would be used?\n* If the compiler sees that it can optimize away the call to String.Format, and use instead something more lightweight (that still has the same semantics), then it would:\n``` cs\nvar x = \"It measures \\{distance}m\";\n==> var x = String.Format(\"It measures {0}m \", distance);\n==> var x = String.Concat(\"It measures \", distance.ToString(), \"m\");\n```\n* Will there be compiler folding? e.g.\n``` cs\nvar x = \"hello \\{a}\" + \"world \\{b}\";\n==> var x = \"hello \\{a}world \\{b}\";\n==> var x = String.Format(\"hello {0}world {1}\", a, b);\n```\n* Will the compiler do compile-time evaluation if the arguments that go in the hole are constant and which don’t depend on the current culture? It seems risky to take a dependency on the internal behavior of String.Format…\n\n## Q. Prefix syntax?\nOn an interpolated string, should it have a prefix?\n``` cs\nvar x = \"It measures \\{d}m\";\nvar x = $\"It measures {d}m\";\n```\n* For C# we were leaning towards the first form, where the presence of `\\{.}` inside a string implies it is to be interpolated. For VB that's impossible, so we were pushed towards the second form where the prefix implies that the string will be interpolated.\n* MVPs raised the issue that, if you wanted to do a global search to find all interpolated strings in a codebase, the prefix form makes it easier. If you merely searched for \\{ then you'd get false-positives from double-escaped \\\\{, and from \\{ in XML doc-comments.\n* For choice of prefix, we considered the following, and preferred $\n``` vb\nDim x = @\"hello\"   ' bad, since confusing with C# verbatim strings\nDim x = #\"hello\"   ' used in a few other languages\nDim x = $\"hello\"   ' used in Nemerle. Fits with the VB heritage\n```\n\n## Q. Hole syntax?\nIn an interpolated string, what syntax to use for marking an expression hole? And then how do you escape that syntax if you want to use it literally? For VB we considered the following:\n``` vb\nDim brace  = $\"hello {name} \"\" {{ {vbCrLf}\"    ' PHP, Python, String.Format\nDim escape = $\"hello \\{name} \\\" \\\\ \\n\"         ' C# proposal\nDim hash   = $\"hello #{name} \"\" ## ${vbCrLf}\"  ' Ruby, Coffeescript\nDim $brace = $\"hello ${name} \"\" $$ ${vbCrLf}\"  ' Dart\nDim $paren = $\"hello $(name) \"\" $$ $(vbCrLf)\"  ' Nemerle\nDim $dollar= $\"hello $name \"\" $$ $vbCrLf\"      ' PHP, Perl, Dart, Nemerle\n```\n* `brace` is strongly reminiscent of String.Format, which is good. And {{ is how you already escape out of String.Format. The \"vbCrLf\" is reasonable way to get a newline. We preferred this option for VB.\n* `escape` has the nice feature that it opens the door for escape characters, and is like C#. But it feels wrong to have to have that redundant extra character.\n* `hash` doesn’t have much going for it.\n* `$brace` re-uses $ in a reasonable way but the way to escape $ is pretty ugly\n* `$paren` is a Nemerle variant of `$brace` with the same disadvantages\n* `$dollar` would be a nice shortcut for the common case of just wanting to include an identifier, and is something allowed by string-interpolation in a lot of other languages. However it only combines well with `$brace` and `$paren`.\n\n\n## Q. Expressions in holes?\nWhat kinds of expressions should be allowed in the \"holes\"? Just identifiers? Or qualified identifiers? How about indexers? Invocations? Arbitrary expressions?\n``` cs\nvar x = \"This is \\{arg[0]} and \\{arg[1]}\";\nvar y = \"This is \\{Lookup(x)} \";\nvar x = \"Welcome \\{user.Name} to \\{user.Activity}\";\n```\n* MVPs justifiably observed that it would be bad practice to use complex expressions inside the holes.\n* But it's hard to draw a clear compiler-enforced line between \"things that are okay in holes\" and \"things that aren't\". For instance, indexers and method-invocations are probably good. So to keep things plain and regular, the compiler should probably to allow all expressions.\n* There's a good precedent for this. With the async/await feature, we wanted to allow things like `var x = await t` and also `using (var x = await t)`. And so we allowed await in all expression contexts, even though it's bad practice to use them in confusing places like `x[await t1] += await t2;`\n* In practical terms, it's very hard (in terms of implementing the lexer+parser) to allow arbitrary expressions inside a hole. VB already does this for expression holes in XML-literals, so could use the same codebase for expressions in interpolated-string-holes. But C# doesn't yet do this anywhere.\n* Should it allow format-specifiers like the :0.00 used in the first example? That might complicate the lexing/parsing. But we don't see any ambiguity problems.\n\n\n## Q. C# verbatim string?\nCan you use string interpolation in a C# verbatim string?\n\n\n## Q. VB implicit line continuations?\nHow does it work with VB implicit line continuations? e.g.\n``` vb\nDim x = $\"hello { 3\n         + 4 } world\"\n```\nAnswer: it works exactly the same as always: implicit line continuations happen before or after specific characters. The fact of being inside a hole in an interpolated string doesn’t change that. So the above code won’t work, since implicit line continuation isn't allowed before +.\n\nAlso, { allows an implicit line-continuation after it as always, and } at the end of a hole allows an implicit line continuation before it as always. Note for precedent that `Dim x = New With { .x=15}` also allows an implicit LC after the `{`, and XML expression holes allow an implicit LC after the `<%=`.\n\n## Q. VB Case statement?\nCan you use interpolated strings as a VB Case expression? e.g. `Select Case x : Case $\"hello {a}`\nAnswer: Yes. VB case statements always allow computed values here. C# never does.\n\n## Q. Const?\nIs an interpolated string const? `Const x as String = $\"hello\"`\n\nAnswer: No, never, not even for the ones that are clearly recognizable as constants. The rule is that string interpolation is semantically shorthand for String.Format (notwithstanding any under-the-hood compiler optimizations).\n\n## The Python alternative\nThere's an idiom used in Python today, that some people in VB/C# are also adopting. Here's how it would look in .NET:\n\n``` vb\nDim args = New With {.Name = \"Jones\", .Address = \"1256 92nd St\"}\nDim str = \"Mr {Name} lives at {Address}\".FormatEx(args)\n```\n\nThe idea here is that it's all the positional format-arguments {0}, {1} in String.Format that are difficult to read. So we could do them using named arguments {Name}, {Address}. You would write an extension method on String which takes an object. At runtime your method parses the string to find curly braces (just like String.Format does), and it uses reflection to look for corresponding members in the \"args\" object.\n\n(You'd have to be careful that the folks doing localization of your strings don't try to localize {Name} or {Address} !)\n\nWith the proposed \"dictionary\" features of C# and VB vNext, you could write FormatEx using dictionary arguments rather than reflection:\n``` vb\nDim args = New Args With {!Name = \"Jones\", !Address = \"1256 92nd St\"}\nDim str = \"Mr {Name} lives at {Address}\".FormatEx(args)\n```\n\nThis Python-style approach would also solve the culture problem -- because you can easily pass Culture to your extension method.\n\n## The Javascript alternative\nThere's a string-interpolation proposal on the table for the next version of EcmaScript that's designed specifically to solve the security worries of string interpolation. It also solves Culture.\nhttp://wiki.ecmascript.org/doku.php?id=harmony:quasis\n\nIt would look something like this if we translated it into .NET:\n``` vb\nDim x = c.Fmt`Mr {name} at {address}`\n==>\nDim x = c.Fmt({\"Mr \", \" at \", \"\"}, name, address)\n```\nThe idea here is that at compile-time the interpolated string gets broken up into pieces, and then at runtime it gets passed as an argument to the specified function or delegate. The advantage, as compared to the Python approach, is that there's less runtime overhead.\n\n\n\nWe had discussed something sort-of-related for C#. \"There are many different APIs which work the same way: let's come up with a proposal for string-interpolation which works with all of them\". It would expand an interpolated string into a *comma-separate sequence of expressions* :\n``` vb\n$\"hello {a} in {b}\"\n==>\n\"hello {0} in {1}\", a, b\n```\n\nThis would enable it to be used for a wide variety of APIs, e.g.\n``` vb\n1: Console.WriteLine($\"hello {a} in {b}\")\n2: Dim x = String.Format($\"hello {a} in {b}\")\n3: Diagnostics.WriteLine($\"hello {a} in {b}\")\n```\nHowever it would prevent another idiom,\n``` vb\n4: Dim x = $\"hello {a} in {b}\"\n```\n\nThe pain of losing [4] is severe. And the other cases above all boil down to a call to String.Format, so we're not losing much by saying that string-interpolation is always translated into a call to String.Format. Indeed, we think that most of the time people take parameters `(fmt as string, ParamArray args as Object())`, then they just pass it down straight to String.Format. True there are just a few cases where they don't... for instance, the Roslyn codebase has a function where it modifies the format and args before passing them to String.Format. The pain of losing these scenarios seemed less than the pain of losing [4].\n\n"
  },
  {
    "path": "meetings/2014/LDM-2014-04-16.md",
    "content": "# #Warning Disable\n\n## REQUEST\n\nPlease add `#pragma` to VB so we can suppress warnings. This will be especially useful for Roslyn Diagnostics, where people will find many more warnings in their code.\n\n## RESOLUTION\n\nAdd two new preprocessor directives:\n\n``` vb\n#Disable Warning 40008, BC42358, \"BC42356\"\n#Enable Warning 40008, BC42358, \"BC42356\"\n```\n\n## ALTERNATIVE SYNTAXES CONSIDERED\n\n``` vb\n#pragma disable <id>\n#pragma enable <id>\n\n#Disable <id>  ' sounds like you're disabling code, not warnings\n#Enable <id>\n\n#Ignore <id>\n#End Ignore  ' block structure is worse than toggles\n\n#Disable Warning <id>\n#Enable Warning <id>\n```\n\n\n## DISCUSSION\n\nThe tradition in VB and its rich history of quick-fixes is that you resolve warnings by FIXING YOUR CODE, e.g. by doing whatever the quickfix says, adding an explicit cast, adding a return statement, ...\n\nQ. Do people really use #pragma much in C# today? Hard to say. With new Roslyn diagnostics, will *more* people start using #pragma in C# ? Will people write Roslyn diagnostics that have a much higher false-positive rate than existing rules, for people who wish to be more careful, safe in the knowledge that it's easy to suppress?\n\nQ. Is there a downside to adding #pragma to VB for suppressing warnings? - no, not really\n\nQ. Should we add a feature which suppresses the warning merely for the next line, rather than for the rest of the file? -- This isn't feasible in C# where lines don't really exist semantically. It is feasible for VB. Disadvantage: would confusing for LINQ, and not refactoring-safe. Advantage: if the lightbulb/quickfix appears for a warning, and when you chose the option to \"suppress warning\" then it only has to insert a single line to \"suppress-warning-on-next-line\", rther than having to insert `#ignore` before and `#restore` after. Conclusion: No we won't add this next-line-suppression feature.\n\nQ. Is it good to disable/enable on a \"block\" basis like `#Ignore / #End Ignore` ? Or on a toggle basis like `#Disable Warning / #Enable Warning` ? Well, with blocks you can't do overlapping regions. And you can't easily disable warnings for an entire method but then re-enable them for a small critical region inside (even though that's a weird scenario). We believe overall that toggles are nicer. They have a lot of engineering, thought and experience behind them.\n\nQ. For the `<id>`, should quotation marks be obligatory? - No. You can use any identifier or integer. It's only if the warning-id has spaces or other weird characters that you'd need quotation marks.\n\nQ. Should we allow pure integers for the `<id>`, with the expectation that they disable intrinsic VB compiler warnings? All user-defined warnings (that come through Roslyn diagnostics) would have error codes that aren't pure integers. -- Yes, let's allow integers, just like C#, and just like the VB command-line. It will be a common case.\n\nQ. Will the Roslyn diagnostics APIs allow people to define error codes that are just pure numbers, even though they'll be impossible to disable them? -- No real need. Diagnostic-authors will learn soon enough not to do this.\n\nQ. Should we allow you to disable/enable command-separated lists of warnings in a single `#Disable Warning / #Enable Warning` directive? -- Yes.\n\nQ. Preprocessor directives look ugly because they're always left-aligned. Can we make it so preprocessor directives can be indented? There's a uservoice request for it. -- Not discussed; left for another day.\n\n\n# Back-compat break with interface implementations\n\nWe also discussed another topic to do with ambiguity between unrelated interfaces. Discussion is in this thread:\nhttps://roslyn.codeplex.com/discussions/570975\n\n\n# Update: VB LDM 2014.07.01\n\nWe re-visited #Disable Warning. The summary for VB is:\n\n* Use the syntax `#Disable Warning id1, id2, ...`\n* The warning IDs must parse as per the same rules of VB identifiers, and are case-insensitive. That rules out plain numbers `#Disable Warning 4008` (instead you must disable BC4008) and it rules out strings `#Disable Warning \"Don't Use Capitals!\"`. That means you can't disable warnings that have fancy error codes with punctuation and so on.\n* This will guide users to the thought that they can right-click, find all references, and opens up the mental door to other refactorings/tooling\n* We will restrict what identifiers can be produced at the production side too, when authoring analyzers\n* We used to give BC2026 “that warning can’t be configured” when you try to nowarn or warnaserror on non-existent warnings (and also on certain named warnings e.g. 2026). But that wouldn’t work for diagnostic warning codes. So let’s no longer emit BC2026 ever. Instead, if you try to disable or enable a non-existing warning, simply do nothing.\n* Stretch goal: the IDE could grey out all identifiers that have been disabled but are never actually generated by the code\n\nC# will be mostly similar, but\n* C# will support disabling warnings/errors by number as well as by identifier, and is case sensitive. It has to support disabling numbers for back-compat. If you disable warning number 4008, that's equivalent to disabling identifier CS4008.\n* As with VB, we stop validating whether the warning code is a legal compiler warning ID (both on the command-line and inside #pragma) - CS1691 will no longer be reported for C#.\n \nThings that fall out for free:\n* No changes required to disallow Hexadecimal, Octal, Long etc. literals\n* No need to worry about making BC2026 unerrorable\n \nFor the future:\n* Update lightbulb suppression to always generate #pragma / #disable with identifiers. (Do we need to check that the id will be a legal identifier before spitting the code?)\n* Fix /nowarn and /warnaserror command-line switches to support custom diagnostics\n* Implement grey out for “unused” ids in #pragma, #Disable (plus corresponding code fix)\n* Have some way for users to get from a reported warning id / from a warning id used in #pragma or #Disable to a description of the diagnostic\n* Support for qualified identifiers that use dots (only if customers ask for it)\n\n"
  },
  {
    "path": "meetings/2014/LDM-2014-04-23.md",
    "content": "(this discussion happened in VB language design meeting, but it strongly concerns C# also).\n\n\n# Better support for immutable data, with pattern-matching\n\n## Request\n\nPlease make it easier for me to declare immutable data-types, and make it easier to code over them via pattern-matching. Easier immutable datatypes will make my code have fewer defects, and pattern-matching over immutable data (like in F#, Scala and other functional languages) will allow clean readable maintanable coding idioms.\n\nFor instance, I have a method and want to return 2-3 return values. Here's the ugly code I write now:\n``` cs\n// Ugly 1: use out params (but doesn't work with async)\nvoid Lookup(out string name, out int x, out int y) {...}\n...\nLookup(out name, out x, out y); Console.WriteLine(name);\n\n\n// Ugly 2: use a tuple (but my consumer has a hard time knowing which element is what)\nTuple<string,int,int> Lookup() {...}\n...\nvar r = Lookup(); Console.WriteLine(r.Item1);\n\n\n// Ugly 3: declare a custom datatype\nclass LookupResult(string name, int x, int y)\n{\n   public string Name {get;} = name;\n   public int X {get;} = x;\n   public int Y {get;} = y;\n}\nLookupResult Lookup() {...}\n...\nvar r = Lookup(); Console.WriteLine(r.Name);\n```\n\nWhat I'd like is to write all this much more simply:\n``` cs\nclass LookupResult(string name, int x, int y);\nLookupResult Lookup() {...}\n\nvar r = Lookup(); Console.WriteLine(r?.name);\n```\n\nEven better, I'd like to deconstruct the returned value using pattern-matching:\n``` cs\nif (Lookup() matches LookupResult(var name, var x, var y)) { ... }\n```\n\n\n## Background\n\nWe have been guided in our thoughts by the paper \"Matching Objects with Patterns\" by Emir, Odersky and Williams. There's a link to it on this Scala webpage: http://www.scala-lang.org/old/node/112\n\nThe Roslyn compiler currently has \"primary constructors\" in C#, and a form of \"typecase\" in VB:\n\n``` cs\nclass C(int x, int y)\n{\n    public int X { get; set; } = x;\n    public int Y { get; set; } = y;\n}\n```\n``` vb\nFunction GetArea(shape As Shape) As Double\n    Select Case shape\n        Case r As Rect : Return r.X * r.Y\n        Case c As Circle : Return Math.PI * c.Radius * c.Radius\n    End Select\nEnd Function\n\n' Once we add Out expressions to VB, you can get more pattern-matchey\nFunction Eval(expr As Expr) As Integer\n    Select Case expr\n        Case e As PlusExpr When e.Matches(0, Out rhs)\n            Return Eval(rhs)\n        Case e As PlusExpr When e.Matches(Out rhs, 0)\n            Return Eval(rhs)\n        Case e As PlusExpr When e.Matches(Out lhs, Out rhs)\n            Return Eval(lhs) + Eval(rhs)\n        Case e As IntExpr\n            Return e.Val\n    End Select\nEnd Function\n```\n\n**Question: how will the two features work together?** Will there be a \"sweet spot\" where their designs mesh together well, and mesh with additional features in future versions of the languages, to produce a nice pattern-matching design? Something as nice as what F# or Scala have?\n\n**Urgent question: do we need to make changes to the CURRENT design of primary constructors and Select Case** so that we don't block off a future world of pattern-matching?\n\n\n## PROPOSAL: Records, and Plain Old CLR Objects\n\nHere is a coherent set of proposals that combine construction and deconstruction into one neat easily-written proposal, to support the scenario in the \"Request\".\n\n\nImagine something called a *\"Record\"*, a type with an ordered list of named data members. Not saying there should be a new kind of type called a \"record type\" alongside classes and structs... indeed it might be best not to have a new kind of type, since we might want record-like classes and structs.\n\n**PROPOSAL 1:** a record can be defined using primary-constructor syntax, and it is syntactic sugar for an expanded form as follows...\n``` cs\nclass Point(int X, int Y);\n\n==>\n\nclass Point(int X, int Y)\n{\n   public int X { get; } = X;\n   public int Y { get; } = Y;\n}\n```\n\nThe rule is: \"When you write a record, it automatically generates properties for the *PRIMARY PROPERTIES*, unless you have provided those properties yourself\". The term \"Primary Properties\" refers to the parameters in the primary-constructor syntax. Thus, if you didn't want it to auto-generate a property, you'd have to provide your own version of that property, as in the example below. (There's no way to say that you *don't* want the property with this syntax: if you don't want the property, then don't use the feature at all).\n```cs\nclass Point(int X, int Y) { public int X => 15; }\n\n==>\n\nclass Point(int X, int Y)\n{\n   public int X => 15;\n   public int Y {get; set;} = Y;\n}\n```\n\n**PROPOSAL 2:** Just as we've seen the compiler auto-generate properties if you failed to provide them yourself, it will also auto-generate a default implementation of Equals and GetHashCode if you fail to provide them yourself. This default implementation will do element-wise calls to Equals and GetHashCode on the primary properties.\n\n(By default, Proposal 1 uses immutable properties, and so Equals/GetHashCode will terminate. It's bad practice to for GetHashCode to calculate based on mutable properties.)\n\n\n**PROPOSAL 3:** In addition to auto-generated properties, Equals, GetHashCode, we also auto-generate a MAtch operator (unless one is provided by the user)...\n\n``` cs\nclass Point(int X, int Y)\n{\n  public int X {get;} = X;\n  public int Y {get;} = Y;\n  public static bool operator Matches(Point self, out int X, out int Y) {X=self.X; Y=self.Y; return true;}\n}\n```\n\nIn addition to this, we introduce a new *MATCH* operator into the language:\n\n``` cs\n<expr> matches T(args)\n```\nOperational semantics:\n\n1. Evaluate \"var tmp1 = <expr>\"\n2. Look in type \"T\" for an overload of \"Matches\" whose 2nd...last parameters match the arguments\n3. Evaluate \"var tmp2 = tmp1 As TFirst\" where TFirst is the type of the first parameter of that overload\n4. If this is null, then the match operator returns false\n5. Otherwise, the result invoke the Match operator, passing it (tmp2, args) as arguments.\n\nYou'd use the match operator like this:\n``` cs\nif (f() matches T(var name, var x, var y)) { ... }\n```\nNote that this would have different rules from the way out vars are currently conceived. These out be definitely assigned only if the \"e matches T(args)\" returns true. Incidentally, note that the T's Match operator is not necessarily invoked... e.g. if f() returns null, then it won't be called!\n\n\n\n**PROPOSAL 4:** You could also treat the typename as a method, e.g.\n``` cs\nvar p = Point(2,3);\n==>\nvar p = new Point(2,3);\n```\nAll this does is remove the need for the word \"new\" for these record types. It might seem pointless, but it unifies the way you write construction and deconstruction...\n``` cs\nvar p = Point(2,3);\nif (p matches Point(out x, out y)) { ... }\n```\n\n\n## Discussion\n\nThere were questions raised, heated discussions, and no agreed-upon answers.\n\n\nQ. If we go with primary constructors as they're currently envisaged (where the primary parameters *don't* define fields, and instead only exist at construction-time), then will we still be able to support this vision of pattern-matching?\n\nA. Not directly. But we could support this vision through a new modifier \"record\", e.g. `record class Point(int x, int y)`\n\n\n\nQ. What is the difference between putting all this \"record\" stuff (auto-generated properties, Equals, GetHashCode, Match operator) into the existing primary constructor syntax, vs putting them in via a new modifier \"record\" ?\n\nA1. It's a language-cleanliness problem. It would feel goofy for the primary constructor syntax to mean such different things depending on whether the \"record\" modifier is present.\n\nA2. Case is different. The convention in C# will be to use lower-case for primary constructor parameters, since users will write out the properties manually and use upper-case for that. But with records, the convention will probably be to use uper-case for the primary properties.\n\n\n\nQ. It feels wrong for primary-constructors to be so closely tied to immutable data and pattern-matching. Primary constructors have many other uses even when you don't want the rest, e.g. for coding visitor-patterns. Can we add all the features (primary constructors, Matches, Equals/GetHashCode, auto-generated properties) individually and orthogonally over time? And then use \"concise declaration\" (via whatever syntax) as the thread that ties everything together and delivers the smooth end-to-end use-case?\n\nA. Maybe our goal should be to make a concise story for the desired use-case, rather than to add orthogonal features?\n\n\nQ. Is it important that users can declare Match operators today, right from the first version of primary constructors? (granted, this would be pretty much useless on its own: the Match operator only becomes useful in conjunction with all the other features).\n\n\n\nQ. How would these \"record types\" work with serialization? People commonly use Plain Old CLR Objects (POCO) when they want DataContract serialization. But there's no clear way with this proposal to attribute the individual properties.\n\n\n\nQ. What's needed to ship in the first version of primary-constructors so as to allow this kind of evolution over time? Are there any conflicts with the current proposals (of primary-constructors and SelectCase) that would prevent such evolution?\n\nA. Neal and Mads will meet, discuss this question, and take it to C# LDM next week.\n\n"
  },
  {
    "path": "meetings/2014/LDM-2014-07-01.md",
    "content": "# #Warning Disable\n\n## REQUEST\n\nPlease add `#pragma` to VB so we can suppress warnings. This will be especially useful for Roslyn Diagnostics, where people will find many more warnings in their code.\n\n## RESOLUTION\n\nAdd two new preprocessor directives:\n\n``` vb\n#Disable Warning 40008, BC42358, \"BC42356\"\n#Enable Warning 40008, BC42358, \"BC42356\"\n```\n\n## ALTERNATIVE SYNTAXES CONSIDERED\n\n``` vb\n#pragma disable <id>\n#pragma enable <id>\n\n#Disable <id>  ' sounds like you're disabling code, not warnings\n#Enable <id>\n\n#Ignore <id>\n#End Ignore  ' block structure is worse than toggles\n\n#Disable Warning <id>\n#Enable Warning <id>\n```\n\n\n## DISCUSSION\n\nThe tradition in VB and its rich history of quick-fixes is that you resolve warnings by FIXING YOUR CODE, e.g. by doing whatever the quickfix says, adding an explicit cast, adding a return statement, ...\n\nQ. Do people really use #pragma much in C# today? Hard to say. With new Roslyn diagnostics, will *more* people start using #pragma in C# ? Will people write Roslyn diagnostics that have a much higher false-positive rate than existing rules, for people who wish to be more careful, safe in the knowledge that it's easy to suppress?\n\nQ. Is there a downside to adding #pragma to VB for suppressing warnings? - no, not really\n\nQ. Should we add a feature which suppresses the warning merely for the next line, rather than for the rest of the file? -- This isn't feasible in C# where lines don't really exist semantically. It is feasible for VB. Disadvantage: would confusing for LINQ, and not refactoring-safe. Advantage: if the lightbulb/quickfix appears for a warning, and when you chose the option to \"suppress warning\" then it only has to insert a single line to \"suppress-warning-on-next-line\", rther than having to insert `#ignore` before and `#restore` after. Conclusion: No we won't add this next-line-suppression feature.\n\nQ. Is it good to disable/enable on a \"block\" basis like `#Ignore / #End Ignore` ? Or on a toggle basis like `#Disable Warning / #Enable Warning` ? Well, with blocks you can't do overlapping regions. And you can't easily disable warnings for an entire method but then re-enable them for a small critical region inside (even though that's a weird scenario). We believe overall that toggles are nicer. They have a lot of engineering, thought and experience behind them.\n\nQ. For the `<id>`, should quotation marks be obligatory? - No. You can use any identifier or integer. It's only if the warning-id has spaces or other weird characters that you'd need quotation marks.\n\nQ. Should we allow pure integers for the `<id>`, with the expectation that they disable intrinsic VB compiler warnings? All user-defined warnings (that come through Roslyn diagnostics) would have error codes that aren't pure integers. -- Yes, let's allow integers, just like C#, and just like the VB command-line. It will be a common case.\n\nQ. Will the Roslyn diagnostics APIs allow people to define error codes that are just pure numbers, even though they'll be impossible to disable them? -- No real need. Diagnostic-authors will learn soon enough not to do this.\n\nQ. Should we allow you to disable/enable command-separated lists of warnings in a single `#Disable Warning / #Enable Warning` directive? -- Yes.\n\nQ. Preprocessor directives look ugly because they're always left-aligned. Can we make it so preprocessor directives can be indented? There's a uservoice request for it. -- Not discussed; left for another day.\n\n\n# Back-compat break with interface implementations\n\nWe also discussed another topic to do with ambiguity between unrelated interfaces. Discussion is in this thread:\nhttps://roslyn.codeplex.com/discussions/570975\n\n# Update: VB LDM 2014.07.01\n\nWe re-visited #Disable Warning. The summary for VB is:\n\n* Use the syntax `#Disable Warning id1, id2, ...`\n* The warning IDs must parse as per the same rules of VB identifiers, and are case-insensitive. That rules out plain numbers `#Disable Warning 4008` (instead you must disable BC4008) and it rules out strings `#Disable Warning \"Don't Use Capitals!\"`. That means you can't disable warnings that have fancy error codes with punctuation and so on.\n* This will guide users to the thought that they can right-click, find all references, and opens up the mental door to other refactorings/tooling\n* We will restrict what identifiers can be produced at the production side too, when authoring analyzers\n* We used to give BC2026 “that warning can’t be configured” when you try to nowarn or warnaserror on non-existent warnings (and also on certain named warnings e.g. 2026). But that wouldn’t work for diagnostic warning codes. So let’s no longer emit BC2026 ever. Instead, if you try to disable or enable a non-existing warning, simply do nothing.\n* Stretch goal: the IDE could grey out all identifiers that have been disabled but are never actually generated by the code\n\nC# will be mostly similar, but\n* C# will support disabling warnings/errors by number as well as by identifier, and is case sensitive. It has to support disabling numbers for back-compat. If you disable warning number 4008, that's equivalent to disabling identifier CS4008.\n* As with VB, we stop validating whether the warning code is a legal compiler warning ID (both on the command-line and inside #pragma) - CS1691 will no longer be reported for C#.\n \nThings that fall out for free:\n* No changes required to disallow Hexadecimal, Octal, Long etc. literals\n* No need to worry about making BC2026 unerrorable\n \nFor the future:\n* Update lightbulb suppression to always generate #pragma / #disable with identifiers. (Do we need to check that the id will be a legal identifier before spitting the code?)\n* Fix /nowarn and /warnaserror command-line switches to support custom diagnostics\n* Implement grey out for “unused” ids in #pragma, #Disable (plus corresponding code fix)\n* Have some way for users to get from a reported warning id / from a warning id used in #pragma or #Disable to a description of the diagnostic\n* Support for qualified identifiers that use dots (only if customers ask for it)\n \n\n"
  },
  {
    "path": "meetings/2014/LDM-2014-10-01.md",
    "content": "There were two agenda items...\n1. Assignment to readonly autoprops in constructors (we fleshed out details)\n2. A new compiler warning to prevent outsiders from implementing your interface? (no, leave this to analyzers)\n\n# Assignment to readonly autoprops in constructors\n\n```cs\npublic struct S {\n   public int x {get;}\n   public int y {get; set;}\n   public Z z {get;}\n\n   public S() {\n      x = 15;\n      y = 23;\n      z.z1 = 1;\n   }\n}\n\npublic struct Z { int z1; }\n```\n\n_What are the rules under which assignments to autoprops are allowed in constructors?_\n\n__Absolute__ We can't be more permissive in what we allow with readonly autoprops than we are with readonly fields, because this would break PEVerify. (Incidentally, PEVerify doesn't check definite assignment in the constructor of a struct; that's solely a C# language thing).\n\n__Overall principle__ When reading/writing to an autoprop, do we go via the accessor (if there is one) or do we bypass it (if there is one) and access the underlying field directly?\n_Option1:_ language semantics say the accessor is used, and codegen uses it.\n_Option2:_ in an appropriate constructor, when there is a \"final\" autoprop (either non-virtual, or virtual in a sealed class), access to an autoprop _means_ an access to the underlying field. This meaning is used for definite assignment, and for codegen. Note that it is semantically visible whether we read from an underlying field vs through an accessor, e.g. in `int c { [CodeSecurity] get;}`\n_Resolution: Option1_. Under Option2, if you set a breakpoint on the getter of an autoprop, gets of it would not hit the breakpoint if they were called in the constructor which is weird. Also it would be weird that making the class sealed or the autoprop non-virtual would have this subtle change. And things like Postsharper wouldn't be able to inject. All round Option2 is weird and Option1 is clean and expected.\n\n__Definite Assignment__. Within an appropriate constructor, what exactly are the rules for definite assignment? Currently if you try to read a property before _all_ fields have been assigned then it says CS0188 'this' cannot be used before all fields are assignment, but reading a field is allowed so long as merely that field has been assigned. More precisely, within an appropriate constructor, for purposes of definite assignment analysis, when does access of the autoprop behave as if it's an access of the backing field?\n_Option1_: never\n_Option2_: Only in case of writes to readonly autoprops\n_Option3_: In the case of writes to all autoprops\n_Option4_: In the case of reads and writes to all autoprops\n_Resolution: Option4_. This is the most helpful to developers. You might wonder what happens if it's a virtual autoprop and someone overrides getter or setter in derived types in such a way that would violate the definite assignment assumptions. But for structs there won't be derived types, and for classes the semantics say that all fields are assigned to default(.) so there's no difference.\n\n__Piecewise initialization of structs__. In the code above, do we allow `z.z1 = 15` to assign to the _field_ of a readonly struct autoprop?\n_Option1:_ Yes by threating access to \"z\" for purposes of definite assignment as an access of the underlying field.\n_Option2: _ No because in `z.z1` the read of `z` happens via the accessor as per the principle above, and thus returns an rvalue, and hence assignment to `z.z1` can't work. Instead you will have to write `z = new Z(...)`.\n_Resolution: Option2_. If we went with Option1, then readonly autoprops would end up being more expressive than settable autoprops which would be odd! Note that in VB you can still write `_z.z1 = 15` if you do want piecewise assignment.\n\n__Virtual__. What should happen if the readonly autoprop is virtual, and its getter is overridden in a derived class?\n_Resolution:_ All reads of the autoprop go via its accessor, as is already the case.\n\n__Semantic model__. In the line `x = 15` what should the Roslyn semantic model APIs say for the symbol `x` ?\n_Resolution:_ they refer to the property x. Not the backing field. (Under the hood of the compiler, during lowering, if in an appropriate constructor,  for write purposes, it is implicitly transformed into a reference to the backing field). More specifically, for access to an autoprop in the constructor,\n1. It should _bind_ to the property, but the property should be treated as a readable+writable (for purposes of what's allowed) in the case of a readonly autoprop.\n2. The definite assignment behavior should be as if directly accessing the backing field.\n3. It should code gen to the property accessor (if one exists) or a field access (if not).\n\n__Out/ref arguments in C#__. Can you pass a readonly autoprop as an out/ref argument in C#?\n_Resolution: No_. For readonly autoprops passed as _ref_ arguments, that wouldn't obey the principle that access to the prop goes via its accessor. For passing readonly autoprops as _out_ arguments with the hope that it writes to the underlying field, that wouldn't obey the principle that we bind to the property rather than the backing field. For writeonly autoprops, they don't exist because they're not useful.\n\n__Static readonly autoprops__ Should everything we've written also work for static readonly autoprops?\n_Resolution: Yes._ Note there's currently a bug in the native compiler (fixed in Dev14) where the static constructor of a type G<T> is able to initialize static readonly fields in specializations of G e.g. `G<T>.x=15;`. The CLR does indeed maintain separate storage locations for each static readonly fields, so `G<int>.g` and `G<string>.g` are different variables. (The native compiler's bug where the static constructor of G could assign to all of them resulted in unverifiable code).\n\n__VB rules in initializers as well as constructors__. VB initializers are allowed to refer to other members of a class, and VB initializers are all executed during construction time. Should everything we've said about behavior in C# constructors also apply to behavior in VB initializers?\n_Resolution: Yes_.\n\n__VB copyback for ByRef parameters__. In VB, when you pass an argument to a ByRef parameter, then either it passes it as an lvalue (if the argument was a local variable or field or similar) or it uses \"copy-in to a temporary then invoke the method then copy-out from the temporary\" (if the argument was a property), or it uses \"copy-in to a temporary then invoke the method then ignore the output\" (if the argument was an rvalue or a constant). What should happen when you pass a readonly autoprop to a ByRef parameter?\n_Option1:_ Emit a compile-time error because copyback is mysterious and bites you in mysterious ways, and this new way is even more mysterious than what was there before.\n_Option2:_ Within the constructor/initializers, copy-in by reading via the accessor, and copy-back by writing to the underlying field. Elsewhere, copy-in with no copy-out. Also, just as happens with readonly fields, emit an error if assignment to a readonly autoprop happens in a lambda in a constructor (see code example below)\n_Resolution: Option2_. Exactly has happens today for readonly fields. Note incidentally that passing a readonly autoprop to a ByRef parameter will have one behavior in the constructor and initializers (it will do the copy-back), and will silently have different behavior elsewhere (it won't do any copy-back). This too is already the case with readonly fields. On a separate note, developers would like to have feedback in some cases (not constants or COM) where copyback in a ByRef argument isn't done. But that's not a question for the language design meeting.\n\n__VB copyin for writeonly autoprops__. VB tentatively has writeonly autoprops for symmetry, even though they're not useful. What should happen when you pass a writeonly autoprop as a ByRef argument?\n_Resolution: Yuck._ This is a stupid corner case. Notionally the correct thing is to read from the backing field, and write via the setter. But if it's easier to just remove support for writeonly autoprops, then do that.\n\n```vb\nClass C\n    ReadOnly x As Integer = 15\n\n    Public Sub New()\n        f(x)\n        Dim lamda = Sub()\n                        f(x) ' error BC36602: 'ReadOnly' variable\n                        ' cannot be the target of an assignment in a lambda expression\n                        ' inside a constructor.\n                    End Sub\n    End Sub\n    Shared Sub f(ByRef x As Integer)\n        x = 23\n    End Sub\nEnd Class\n```\n\nWe discussed a potential new error message in the compiler.\n\n__Scenario:__ Roslyn ships with ISymbol interface. In a future release it wants to add additional members to the interface. But this will break anyone who implemented ISymbol in its current form. Therefore it would be good to have a way to prevent anyone _else_ from implementing ISymbol. That would allow us to add members without breaking people.\n\nIs this scenario widespread? Presumably, but we don't have data and haven't heard asks for it. There are a number of workarounds today. Some workarounds provide solid code guarantees. Other workarounds provide \"suggestions\" or \"encouragements\" that might be enough for us to feel comfortable breaking people who took dependencies where we told them not to.\n\n__Counter-scenario:__ Nevertheless, I want to _MOCK_ types. I want to construct a mock ISymbol myself maybe using MOQ, and pass it to my functions which take in an ISymbol, for testing purposes. I still want to be able to do this. (Note: MOQ will automatically update whenever we add new members to ISymbol, so users of it won't be broken).\n\n\n__Workarounds__\n\n1. Ignore the problem and just break people.\n2. Like COM, solve it by adding new incremental interfaces ISymbol2 with the additional members. As Adam Speight notes below, you can make ISymbol2 inherit from ISymbol.\n3. Instead of interfaces, use abstract classes with internal constructors. Or abstract classes but never add abstract methods to it; only virtual methods.\n4. Write documentation for the interface, on MSDN or in XML Doc-Comments, that say \"Internal class only; do not implement it\". We see this for instance on ICorThreadpool.\n5. Declare a method on the interface which has an internal type in its signature. The CLR allows this but the language doesn't so it would have to be authored in IL. Every type which implements the interface would have to provide an implementation of that method.\n6. Write run-time checks at the public entry points of key Roslyn methods that take in an ISymbol, and throw if the object given was implemented in the wrong assembly.\n7. Write a Roslyn analyzer which is deployed by the same Nuget package that contains the definition of ISymbol, and have this analyzer warn if you're trying to implement the interface. This analyzer could be part of Roslyn, or it could be an independent third-party analyzer used by many libraries.\n\n\n__Proposal:__ Have the compiler recognize a new attribute. Given the following code\n```cs\n[System.Runtime.CompilerServices.InternalImplementationOnly] interface I<...> {...}\n```\nit should be a compile-time warning for a type to implement that interface, directly or indirectly, unless the class is in the same assembly as \"I\" or is in one of its InternalsVisibleTo friends. It will also be a compile-time error for an interface to inherit from the interface in the same way. Also, we might ask for the .NET Framework team to add this attribute in the same place as System.Runtime.CompilerServices.ExtensionAttribute, and CallerMemberNameAttribute. But doing it isn't necessary since the compiler will recognize any attribute with that exact fully-qualified name and the appropriate (empty) constructor. \n\nNote that this rule would not be cast-iron, since it won't have CLR enforcement. It would still be possible to bypass it by writing IL by hand, or by compiling with an older compiler. But we're not looking for cast-iron. We're just looking for discouragement strong enough to allow us to add members to ISymbol in the future. (In the case of ISymbol, it's very likely that people will be using Roslyn to compile code relating to ISymbol, but that doesn't apply to other libraries).\n\n\n__Resolution:__ Workaround #7 is a better option than adding this proposal to the language.\n"
  },
  {
    "path": "meetings/2014/LDM-2014-10-08.md",
    "content": "# Back-compat break with interface implementations\n\n## High-level summary\n\n* _On the declaration side,_ C# users always used to be able to declare overloads of ambiguous interface methods. We are adding this ability also to VB for VS2015.\n* _On the consumption side,_ C# language is more \"hide-by-name\" while VB supports both \"hide-by-name\" and \"hide-by-sig\".\n* In such cases VB used to try to emulate the C# behavior when meta-importing such declarations. Now it will follow the more VB behavior.\n* _This will cause some small breaking changes_. The breaking cases are limited to where...\n* (1) Library code was authored in C#\n* (2) In that library an interface ID inherits from two others IA,IB and declares a more general overload of a method in each of them\n* (3) VB consumers of that library used to pick the more general overload (copying C#'s hide-by-name behavior). But now they will pick the more specific overload (using VB's hide-by-sig behavior)\n* (4) If there were ambiguous specific overloads then it will be a break for VB consumers of the C# library.\n\n\n## Background\n\n``` vb\nInterface A\n  Sub M(x As Integer)\nEnd Interface\n\nInterface B\n  Sub M(x As String)\nEnd Interface\n\nInterface C : Inherits A,B\n  Overloads Sub M(x As Char)\nEnd Interface\n\nInterface D : Inherits A, B\nEnd Interface\n```\n\nDECLARATION: Declaration C\" had been illegal in VB up to VS2013; you could only declare M in C with 'Shadows, or meta-import it from C#. But VB Roslyn made a change... it now lets you *declare* such things.\n\nCONSUMPTION: We never came up with a policy around CONSUMPTION of such things.\n\n* VS2013: In the type \"C\" if you try to access \"M\", the compiler doesn't see \"M\" from A and B. It only sees it from C. Note: you can meta-import C, but can't declare it.\n* VS2013: In the type \"D\" if you try to access \"M\", the compiler gives a name-lookup ambiguity error prior to even attempting overload resolution.\n* Roslyn as of May 2014: In both \"C\" and \"D\" if you try to access \"M\", the compiler gives name-lookup ambiguity error prior to even considering overload resolution.\n\n## Request\n\nWe'd like to be able to invoke \"M\" in both \"C\" and \"D\". But we'd also like to preserve backwards compatibility. It's a conundrum.\n\n\nNote that there's a similar issue with Modules:\n``` vb\nModule Module1\n  Function Sin(d As Double) As Double\n\nModle Module2\n  Function Sin(s As Single) As Single\n\n' this callsite is in a place that imports both modules' containing namespaces\nDim x = Sin(1.0) ' VB currently makes this an ambiguity. \n```\nVB makes this invocation of Sin an ambiguity. But when you do the equivalent in C# using \"static using\", it gathers together all candidates from all usings, and then performs overload resolution on them. This case seems very minor. Not worth worrying about.\n\n## VB LDM 2014.04.16\n\nPROPOSAL1: revert change that enabled declaration in C. (but doesn't help consumption of meta-imported C, nor consumption of D).\n\nPROPOSAL2: silently treat it as shadowing at the callsite, consistent with native compiler. (but doesn't help consumption of D).\n\n_PROPOSAL3: Allow at lookup, i.e. merge them all, and leave it to overload resolution. (This is the proposal that we picked)._ This is a small breaking change. It will break code which used to meta-import \"C\", and invoked \"M\" in it, and always got the version of \"M\" in \"C\". Now with this change, it might get the version of \"M\" from \"A\" or \"B\". We think this is a minor breaking change, because (1) it only applied to meta-import situations, (2) it will now behave as the author intended. Note that this requires a change to VB spec 4.3.2.\n\nPROPOSAL4: combination of 1 and 2, i.e. completely duplicate behavior of native compiler.\n\n## VB LDM 2014.10.08\n\nWe revisited the previous conclusion in the light of implementation. The related bug numbers are:\nhttps://roslyn.codeplex.com/workitem/34\nInternal vstfdevdiv bug 527642\n\nThe issue is that the C# language has hide-by-name lookup rules, and because of this it doesn't matter whether it meta-exports its signatures as \"hide-by-name\" or \"hide-by-sig\"; that difference is ignored. It happens to export them as \"hide-by-sig\".\n\n\nHere's a representative example of the kind of breaks we'll now get under PROPOSAL3. There is a library that was authored in C#:\n```cs\ninterface IA {void m(int x);}\ninterface IB {void m(int x);}\ninterface ID : IA,IB {void m(object x);}\n```\nC# users of the library are able to use it fine:\n```cs\nID d = null;\nd.m(1);  // picks the \"object\" overload\n```\nHowever VB users of the library will now experience a break\n```vb\nDim x As ID = Nothing\nx.m(1) ' VS2013 used to pick 'Object' but under Proposal3 will now give an ambiguity error\nx.m(CObj(1)) ' this is the workaround to use in this case\n```\n\nThe breaking cases are limited to where C# had ambiguous methods in unrelated interfaces, and overrode them with a more general overload in the derived interface ID. We imagine this breaking case will be uncommon.\n\n\n\nThere's a more common related scenario which WILL CONTINUE to work just fine. Let's walk through it:\n```cs\ninterface IJson {string GetName();}\ninterface IComponent {string GetName();}\ninterface IPatient : IJson,IComponent {}\n```\nI am a C# author. I am taking in two libraries that provide IJson and IComponent. They are unrelated by they happen to have a method which shares a signature and has more or less the same behavior. I write it as above. However, within my C# use of my library, I discover a problem straight away: `IPatient y = ...; y.GetName();` This code will give a compile-time ambiguity error because it doesn't know which unrelated overload of GetName to use. So I fix up my C# library as follows, to silence up the compiler:\n```cs\ninterface IPatient : IJson,IComponent {new string GetName();}\n```\nWith this change, the same C# code `IPatient y = ...; y.GetName();` will work just fine. The reason it works in C# is because C# language uses hide-by-name lookup rules, and finds IPatient.GetName, and is happy with that.\n```vb\nDim y As IPatient = Nothing\ny.GetName() ' correctly picks IPatient.GetName\n```\nFortunately the VB consumers of the library will also work great. In VS2013 it worked because VB faked up hide-by-name semantics on meta-import and so got the derived class. Under Proposal3 it will work because VB honestly uses hide-by-sig semantics and in this case (unlike ID.m(object) above) the hide-by-sig semantics pick the correct method.\n\n\nHow did VS2013 VB fake up \"hide-by-name\" semantics? Well, upon meta-import, it did a \"shadowing trick\": if it encountered an interface like C, it knew that such an interface could not have been declared by VB, and therefore it must have been declared in C#, and C# language had hide-by-name (shadowing) semantics, and so VB ignored the \"hide-by-sig\" attribute on the metadata and imported it as hide-by-name.\n\n\nWe went back on our resolution. We decided to forbid declaration of interfaces like \"C\". By forbidding it, we open the door to pulling the same \"shadowing\" trick as VS2013 did on meta-import. Actually the Roslyn compilers have a cleaner design and can't pull the trick on meta-import; however they can pull it on name lookup.\n\nIn other words, we resolved to go for PROPOSAL4.\n\n## VB LDM 2014.10.08\n\nGosh this is difficult. In trying to replicate the behavior of VS2013, Aleksey discovered some pretty weird bugs in the way VS2013 applied its shadowing heuristics.\n\n```vb\n' BUG NUMBER 1 IN VS2013\n\nInterface IA(Of T)\n    Sub M1(x As T)\nEnd Interface\n\nInterface IB\n    Inherits IA(Of Integer), IA(Of Short)\n    Overloads Sub M1(x As String) ' VS2013 doesn't report an error\nEnd Interface\n\nInterface IC1\n    Sub M1(x As Integer)\nEnd Interface\n\nInterface IC2\n    Sub M1(x As Short)\nEnd Interface\n\nInterface ID\n    Inherits IC1, IC2\n    Overloads Sub M1(x As String) ' VS2013 reports error BC31410 \"Overloading methods declared in multiple base interfaces is not valid\"\nEnd Interface\n\nModule Module2\n    Sub Test(x As IB)\n        x.M1(1) ' VS2013 reports error BC30685: 'M1' is ambiguous across the inherited interfaces 'IA(Of Integer)' and 'IA(Of Short)'\n    End Sub\n\n    Sub Test(x As ID)\n        x.M1(1) 'ID\n    End Sub\nEnd Module  \n```\nWhat's strange in this bug number 1 is that you expect the declaration error BC31410 to be reported in both cases IB and ID. However VS2013 only reports a declaration error for ID. Instead it reports a consumption error for IB.\n\n```vb\n' BUG NUMBER 2 IN VS2013\n\nInterface IA\n    Sub M1()\nEnd Interface\n\nInterface IB\n    Inherits IA\n    Overloads Sub M1(x As Integer)\nEnd Interface\n\nInterface IC1\n    Inherits IA, IB\n    Overloads Sub M1(x As String) ' VS2013 reports error BC31410 \"Overloading methods declared in multiple base interfaces is not valid.\"\nEnd Interface\n\nInterface IC2\n    Inherits IB, IA\n    Overloads Sub M1(x As String) ' VS2013 reports error BC31410 \"Overloading methods declared in multiple base interfaces is not valid.\"\nEnd Interface\n\nInterface IC3\n    Inherits IB\n    Overloads Sub M1(x As String) ' VS2013 reports no error\nEnd Interface\n```\nWhat's strange about this is that interfaces IC1, IC2 and IC3 are semantically equivalent: whether or not you explicitly declare that you inherit from IA is irrelevant, since it's implied. So the compiler shouldn't be reporting a declaration error in IC1/IC2, just as it doesn't report a declaration error in IC3.\n\nThis means that we have to refine our idea of Proposal 4:\n\nPROPOSAL4a: disallow declaration C by reimplementing all the weird quirks of VS2013, and use implicit shadowing upon name lookup. We rejected this as too difficult: Roslyn has very different code paths, so there's a high risk that we'd get different behavior from VS2013.\n\nPROPOSAL4b: disallow declaration C in a clean way without any of the weird quirks of VS2013.\n\nThe question is: out of Proposal3 and Proposal4b, which will be the most painful break?\n\nProposal4b will hurt people who declare things that used to be okay under the old quirky rules but are no longer okay. We haven't discovered many cases yet.\n\nProposal3, as we said before, will hurt people who invoked x.m(1) in the case identified above. Their workaround is to change the callsite with an explicit cast. There is precedent for this: the overload resolution rules between VB and C# are different, and VB people have to put explicit casts in other callsites.\n\nCOM is an interesting case where you generally have IFoo1 and IFoo2 where IFoo2 duplicates (doesn't inherit) the methods of IFoo but also adds a few others. However we don't see this as a problem. It's very nontypical to declare a third interface IBar which inherits both IFoo1 and IFoo2 in COM scenarios.\n\nIn the light of this new evidence, we prefer Proposal3. It will be a better cleaner future for the VB language to declare things like this. And it puts the pain on callsites to ambiguous interfaces, rather than producers of them; it's generally easier to fix callsites. As for the breaking changes, some of them will be silently picking more appropriate overloads, which is generally the right thing to do and more intuitive. Only in rare and contrived cases (where C# author overrides two ambiguous specific methods with a less specific methods) will there be a compile-time failure.\n\nNote that the VS2015 CTP4 (already shipped by the time we had this LDM) lets you declare things like \"C\" but there's not even any overload resolution at the callsite. That will give us lots of opportunity to hear from customers whether they're suffering from the fact that we no longer do implicit shadowing. If we hear pain, then we can re-visit.\n\n"
  },
  {
    "path": "meetings/2014/LDM-2014-10-15.md",
    "content": "We've been reconsidering some details about the \"nameof\" operator. This was prompted by a few questions:\n\n* _Why can't I write \"nameof(this.p)\"? My convention is to always put 'this' in front of my fields and properties._\n* _Why does the IDE throw an exception when I rename symbols that appear in nameof expressions? Why is it so hard to write analyzers that work correctly in the face of nameof?_\n\nA revised spec is below. The chief difference from the original spec ([part1](https://roslyn.codeplex.com/discussions/552376) and [part2](https://roslyn.codeplex.com/discussions/552377)) is that now the argument of nameof(.) is just an expression, like any other expression in the language (in CTP4 it had been an unusual hybrid similar in some ways to the argument of typeof). The common cases of nameof will still be written the same as what's in CTP4, but some edge cases will be different.\n\nThere's one chief open design question remaining, detailed below.\n\nPlease let us know what you think!\n\n\n# nameof operator: revised spec\n\nThe nameof(.) operator takes one expression argument (note that in C#, types are expressions). There are two principles: in essence, (1) the expression must \"have a name\", and (2) it must resolve to one single symbol.\n\n## Bread and butter cases\n```cs\n// Validate parameters \nvoid f(string s) {\n    if (s == null) throw new ArgumentNullException(nameof(s));\n}\n```\n\n```cs\n// MVC Action links\n<%= Html.ActionLink(\"Sign up\",\n             nameof(UserController),\n             nameof(default(UserController).SignUp()))\n%>\n```\n\n```cs\n// INotifyPropertyChanged\nint p {\n    get { return this._p; }\n    set { this._p = value; PropertyChanged(this, new PropertyChangedEventArgs(nameof(this.p)); }\n}\n```\n\n```cs\n// XAML dependency property\npublic static DependencyProperty AgeProperty = DependencyProperty.Register(nameof(default(C).Age), typeof(int), typeof(C));\n```\n\n```cs\n// Logging\nvoid f(int i) {\n    Log(nameof(f(i)), \"method entry\");\n}\n```\n\n```cs\n// Attributes\n[DebuggerDisplay(\"={\" + nameof(default(C).getString()) + \"()}\")]\nclass C {\n    string getString() { ... }\n}\n```\n\n_I'm sorry. Markdown keeps turning my plus symbols into ampersand hash 43. I don't know how to stop it._\n\nI call out the last two cases. If we decided to break principle (2), then we could allow method-groups, and hence omit the argument lists for these two cases. We could reasonably choose either to keep principle (2) or to break it, and there are pros and cons to both sides. More details in the post below.\n\n# Implementation\n```cs\nclass NameOfExpressionSyntax : ExpressionSyntax { readonly ExpressionSyntax argument; }\n```\nFor source code that compiles without errors, semanticModel.GetSymbolInfo(argument) will return a single symbol. For erroneous code it might also return 0 or many candidates.\n\n(Under the alternative option, where principle (2) is violated, then we would make GetSymbolInfo return no single preferred symbol, and instead always return a candidate list. Analyzers would now have to deal with this case for successful user code as well as for erroneous user code.)\n\n# C# Syntax\n```\nexpression: … | nameof-expression\n\nnameof-expression:\n    nameof ( nameof-expression-argument )\n\nnameof-expression-argument:\n    simple-name                  x\n    member-access                e.x, e.x<int>, e?.x,\n                                 int.TryParse, a::b.c\n    invocation-expression        e(args)\n    base-access-named            base.x\n```\n\nIt is helpful to list what is not allowed as the nameof argument. In general, nameof accepts expressions that have names (including type expressions that have names). All other arguments produce compile-time error \"This expression does not have a name\". Here are the expressions that are not allowed:\n```\n    assignment                   x += 15\n    query-expression             from y in z select y\n    lambda-expression            () => e\n    conditional-expression       a ? b : c\n    null-coalescing-expression   a?? b\n    binary-expression            ||, &&, |, ^, &, ==, !=,\n                                 <, >, <=, >=, is, as, <<,\n                                 >>, +, -, *, /, %\n    prefix-expression            +, -, !, ~, ++, --,\n                                 (cast)e, *, &\n    postfix-expression           ++, --\n    array-creation-expression    new C[…]\n    object-creation-expression   new C(…)\n    delegate-creation-expression new Action(…)\n    anonymous-object-creation-expression new {…}\n    typeof-expression            typeof(int)\n    checked-expression           checked(…)\n    unchecked-expression         unchecked(…)\n    default-value-expression     default(…)\n    anonymous-method-expression  delegate {…}\n    pointer-member-access        e->x\n    sizeof-expression            sizeof(int)\n    literal                      \"hello\", 15\n    parenthesized-expression     (x)\n    element-access               e[i]\n    this-access                  this\n    base-access-indexed          base[i]\n    await-expression             await e\n    nameof-expression            nameof(e)\n    vb-dictionary-lookup         e!foo \n```\n\nNote that there are some types which are not counted as expressions by the C# grammar. These are not allowed as nameof arguments (since the nameof syntax only allows expressions for its argument). It is a pleasant coincidence that none of these types even have names, so they wouldn't be useful as a nameof argument anyway. Even keywords like \"int\" and \"bool\" are not names; they are keywords. There's no need to spell out that the following things are not valid expressions, since that's already said by the language syntax, but I'm going to spell it out anyway. \n```\n    predefined-type              int, bool, float, object,\n                                 dynamic, string, void\n    nullable-type                Customer?\n    array-type                   Customer[,]\n    pointer-type                 Buffer*, void* \n```           \n\n# Semantics\n\nThe nameof expression is a constant. In all cases, nameof(…) is evaluated at compile-time to produce a string. Its argument is not evaluated at runtime, and is considered unreachable code (however it does not emit an \"unreachable code\" warning).\n\n_Name lookup._ The same rules of \"simple name lookup\" and \"member access\" apply to nameof arguments as they do to the rest of the language.\n\n_Accessibility._ The same rules of accessibility apply to nameof arguments as they do to all other expressions.\n\n_Error in binding._ The same rules of binding apply to nameof as to all other expressions. If binding to the argument/type would result in an error, e.g. to obsolete methods, then that is still an error for purposes of nameof.\n\n_Definite assignment._ The same rules of definite assignment apply to nameof arguments as they do to all other unreachable expressions.\n\n_VB invocation / indexing._ In VB, e(…) might be either an method invocation, a delegate invocation, an array indexing, a property access, a default property access, or an invocation of a parameterless function \"e\" followed by indexing. Which one of these it is, is determined by symbol resolution. After symbol resolution, as with C#, only method invocations are allowed as nameof arguments.\n\n_Result of the nameof operator._ This depends on the form of the nameof argument…\n\n__nameof(simple-name)__, of the form I<A1…AK>\n__nameof(member-access)__, of the form E.I<A1…AK>\n__nameof(base-access-named)__, of the form base.I<A1…AK>\n\nThese cases are all resolved using the rules for simple name lookup $7.6.2 or member access $7.6.4. If they succeed in binding, they must bind to one of:\n\n* A method-group. This produces an error \"To specify the name of a method, you must provide its arguments\".\n* A variable, value, parameter, constant, enumeration-member, property-access, field, event, type-parameter, namespace or type. In this case the result of the nameof operator is simply \"I\", which is generally the name of the symbol that the argument bound to. There are some caveats…\n\nIf \"I\" identified an alias e.g. \"using I = X.Y.Z; nameof(I)\", then the result of nameof is still \"I\", even though the expression bound to the type X.Y.Z.\n\nAlso \"I\" undergoes the standard identifier transformations prior to being returned from nameof. In C# these are detailed in $2.4.2 of the C# spec: first any leading @ is removed, then Unicode escape sequences are transformed, and then any formatting-characters are removed. This of course still happens at compile-time. In VB, any surrounding [] is removed.\n\nAlso in VB the result has the capitalization that was used in the argument. This might be different from the capitalization of the symbol that the argument bound to.\n\n\n__nameof(invocation-expression)__, of the form F(args)\n\nThe invocation expression must be either a method-invocation because F was a method-group, or a delegate-invocation because F was a value of delegate type.\n\n* If a method-invocation, then F must have had the form E.I<A1…AK> or I<A1…AK> or base.I<A1…AK> from other rules in the language, and must have bound to a method-group. F(args) must bind to a unique method by the normal rules of overload resolution. The result of the nameof operator is simply I, subject to the same transformations as above.\n\n* If a delegate-invocation, it is a compile-time error \"This expression does not have a name.\"\n\n# Examples\n\n```cs\nvoid f(int x) {\n   nameof(x)\n}\n// result \"x\": Parameter (simple name lookup)\n```\n\n```cs\nint x=2; nameof(x)\n// result \"x\": Local (simple name lookup)\n```\n\n```cs\nconst x=2; nameof(x)\n// result \"x\": Constant (simple name lookup)\n```\n\n```cs\nclass C {\n   int x;\n   … nameof(x)\n}\n// result \"x\": Field (simple name lookup)\n```\n\n```cs\nclass C {\n   void f() {}\n   … nameof(f)\n}\n// result: error \"To specify the name of a method, you must provide its arguments\": Method-group (simple name lookup)\n```\n\n```cs\nclass C {\n   void f() {}\n   … nameof(f())\n}\n// result \"f\": Invocation-expression that resolves successfully\n```\n\n```cs\nclass C {\n   void f(){}\n   void f(int i){}\n   … nameof(f(1))\n}\n// result \"f\": Invocation-expression that resolves successfully\n```\n\n```cs\nCustomer c; … nameof(c.Age)\n// result \"Age\": Field (member access)\n```\n\n```cs\nCustomer c; … nameof(c._Age)\n// result error \"_Age is inaccessible due to its protection level: Private field (member access)\n```\n\n```cs\nnameof(Tuple.Create)\n// result error \"To specify the name of a method, you must provide its arguments\": Method-group (member access)\n```\n\n```cs\nnameof(Tuple.Create(1,2))\n// result \"Create\": Invocation-expression that resolves successfully, including with generic type inference\n```\n\n```cs\nnameof(System.Exception)\n// result \"Exception\": Type (member access)\n```\n\n```cs\nnameof(List<int>)\n// result \"List\": Type (simple name lookup)\n```\n\n```cs\nnameof(List<>)\n// result error \"type expected\": Unbound types are not valid expressions\n```\n\n```cs\nnameof(List<int>.Length)\n// result error \"List<int> doesn't contain a member Length\": Member access, is unable to find an static member named Length on this type\n```\n\n```cs\nnameof(default(List<int>))\n// result error \"This expression doesn't have a name\": Not one of the allowed forms of nameof\n```\n\n```cs\nnameof(default(List<int>).Length)\n// result \"Length\": Property access (member access)\n```\n\n```cs\nnameof(int)\n// result error \"Invalid expression term 'int'\": Not an expression. Note that 'int' is a keyword, not a name.\n```\n\n```cs\nnameof(System.Int32)\n// result \"Int32\": Type (member access)\n```\n\n```cs\nusing foo=System.Int32;\nnameof(foo) \n// result \"foo\": Alias (simple name lookup)\n```\n\n```cs\nnameof(System.Globalization)\n// result \"Globalization\": Namespace (member access)\n```\n\n```cs\nnameof(x[2])\nnameof(\"hello\")\nnameof(1+2)\n// error \"This expression does not have a name\": Not one of the allowed forms of nameof\n```\n\n```vb\nNameOf(a!Foo)\n' error \"This expression does not have a name\": VB-specific. Not one of the allowed forms of NameOf.\n```\n\n```vb\nNameOf(dict(\"Foo\"))\n' error \"This expression does not have a name\": VB-specific. This is a default property access, which is not one of the allowed forms.\n```\n\n```vb\nNameOf(dict.Item(\"Foo\"))\n' error \"This expression does not have a name\": VB-specific. This is an index of a property, which is not one of the allowed forms.\n```\n\n```vb\nNameOf(arr(2))\n' error \"This expression does not have a name\": VB-specific. This is an array element index, which is not one of the allowed forms.\n```\n\n```vb\nDim x = Nothing\nNameOf(x.ToString(2))\n' error \"This expression does not have a name\": VB-specific. This resolves to .ToString()(2), which is not one of the allowed forms.\n```\n\n```vb\nDim o = Nothing\nDim b As Func(Of Object, Object, Boolean) = AddressOf o.Equals\n' result \"Equals\". Warning \"Access of static member of instance; instance will not be evaluated\": VB-specific. VB allows access to static members off instances, but emits a warning.\n```\n\n```cs\n[Foo(nameof(C))]\nclass C {}\n// result \"C\": Nameof works fine in attributes, using the normal name lookup rules.\n```\n\n```cs\n[Foo(nameof(T))]\nclass C<T> {}\n// result error \"T is not defined\": A class type parameter is not in scope in an attribute on that class\n```\n\n```cs\n[Foo(nameof(T))] void f<T> { }\n// result error \"T not defined\": A method type parameter is not in scope in an attribute on that method\n```\n\n```cs\nvoid f([Attr(nameof(x))] int x) {}\n// result error \"x is not defined\": A parameter is not in scope in an attribute on that parameter, or any parameter in the method\n```\n\n```vb\nFunction f()\n  nameof(f)\nEnd Function\n' result \"f\": VB-specific. This is resolved as an expression which binds to the implicit function return variable\n```\n\n```vb\nNameOf(New)\n' result error \"this expression does not have a name\": VB-specific. Not one of the allowed forms of nameof. Note that New is not a name; it is a keyword used for construction.\n```\n\n```vb\nClass C\n  Dim x As Integer\n  Dim s As String = NameOf(x)\nEnd Class\n' result \"x\": VB-specific. Field access (simple name lookup)\n```\n\n```cs\nclass C {\n   int x;\n   string s = nameof(x);\n}\n// result error \"cannot reference non-static field\": C#-specific. Normal  name referencing error\n```\n\n```cs\nclass C {\n   int x;\n   string s = nameof(C.x);\n}\n// error \"C doesn't contain a member named x\": Normal member access rules, with static/instance mismatch\n```\n\n```cs\nclass C {\n   int x;\n   string s = nameof(default(C).x);\n}\n// result \"x\": This is the C# idiom for getting the name of an instance variable.\n```\n\n```cs\nstruct S {\n   int x;\n   S() {var s = nameof(x); …}\n}\n// result \"x\": Field access (simple name lookup). Nameof argument is considered unreachable, and so this doesn't violate definite assignment.\n```\n\n```cs\nint x; … nameof(x); x=1;\n// result \"x\": Local access (simple name lookup). Nameof argument is unreachable, and so this doesn't violate definite assignment.\n```\n\n```cs\nint x; nameof(f(ref x));\n// result \"f\": Invocation expression. Nameof argument is unreachable and so can be used as a ref argument prior to definite assignment.\n```\n\n```cs\nvar @int=5; nameof(@int)\n// result \"int\": C#-specific. Local (simple name lookup). The leading @ is removed.\n```\n\n```cs\nnameof(m\\u200c\\u0065)\n// result \"me\": C#-specific. The Unicode escapes are first resolved, and the formatting character \\u200c is removed.\n```\n\n```vb\nDim [Sub]=5 : NameOf([int])\n' result \"int\": VB-specific. Local (simple name lookup). The surrounding [.] is removed.\n```\n\n# Chief Open Design Question\n\nPrinciple (2) says the nameof argument must resolve to one single symbol. Is this a principle worth sticking to? It could go either way. Let's examine the issues, starting with some concrete examples...\n\n```cs\n// Logging\nvoid f(int i) {\n    Log(nameof(f(i)), \"method entry\");\n}\n```\n\n```cs\n// Attributes\n[DebuggerDisplay(\"={\" + nameof(default(C).getString()) + \"()}\")]\nclass C {\n    string getString() { ... }\n}\n```\n\nIf we decided to break principle (2), then we could allow method-groups, and hence omit the argument lists for these two examples. We could reasonably choose either to keep principle (2) or to break it, and there are pros and cons to both sides.\n\n## Comparison: code\n```cs\nvoid M(int i) {\n}\nvoid M(string s) { \n    var x = nameof(M);    // error with principle (2); okay without it\n    var x = nameof(M(s)); // okay\n    var x = nameof(M(s)); // okay\n}\n```\n\n## Comparison: logging code\n```cs\n// Logging\nvoid f(int i) {\n    Log(nameof(f(i)), \"method entry\"); // with principle (2) you have to supply arguments\n    Log(nameof(f), \"method entry\"); // without it, you can omit arguments\n}\n```\n\n## Comparison: attributes\n```cs\n// Attributes\n[DebuggerDisplay(nameof(default(C).getString())] // with principle (2) you supply parentheses\n[DebuggerDisplay(nameof(default(C).getString)] // without it, you can omit them\nclass C {\n    string getString() { ... }\n}\n```\n\n## Comparison: IDE behavior\n\nWith principle (2), IDE refactoring behavior will be understandable, e.g. if you rename M then you can anticipate how it will be renamed inside nameof arguments. It's easy to understand+predict what HighlightAllReferences and GoToDef and FindAllReferences will do.\n\nWithout principle (2), IDE refactoring becomes less predictable. What will happen if you rename-refactor the second \"M\" in _Comparison:Code_? Would it rename the first one as well, and also the nameof argument? It's also not clear how CodeLens and other tools would count nameof(M). Would it count it as a reference to all overloads of M? There are probably similar issues all over the IDE.\n\n## Comparison: typing burden\n\nWith principle (2), you always need to specify which overload of M you're referring to, even though they have the same name. (In mitigation, it's often quite easy to specify which overload. As in the logging case, you typically do it within the method you wish to name, and so you typically have parameters to hand).\n\n## Comparison: conceptual burden\n\nWithout principle (2), nameof will be the _only_ part of the language where \"method-group\" is a valid expression. Everywhere else it must be resolved to a single method.\n\n## Comparison: analyzer burden\n\nWith principle (2), it will be easier to write analyzers. They won't blow up in untested corner cases involving nameof.\n\n"
  },
  {
    "path": "meetings/2014/LDM-2014-10-23.md",
    "content": "# nameof operator: spec v5\nThe nameof(.) operator has the form nameof(expression). The expression must have a name, and may refer to either a single symbol or a method-group or a property-group. Depending on what the argument refers to, it can include static, instance and extension members.\n\nThis is v5 of the spec for the \"nameof\" operator. [[v1](https://roslyn.codeplex.com/discussions/552376), [v2](https://roslyn.codeplex.com/discussions/552377), [v3](https://roslyn.codeplex.com/discussions/570115), [v4](https://roslyn.codeplex.com/discussions/570364)]. The key decisions and rationales are summarized below. _Please let us know what you think!_\n\n\n# Rationale\n\nQuestion: why do we keep going back-and-forth on this feature?\n\nAnswer: I think we're converging on a design. It's how you do language design! (1) make a proposal, (2) _spec it out_ to flush out corner cases and make sure you've understood all implications, (3) _implement the spec_ to flush out more corner cases, (4) try it in practice, (5) if what you hear or learn at any stage raises concerns, goto 1.\n\n* _v1/2 had the problem \"Why can't I write nameof(this.p)? and why is it so hard to write analyzers?\"_\n* _v3 had the problem \"Why can't I write nameof(MyClass1.p)? and why is it so hard to name method-groups?\"_\n* _v4 had the problem \"What name should be returned for types? and how exactly does it relate to member lookup?\"_\n\nThis particular \"nameof v5\" proposal came from a combined VB + C# LDM on 2014.10.22. We went through the key decisions:\n\n1. __Allow to dot an instance member off a type? Yes.__ Settled on the answer \"yes\", based on the evidence that v1/v2 had it and it worked nicely, and v3 lacked it and ended up with unacceptably ugly \"default(T)\" constructions.\n2. __Allow to dot instance members off an instance? Yes.__ Settled on the answer \"yes\", based on the evidence that v1/v2 lacked it and it didn't work well enough when we used the CTP, primarily for the case \"this.p\"\n3. __Allow to name method-groups? Yes.__ Settled on the answer \"yes\", based on the evidence that v1/v2 had it and it worked nicely, and v3 lacked it and ended up with unacceptably ugly constructions to select which method overload.\n4. __Allow to unambiguously select a single overload? No.__ Settled on the answer \"no\" based on the evidence that v3 let you do this but it looked too confusing. I know people want it, and it would be a stepping stone to infoof, but at LDM we rejected these (good) reasons as not worth the pain. The pain is that the expressions look like they'll be executed, and it's unclear whether you're getting the nameof the method or the nameof the result of the invocation, and they're cumbersome to write.\n5. __Allow to use nameof(other-nonexpression-types)? No.__ Settled on the answer \"only nameof(expression)\". I know people want other non-expression arguments, and v1/v2 had them, and it would be more elegant to just write nameof(List<>.Length) rather than having to specify a concrete type argument. But at LDM we rejected these (good) reasons as not worth the pain. The pain is that the language rules for member access in expressions are too different from those for member access in the argument to nameof(.), and indeed member access for StrongBox<>.Value.Length doesn't really exist. The effort to unify the two concepts of member access would be way disproportionate to the value of nameof. This principle, of sticking to existing language concepts, also explains why v5 uses the standard language notions of \"member lookup\", and hence you can't do nameof(x.y) to refer to both a method and a type of name \"y\" at the same time.\n6. __Use source names or metadata names? Source.__ Settled on source names, based on the evidence... v1/v2/v3 were source names because that's how we started; then we heard feedback that people were interested in metadata names and v4 explored metadata names. But I think the experiment was a failure: it ended up looking like _disallowing_ nameof on types was better than picking metadata names. At LDM, after heated debate, we settled on source names. For instance `using foo=X.Y.Z; nameof(foo)` will return \"foo\". Also `string f<T>() => nameof(T)` will return \"T\". There are pros and cons to this decision. In its favor, it keeps the rules of nameof very simple and predictable. In the case of nameof(member), it would be a hindrance in most (not all) bread-and-butter cases to give a fully qualified member name. Also it's convention that \"System.Type.Name\" refers to an unqualified name. Therefore also nameof(type) should be unqualified. If ever you want a fully-qualified type name you can use typeof(). If you want to use nameof on a type but also get generic type parameters or arguments then you can construct them yourself, e.g. nameof(List<int>) + \"`2\". Also the languages have no current notion of metadata name, and metadata name can change with obfuscation.\n7. __Allow arbitrary expressions or just a subset?__ We want to try out the proposal \"just a subset\" because we're uneasy with full expressions. That's what v5 does. We haven't previously explored this avenue, and it deserves a try.\n8. __Allow generic type arguments?__ Presumably 'yes' when naming a type since that's how expression binding already works. And presumably 'no' when naming a method-group since type arguments are used/inferred during overload resolution, and it would be confusing to also have to deal with that in nameof. [this item 8 was added after the initial v5 spec]\n\n\nI should say, we're not looking for unanimous consensus -- neither amongst the language design team nor amongst the codeplex OSS community! We hear and respect that some people would like something closer to infoof, or would make different tradeoffs, or have different use-cases. On the language design team we're stewards of VB/C#: we have a responsibility to listen to and understand _every opinion_, and then use our own judgment to weigh up the tradeoffs and use-cases. I'm glad we get to do language design in the open like this. We've all been reading the comments on codeplex and elsewhere, our opinions have been swayed, we've learned about new scenarios and issues, and we'll end up with a better language design thanks to the transparency and openness. I'm actually posting these notes on codeplex as my staging ground for sharing them with the rest of the team, so the codeplex audience really does see everything \"in the raw\".\n\n# C# Syntax\n```\nexpression: ... | nameof-expression\n\nname-of-expression:\n    nameof ( expression )\n```\nIn addition to the syntax indicated by the grammar, there are some additional syntactic constraints: (1) the argument expression can only be made up out of simple-name, member-access, base-access, or \"this\", and (2) cannot be simply \"this\" or \"base\" on its own. These constraints ensure that the argument looks like it has a name, and doesn't look like it will be evaluated or have side effects. I found it easier to write the constraints in prose than in the grammar.\n\n[clarification update] Note that member-access has three forms, `E.I<A1...AK>` and `predefined-type.I<A1...AK>` and `qualified-alias-member.I`. All three forms are allowed, although the first case `E` must only be made out of allowed forms of expression.\n\nIf the argument to nameof at its top level has an unacceptable form of expression, then it gives the error \"This expression does not have a name\". If the argument contains an unacceptable form of expression deeper within itself, then it gives the error \"This sub-expression cannot be used as an argument to nameof\".\n\nIt is helpful to list some things not allowed as the nameof argument:\n```\n    invocation-expression        e(args)\n    assignment                   x += 15\n    query-expression             from y in z select y\n    lambda-expression            () => e\n    conditional-expression       a ? b : c\n    null-coalescing-expression   a?? b\n    binary-expression            ||, &&, |, ^, &, ==, !=,\n                                 <, >, <=, >=, is, as, <<,\n                                 >>, +, -, *, /, %\n    prefix-expression            +, -, !, ~, ++, --,\n                                 *, &, (T)e\n    postfix-expression           ++, --\n    array-creation-expression    new C[…]\n    object-creation-expression   new C(…)\n    delegate-creation-expression new Action(…)\n    anonymous-object-creation-expression new {…}\n    typeof-expression            typeof(int)\n    checked-expression           checked(…)\n    unchecked-expression         unchecked(…)\n    default-value-expression     default(…)\n    anonymous-method-expression  delegate {…}\n    pointer-member-access        e->x\n    sizeof-expression            sizeof(int)\n    literal                      \"hello\", 15\n    parenthesized-expression     (x)\n    element-access               e[i]\n    base-access-indexed          base[i]\n    await-expression             await e\n    nameof-expression            nameof(e)\n    vb-dictionary-lookup         e!foo \n```\n\nNote that there are some types which are not counted as expressions by the C# grammar. These are not allowed as nameof arguments (since the nameof syntax only allows expressions for its argument). There's no need to spell out that the following things are not valid expressions, since that's already said by the language syntax, but here's a selection of some of the types that are not expressions:\n```\n    predefined-type              int, bool, float, object,\n                                 dynamic, string\n    nullable-type                Customer?\n    array-type                   Customer[,]\n    pointer-type                 Buffer*, void* \n    qualified-alias-member       A::B\n    void                         void\n    unbound-type-name            Dictionary<,>\n```           \n\n\n# Semantics\n\nThe nameof expression is a constant. In all cases, nameof(...) is evaluated at compile-time to produce a string. Its argument is not evaluated at runtime, and is considered unreachable code (however it does not emit an \"unreachable code\" warning).\n\n_Definite assignment._ The same rules of definite assignment apply to nameof arguments as they do to all other unreachable expressions.\n\n_Name lookup_. In the following sections we will be discussing member lookup. This is discussed in $7.4 of the C# spec, and is left unspecified in VB. To understand nameof it is useful to know that the existing member lookup rules in both languages either return a single type, or a single instance/static field, or a single instance/static event, or a property-group consisting of overloaded instance/static properties of the same name (VB), or a method-group consisting of overloaded instance/static/extension methods of the same name. Or, lookup might fail either because no symbol was found or because ambiguous conflicting symbols were found that didn't fall within the above list of possibilities.\n\n_Argument binding_. The nameof argument refers to one or more symbols as follows.\n\n__nameof(simple-name)__, of the form I or I<A1...AK>\nThe normal rules of simple name lookup $7.6.2 are used but with one difference...\n* The third bullet talks about member lookup of I in T with K type arguments. Its third sub-bullet says _\"Otherwise, the result is the same as a member access of the form T.I or T.I<A1...AK>. In this case, it is a binding-time error for the simple-name to refer to an instance member.\"_ For the sake of nameof(simple-name), this case does not constitute a binding-time error.\n\n\n__nameof(member-access)__, of the form E.I or E.I<A1...AK>\nThe normal rules of expression binding are used to evaluate \"E\", with _no changes_. After E has been evaluated, then E.I<A1...AK> is evaluated as per the normal rules of member access $7.6.4 but with some differences...\n* The third bullet talks about member lookup of I in E. Its sub-bullets have rules for binding when I refers to static properties, fields and events. For the sake of nameof(member-access), each sub-bullet applies to instance properties, fields and events as well.\n* The fourth bullet talks about member lookup of I in T. Its sub-bullets have rules for binding when I refers to instance properties, fields and events. For the sake of nameof(member-access), each sub-bullet applies to static properties, fields and events as well.\n\n__nameof(base-access-named)__, of the form base.I or base.I<A1...AK>\nThis is treated as nameof(B.I) or nameof(B.I<A1...AK> where B is the base class of the class or struct in which the construct occurs.\n\n\n_Result of nameof_. The result of nameof is the identifier \"I\" with the _standard identifier transformations_. Note that, at the top level, every possible argument of nameof has \"I<A1...AK>\".\n\n[update that was added after the initial v5 spec] If \"I\" binds to a method-group and the argument of nameof has generic type arguments at the top level, then it produces an error \"Do not use generic type arguments to specify the name of methods\". Likewise for property-groups.\n\nThe standard identifier transformations in C# are detailed in $2.4.2 of the C# spec: first any leading @ is removed, then Unicode escape sequences are transformed, and then any formatting-characters are removed. This of course still happens at compile-time. In VB, any surrounding [] is removed\n\n# Implementation\nIn C#, nameof is stored in a normal InvocationExpressionSyntax node with a single argument. That is because in C# 'nameof' is a contextual keyword, which will only become the \"nameof\" operator if it doesn't already bind to a programmatic symbol named \"nameof\". TO BE DECIDED: what does its \"Symbol\" bind to?\n\nIn VB, NameOf is a reserved keyword. It therefore has its own node:\n```vb\nClass NameOfExpressionSyntax : Inherits ExpressionSyntax\n    Public ReadOnly Property Argument As ExpressionSyntax\nEnd Class\n```\nTO BE DECIDED: Maybe VB should just be the same as C#. Or maybe C# should do the same as VB.\n\nWhat is the return value from `var r = semanticModel.GetSymbolInfo(argument)`? In all cases, r.Candidates is the list of symbol. If there is only one symbol then it is in r.Symbol; otherwise r.Symbol is null and the reason is \"ambiguity\".\n\nAnalyzers and the IDE will just have to deal with this case.\n\n\n# IDE behavior\n```cs\nclass C {\n   [3 references] static void f(int i) {...nameof(f)...}\n   [3 references] void f(string s) {...nameof(this.f)...}\n   [3 references] void f(object o) {...nameof(C.f)...}\n}\nstatic class E {\n   [2 references] public static void f(this C c, double d) {}\n}\n```\n\n__Highlight symbol from argument__: When you set your cursor on an argument to nameof, it highlights all symbols that the argument bound to. In the above examples, the simple name \"nameof(f)\" binds to the three members inside C. The two member access \"nameof(this.f)\" and \"nameof(C.f)\" both bind to extension members as well.\n\n__Highlight symbol from declaration__: When you set your cursor on any declaration of f, it highlights all nameof arguments that bind to that declaration. Setting your cursor on the extension declaration will highlight only \"this.f\" and \"C.f\". Setting your cursor on any member of C will highlight both all three nameof arguments.\n\n__Goto Definition__: When you right-click on an argument to nameof in the above code and do GoToDef, it pops up a FindAllReferences dialog to let you chose which declaration. (If the nameof argument bound to only one symbol then it would go straight to that without the FAR dialog.)\n\n__Rename declaration__: If you do a rename-refactor on one of the declarations of f in the above code, the rename will only rename this declaration (and will not rename any of the nameof arguments); the rename dialog will show informational text warning you about this. If you do a rename-refactor on the _last remaining_ declaration of f, then the rename will also rename nameof arguments. Note that if you turn on the \"Rename All Overloads\" checkbox of rename-refactor, then it will end up renaming all arguments.\n\n__Rename argument__: If you do a rename-refactor on one of the nameof arguments in the above code, the rename dialog will by default check the \"Rename All Overloads\" button.\n\n__Expand-reduce__: The IDE is free to rename \"nameof(p)\" to \"nameof(this.p)\" if it needs to do so to remove ambiguity during a rename. This might make nameof now bind to more things than it used to...\n\n__Codelens__: We've articulated the rules about what the argument of nameof binds to. The CodeLens reference counts above are a straightforward consequence of this.\n\n\n## Bread and butter cases\n```cs\n// Validate parameters \nvoid f(string s) {\n    if (s == null) throw new ArgumentNullException(nameof(s));\n}\n```\n\n```cs\n// MVC Action links\n<%= Html.ActionLink(\"Sign up\",\n             @typeof(UserController),\n             @nameof(UserController.SignUp))\n%>\n```\n\n```cs\n// INotifyPropertyChanged\nint p {\n    get { return this._p; }\n    set { this._p = value; PropertyChanged(this, new PropertyChangedEventArgs(nameof(this.p)); }\n}\n// also allowed: just nameof(p)\n```\n\n```cs\n// XAML dependency property\npublic static DependencyProperty AgeProperty = DependencyProperty.Register(nameof(Age), typeof(int), typeof(C));\n```\n\n```cs\n// Logging\nvoid f(int i) {\n    Log(nameof(f), \"method entry\");\n}\n```\n\n```cs\n// Attributes\n[DebuggerDisplay(\"={\" + nameof(getString) + \"()}\")]\nclass C {\n    string getString() { ... }\n}\n```\n\n# Examples\n\n```cs\nvoid f(int x) {\n   nameof(x)\n}\n// result \"x\": Parameter (simple name lookup)\n```\n\n```cs\nint x=2; nameof(x)\n// result \"x\": Local (simple name lookup)\n```\n\n```cs\nconst x=2; nameof(x)\n// result \"x\": Constant (simple name lookup)\n```\n\n```cs\nclass C {\n   int x;\n   ... nameof(x)\n}\n// result \"x\": Member (simple name lookup)\n```\n\n```cs\nclass C {\n   void f() {}\n   nameof(f)\n}\n// result \"f\": Member (simple name lookup)\n```\n\n```cs\nclass C {\n   void f() {}\n   nameof(f())\n}\n// result error \"This expression does not have a name\"\n```\n\n```cs\nclass C {\n   void f(){}\n   void f(int i){}\n   nameof(f)\n}\n// result \"f\": Method-group (simple name lookup)\n```\n\n```cs\nCustomer c; ... nameof(c.Age)\n// result \"Age\": Property (member access)\n```\n\n```cs\nCustomer c; ... nameof(c._Age)\n// result error \"_Age is inaccessible due to its protection level: member access\n```\n\n```cs\nnameof(Tuple.Create)\n// result \"Create\": method-group (member access)\n```\n\n```cs\nnameof(System.Tuple)\n// result \"Tuple\": Type (member access). This binds to the non-generic Tuple class; not to all of the Tuple classes.\n```\n\n```cs\nnameof(System.Exception)\n// result \"Exception\": Type (member access)\n```\n\n```cs\nnameof(List<int>)\n// result \"List\": Type (simple name lookup)\n```\n\n```cs\nnameof(List<>)\n// result error \"type expected\": Unbound types are not valid expressions\n```\n\n```cs\nnameof(List<int>.Length)\n// result \"Length\": Member (Member access)\n```\n\n```cs\nnameof(default(List<int>))\n// result error \"This expression doesn't have a name\": Not one of the allowed forms of nameof\n```\n\n```cs\nnameof(default(List<int>).Length)\n// result error \"This expression cannot be used for nameof\": default isn't one of the allowed forms\n```\n\n```cs\nnameof(int)\n// result error \"Invalid expression term 'int'\": Not an expression. Note that 'int' is a keyword, not a name.\n```\n\n```cs\nnameof(System.Int32)\n// result \"Int32\": Type (member access)\n```\n\n```cs\nusing foo=System.Int32;\nnameof(foo) \n// result \"foo\": Type (simple name lookup)\n```\n\n```cs\nnameof(System.Globalization)\n// result \"Globalization\": Namespace (member access)\n```\n\n```cs\nnameof(x[2])\nnameof(\"hello\")\nnameof(1+2)\n// error \"This expression does not have a name\": Not one of the allowed forms of nameof\n```\n\n```vb\nNameOf(a!Foo)\n' error \"This expression does not have a name\": VB-specific. Not one of the allowed forms of NameOf.\n```\n\n```vb\nNameOf(dict(\"Foo\"))\n' error \"This expression does not have a name\": VB-specific. This is a default property access, which is not one of the allowed forms.\n```\n\n```vb\nNameOf(dict.Item(\"Foo\"))\n' error \"This expression does not have a name\": VB-specific. This is an index of a property, which is not one of the allowed forms.\n```\n\n```vb\nNameOf(arr(2))\n' error \"This expression does not have a name\": VB-specific. This is an array element index, which is not one of the allowed forms.\n```\n\n```vb\nDim x = Nothing\nNameOf(x.ToString(2))\n' error \"This expression does not have a name\": VB-specific. This resolves to .ToString()(2), which is not one of the allowed forms.\n```\n\n```vb\nDim o = Nothing\nNameOf(o.Equals)\n' result \"Equals\". Method-group. Warning \"Access of static member of instance; instance will not be evaluated\": VB-specific. VB allows access to static members off instances, but emits a warning.\n```\n\n```cs\n[Foo(nameof(C))]\nclass C {}\n// result \"C\": Nameof works fine in attributes, using the normal name lookup rules.\n```\n\n```cs\n[Foo(nameof(D))]\nclass C { class D {} }\n// result \"D\": Members of a class are in scope for attributes on that class\n```\n\n```cs\n[Foo(nameof(f))]\nclass C { void f() {} }\n// result \"f\": Members of a class are in scope for attributes on that class\n```\n\n```cs\n[Foo(nameof(T))]\nclass C<T> {}\n// result error \"T is not defined\": A class type parameter is not in scope in an attribute on that class\n```\n\n```cs\n[Foo(nameof(T))] void f<T> { }\n// result error \"T not defined\": A method type parameter is not in scope in an attribute on that method\n```\n\n```cs\nvoid f([Attr(nameof(x))] int x) {}\n// result error \"x is not defined\": A parameter is not in scope in an attribute on that parameter, or any parameter in the method\n```\n\n```vb\nFunction f()\n  nameof(f)\nEnd Function\n' result \"f\": VB-specific. This is resolved as an expression which binds to the implicit function return variable\n```\n\n```vb\nNameOf(New)\n' result error \"this expression does not have a name\": VB-specific. Not one of the allowed forms of nameof. Note that New is not a name; it is a keyword used for construction.\n```\n\n```vb\nClass C\n  Dim x As Integer\n  Dim s As String = NameOf(x)\nEnd Class\n' result \"x\": Field (simple name lookup)\n```\n\n```cs\nclass C {\n   int x;\n   string s = nameof(x);\n}\n// result \"x\". Field (simple name lookup)\n```\n\n```cs\nclass C {\n   static int x;\n   string s = nameof(x);\n}\n// result \"x\". Field (simple name lookup)\n```\n\n```cs\nclass C {\n   int x;\n   string s = nameof(C.x);\n}\n// result \"x\". Member (member access)\n```\n\n```cs\nclass C {\n   int x;\n   string s = nameof(default(C).x);\n}\n// result error \"This expression isn't allowed in a nameof argument\" - default.\n```\n\n```cs\nstruct S {\n   int x;\n   S() {var s = nameof(x); ...}\n}\n// result \"x\": Field access (simple name lookup). Nameof argument is considered unreachable, and so this doesn't violate definite assignment.\n```\n\n```cs\nint x; ... nameof(x); x=1;\n// result \"x\": Local access (simple name lookup). Nameof argument is unreachable, and so this doesn't violate definite assignment.\n```\n\n```cs\nint x; nameof(f(ref x));\n// result error \"this expression does not have a name\".\n```\n\n```cs\nvar @int=5; nameof(@int)\n// result \"int\": C#-specific. Local (simple name lookup). The leading @ is removed.\n```\n\n```cs\nnameof(m\\u200c\\u0065)\n// result \"me\": C#-specific. The Unicode escapes are first resolved, and the formatting character \\u200c is removed.\n```\n\n```vb\nDim [Sub]=5 : NameOf([Sub])\n' result \"Sub\": VB-specific. Local (simple name lookup). The surrounding [.] is removed.\n```\n\n```cs\nclass C {\n  class D {}\n  class D<T> {}\n  nameof(C.D)\n}\n// result \"D\" and binds to the non-generic form: member access only finds the type with the matching arity.\n```\n\n```cs\nclass C<T> where T:Exception {\n  ... nameof(C<string>)\n}\n// result error: the type 'string' doesn't satisfy the constraints\n```\n\n"
  },
  {
    "path": "meetings/2014/README.md",
    "content": "# Visual Basic .NET Language Design Notes for 2014\n\nOverview of meetings and agendas for 2014\n\n\n## Feb 17, 2014\n\n[Visul Basic .NET Design Meeting Notes for Feb 17, 2014](LDM-2014-02-17.md)\n\na complete roll-up of all language features that are on the table \n\n\n## Feb 10, 2014\n\n[Visul Basic .NET Design Meeting Notes for Feb 10, 2014](LDM-2014-02-10.md)\n\n\nStrict Module \n\n\n## Mar 12, 2014\n\n[Visul Basic .NET Design Meeting Notes for Mar 12, 2014](LDM-2014-03-12.md)\n\nProtectedAndFriend access modifier, and faster CInt(.) \n\n## Apr 1, 2014\n\n[Visul Basic .NET Design Meeting Notes for Apr 1, 2014](LDM-2014-04-01.md)\n\nString interpolation \n\n\n## Apr 2, 2014\n\n[Visul Basic .NET Design Meeting Notes for Apr 2, 2014](LDM-2014-04-02.md)\n\nNull-propagating operator ?. \n\n## Apr 16, 2014\n\n[Visul Basic .NET Design Meeting Notes for Apr 16, 2014](LDM-2014-04-16.md)\n\n#Disable Warning, and ambiguity from unrelated interfaces \n\n## Apr 23, 2014\n\n[Visul Basic .NET Design Meeting Notes for Apr 23, 2014](LDM-2014-04-23.md)\n\nprimary constructors, and pattern-matching. \n\n## Jul 1, 2014\n\n[Visul Basic .NET Design Meeting Notes for Jul 7, 2014](LDM-2014-07-01.md)\n\n#Disable Warning revisited \n\n## Oct ,1 2014\n\n[Visul Basic .NET Design Meeting Notes for Oct 1, 2014](LDM-2014-10-01.md)\n\nrules for assignment to readonly autoprops in constructors, and preventing outsiders from implementing your interfaces \n\n## Oct 8, 2014\n\n[Visul Basic .NET Design Meeting Notes for Oct 8, 2014](LDM-2014-10-08.md)\n\nrevisit \"ambiguity from unrelated interfaces\" \n\n## Oct 15, 2014\n\n[Visul Basic .NET Design Meeting Notes for Oct 15, 2014](LDM-2014-10-15.md)\n\nrevised nameof operator \n\n\n## Oct 23, 2014\n\n[Visul Basic .NET Design Meeting Notes for Oct 23, 2014](LDM-2014-10-23.md)\n\nrevised nameof operator again. (Also some breaking changes for ambiguous unrelated interface members)"
  },
  {
    "path": "meetings/2015/LDM-2015-01-14-VB.md",
    "content": "VB Design Meeting 2015-01-14\n============================\n\n# Overload Resolution for String Interpolation\n\nDiscussion thread for these notes can be found at https://github.com/dotnet/roslyn/issues/46.\n\n# Summary\n\n* Exactly like C#, we will consider an interpolated string to be like a string in most cases such as overload resolution and searches for user-defined/intrinsic conversion. This implies that what the IDE intellisense shows after $\"hello\".| should be the same as that for regular strings.\n\n* We wrote out some gnarly type-inference test cases for overload resolution and array literals with interpolated strings, and explained the expected output.\n\n* We would like both C# and VB to give more actionable error messages if they end up binding to a factory Create method whose return type isn't right\n\n* We reaffirmed intended behavior for full-width characters in interpolated strings\n\n# Overload resolution for string interpolation\n\nWe want interpolated strings to be easily used as both String and FormattableString:\n```vb\n  Dim x As String = $\"hello {p}\"              ' works fine\n  Dim x As FormattableString = $\"hello {p}\"   ' works fine\n  Dim x = $\"hello {p}\"                        ' works fine, and infers x As String\n```\n\nThe question is about overload resolution... Which candidate should it prefer? Or should it be an ambiguity error?\n```vb\n  Sub f(x As FormattableString) : End Sub\n  Sub f(x As String) : End Sub\n\n  f($\"hello {p}\")    ' ... which does it pick?\n```\n\nOne important principle is that if there's an existing API `Sub f(x As String)` then consumers MUST be able to call it with `f($\"hello {p}\")`.\n\n\nAnother question is: if there's a language intrinsic conversion from string, does that conversion also apply to interpolated strings? e.g.\n```vb\n   Dim x As Char() = \"hello people\"  ' works fine\n   Dim x As Char() = $\"hello {x}\"    ' should this also work?\n```\nAnd separately, if there's a user-defined intrinsic conversion from string, does that conversion also apply to interpolated strings?\n\n(In C# the intention is that both should work. Have to verify that we've covered that in unit tests.)\n\n\n\n## API DESIGN Proposal 1a\n\"Some library APIs really want consumers to use FormattableString because it is safer or faster. The API that takes string and the API that takes FormattableString actually do different things and hence shouldn't be overloaded on the same name. Library authors will want to lead people to use interpolated strings, hence it should have a shorter name.\"\n```vb\n   Sub ExecuteQueryUnsafe(s As String) ...\n   Sub ExecuteQuery(s As FormattableString) ...\n\n   Sql.ExecuteQueryUnsafe(GetRegValueEx(path))\n   Sql.ExecuteQueryUnsafe(\"from p in people select p.Name\")\n   Sql.ExecuteQuery($\"from p in {x} select p.Name\")\n```\n\nQ. If they do different things, then wouldn't you want an ambiguity error here?\n\n\n## API DESIGN Proposal 1b\n\"In other library APIs, strings and FormattableStrings are equally fine; overloads make sense; we should prefer string overload because it will be more efficient\"\n```vb\n   Sub WriteLine(s As String) ...\n\n   Console.WriteLine(\"hello everyone\")\n   Console.WriteLine($\"hello {fred}\")\n```\n\nQ. Isn't it an *antipattern* for an API to have both String and FormattableString if they just do the same thing?\n\nA. Well, maybe, but it could be valid and useful to overload on both String and IFormattable. (Or an overload of both String and Object and then do a TryCast to IFormattable).\n\n\n## Proposal 2\n\"I don't like Safe/Unsafe. How about these names? ...\"\n```vb\n   Sub ExecuteQuery(s As String) ...\n   Sub ExecuteQuery(s As FormattableString) ...\n\n   Sql.ExecuteQuery(GetRegValueEx(path))\n   Sql.ExecuteQuery(\"from p in people select p.Name\")\n   Sql.ExecuteQueryWithFormat($\"from p in {x} select p.Name\")\n```\n\n\n## API DESIGN Proposal 3\n\"Someone will start with ExecuteQuery, and when they change the argument to $ then they won't see or understand the differently-named method. So let's pick the FormattableString overload which is most likely to be safe.\"\n```vb\n   Sub ExecuteQuery(s As String) ...\n   Sub ExecuteQuery(s As FormattableString) ...\n\n   Sql.ExecuteQuery(\"from p in people select p.Name\")  ' picks String overload\n   Sql.ExecuteQuery(GetRegValueEx(path))  ' picks String overload\n   Sql.ExecuteQuery($\"from p in {x} select p.Name\")  ' picks FormattableString overload\n```\n \nQ. What about the following consequence? Imagine an API has existed whose behavior is to format its string in a particular culture\n```vb\n   Sub f(x As IFormattable)\n   f($\"hello {p}\")\n```\nAnd later on down the line someone adds a new overload that takes string\n```vb\n   Sub f(x As String)\n```\nThen the user's call will change behavior upon recompilation.\n\n\n## RESOLUTION\nWe generally believe that libraries will mostly be written with different API names for methods which do different things. Therefore overload resolution differences between FormattableString and String don't matter, so string might as well win. Therefore we should stick with the simple principle that an interpolated string *is* a string. End of story.\n\nImplication: in intellisense `$\"hello\".|` will show extension methods off String, but will *NOT* show extension methods off FormattableString.\n\nImplication: both intrinsic and user-defined conversions that apply to string will also apply to interpolated string\n\nImplication: overload resolution will prefer String over FormattableString candidates when given an interpolated string argument.\n\nImplication: type inference works as follows.\n```vb\nSub f(Of T)(x As T)\nf($\"hello {p}\")\n' then it picks string. (it has *contributed* string as a candidate)\n\nSub f(Of T)(x As T, y As T)\nf($\"hello {p}\", CType(Nothing, FormattableString))\n' Then it gets two candidates, \"String\" and \"FormattableString\"\n' In most of the language (other than array literals), it checks whether\n' the *type* of each argument can convert to the candidate type.\n' In this case it will give an error.\n```\n\nImplication: if you have an array literal that contains an interpolated string expression\n```vb\n   Dim x = {$\"hello\", CType(Nothing, IFormattable)}\n```\nthen this will pick \"Object Assumed\" in Option Strict Off, and give an error in Option Strict On. The reason is that there is no dominant type between the candidate types \"String\" and \"IFormattable\". (There's no widening/identity conversion from one to the other, and there is a narrowing conversion from each to the other).\n\n\n## About the factory method that interpolation strings use\n\nThe language conversion rules bake in knowledge of `System.IFormattable` and `System.FormattableString` for their knowledge of widening conversions.\n\nThe compiler emits a call to a factory method when there is an interpolated string in source code. The factory method looks like this. There might be a whole family of overloaded Create methods.\n```vb\nSystem.Runtime.CompilerServices.FormattableStringFactory\n   Function Create(...) As ...\n```\nThe compiler separates the interpolated-string into a format string and a comma-separated list of expressions for the holes which it classifies as values before generating a call to `Create(fmtstring, expr1, expr2, ...)`. It will rely on normal VB overload resolution to pick the best Create method. This leaves the implementors of the factory free to do lots of nice optimizations.\n\nThe question is, what return type do we expect from the Create method?\n\nOption1: We could bake in the requirement that the factory method gives back a System.FormattableString, and this type must implement System.IFormattable, and do this as a pre-filter prior to doing overload resolution of the Create() overload family.\n\nOption2: Or we could merely invoke the method, and do a cast of the return type to IFormattable/FormattableString depends on what the user asked for. But then...\n* Do we give a warning if it has the [Obsolete] attribute?\n* Do we give a warning if it is narrowing?\n* What if it picks a Sub() ?\n\nOption3: Just do plain ordinary overload resolution, and if there were ANY errors or warnings, them emit them. In addition, if there were any errors (not just warnings that happened to be WarnAsError'd), then additionally report an error message at the same location \"The factory is malformed\". Precedent: we do this for queries. [Note: this message might appear or disappear if you change option strict on/off in your file].\n\nOption4: As with Option3 but enforcing it to use Option Strict On for its overload resolution and its conversion to IFormattable/FormattableString.\n\nRESOLUTION: Option3.\n\n\n\nQ. What about delegate relaxation level of $\"hello\" to FormattableString/IFormattable ?\n```vb\nSub f(lambda as Func(Of FormattableString))\nSub f(lambda as Func(Of String))\nf(Function() $\"hello\")\n```\nRESOLUTION: From the principle above, we'd like this to pick the String overload. The way to accomplish this is to classify the lambda conversion as DelegateRelaxationLevelReturnWidening.\n\n\n\nQ. What about full-width characters?\ne.g. does $\"{{\" give the non-full-width string \"{\" even if the two source characters had different widths?\ne.g. can you write $\"{p}\" where the open is wide and the close is normal width?\ne.g. there is no escape to put a full-width {, similar to how there's no escape to put a full-width \" ?\n\nRESOLUTION: Yes that's all fine.\n\n\n\n---\n\nThese are the workitems left to do...\n\nC#: additionally report error message about bad factory\nC#: verify (add a test case) that user-defined and intrinsic conversions on string really are used for interpolated strings.\nVB: change array literal dominant type stuff\nVB: all the dominant type stuff\nVB: fix up delegate relaxation level to be widening (and write test for it)\n\n"
  },
  {
    "path": "meetings/2015/README.md",
    "content": "# Visual Basic .NET Language Design Notes for 2015\n\nOverview of meetings and agendas for 2015\n\n\n## Jan 14, 2015\n\n[Visul Basic .NET Design Meeting Notes for Jan 14, 2015](LDM-2015-01-14-VB.md)\n\nOverload Resolution for String Interpolation\n\n"
  },
  {
    "path": "meetings/2016/LDM-2016-05-06-VB.md",
    "content": "# VB Design Notes for May 6, 2016\n\n# Agenda\n- ByRef Returns\n- Tuples\n\n## ByRef Returns\n\nToday, functions and properties may only return values. This feature allows them to return references to storage locations. This is legal in the CLR with some constraints.\n\nProposal is that we focus exclusively on the consumption scenario. The primary use-case for declaring members which return ByRef will be specialized collection classes (such as slice) that will almost certainly be written in C# and by a small number of people. It’s very valuable for VB users to be able to use such collection types but without more compelling use cases the production scenario has too much design baggage. Specifically, how to reconcile VB’s copy-in-copy out semantics for properties passed ByRef with returning properties ByRef.\n\nFurther, I propose we add no new syntax or take a reference to a storage location, or create a ByRef local. This would limit the use of such collection types to exactly the scenarios supported today by arrays with exactly the same usage syntax.\n\n### Decisions\n- Do we need special syntax to assign a reference to a ByRef local?\n\nNo.\n- What if there’s a read-write property that takes a ByRef ‘value’ in its setter?\n\nWe never call the setter.\n\n``` VB.NET\n' This will always assign the value at the location returned from the method to the location returned from the property.\nobjA.ByRefReturningProperty = objB.ByRefReturningMethod() \n```\n- What does the IDE show when you invoke a member with a ByRef return? Maybe nothing, as we do for arrays?\n\n``` VB.NET\n' Signature of ArraySlice(Of Integer).Item\nDefault Public ReadOnly Property Item(index As Integer) As ByRef Integer\n```\n\nSomething like that. The IDE team synthesizes invalid syntax for scenarios like this all the time (e.g. indexed properties in C# Metadata-as-source).\n- Passing a ByRef return to a late-bound method call?\n\n``` VB.NET\n' Where M returns a ByRef. We must copy-back.\nobj.LateBoundCall(M())\n```\n\nMake it work.\n- Assigning a late-bound property with a ByRef return.\n\nDoesn’t work.\n## Tuples\n\nTuples allow multiple values, potentially of different types, to be bundled up and passed around as a unit. This is primarily a platform interop feature so all decisions regarding the mutability of the tuple type, how the names of its members are persisted and read from metadata, how equality is computed, and the names and structure of the underlying tuple types are as decided in the C# LDM. \n### Decisions\n- What is the syntax for a tuple type with names?\n\n``` VB.NET\nDim p As (x As Integer, y As Integer)\n```\n- What is the syntax for a tuple type without names?\n\n``` VB.NET\nDim p As (Integer, Integer)\n```\n- Can I use this syntax in any ‘As’ clause where a type could appear today?\n  Yes. \n- Can attributes be applied to tuple element types? If so, how would this be persisted?\n\n``` VB.NET\nFunction GetFormatStringAndArgs() As (formatString As <FormatString> String, args As Object())\n```\n\nNo.\n- When a tuple type appears as the return type of a function or property, are the names of its elements in scope inside the body of the function or property?\n\n``` VB.NET\n' Multiple return values\nFunction GetMinMax(numbers As Integer()) As (min As Integer, max As Integer)\n    If numbers Is Nothing OrElse numbers.Length = 0 Then Return (0, 0)\n\n    min = numbers(0)\n    max = numbers(0)\n\n    For i = 1 To numbers.Length - 1\n        Dim n = numbers(i)\n\n        If n < min Then min = n\n        If n > max Then max = n\n    Next\nEnd Function\n\n' This feels like idiomatic VB.\n```\n\nOne major issue is that the parameter names and return variable names would share a namespace so this would be an error:\n\n``` VB.NET\n' Multiple return values\nFunction Pair(Of T1, T2)(first As T1, second As T2) As (first As T1, second As T2)\n    Return (first, second)\nEnd Function\n\n' Of course, since we're adding tuples to the language no one will ever write this method.\n```\n\nCounter-proposal: Auto “With” the return variable so you can use .min and .max in the scope of the function.\n\nLet's table this until we get more user/dogfooding feedback. We'll soon know whether this is essential our not.\n- How are tuple types convertible to one another?\n\nThey are element-wise convertible. The conversion is a widening conversion if and only if each element conversion is a widening conversion and narrowing if any conversion is narrowing.\nSame warnings for name mix-ups, case-insensitive name comparisons (of course).\n- What's the impact on the late-binder?\n\nWe might need to update the late-binder to support tuple conversions but not for tuple names. Lot of work and so many plot holes as names are associated with declarations, not values. This will also be a problem in the debugger since tuple names won't be there at runtime in many scenarios.\n- What is the syntax for a tuple literal expression without names?\n\n``` VB.NET\nM((0, 0))\n```\n- What is the syntax for a tuple literal expression with names?\n\n``` VB.NET\nM((x:=0, y:=0))\n```\n- Can you specify tuple elements out of order with named arguments?\n\n``` VB.NET\nM((x:=0, y:=0))\n```\n\nNo.\n- Do we infer names for the tuple elements as we do for anonymous type members?\n\n``` VB.NET\nDim x = 0, y = 0\nDim p = (x, y)\n' Names inferred from initializer.\nWriteLine($\"{p.x}, {p.y}\")\n```\n\nNo, as that would make it too difficult to make a tuple with no names.\n- How are tuple literals classified in the spec?\n\nInitially type-less, but reclassified as values after target-typing/type-inference. Analogous to array literals.\n\n``` VB.NET\n' The type of the literal is (Integer, Integer), not (String, String)\nDim p As (Integer, Integer) = (\"0\", \"0\")\n```\n- What should the SemanticModel.GetSymbolInfo in target typing scenarios?\n\n``` VB.NET\n' The type of the literal is (Integer, Integer), not (String, String)\nDim p As (x As Integer, y As Integer) = (x:=0, z:=0)\n```\n\nIf you bind 'x' in the 'x:=' it should bind as a _reference_ to the x element of the tuple, not a definition. Likewise binding 'z' should bind as would a named argument which does not refer to any parameter defined on that method. Basically, tuple expression names _always_ refer to elements declared elsewhere, either explicitly or implicitly, but are never considered definitions on their own. This means that z:= in this case is an error since (x As Integer, y As Integer) does not define any element z.\n- Is there a special syntax for decomposing a tuple into separate variables?\n\n``` VB.NET\nDim (x, y) = GetPoint()\nFor Each (x, y) In GetPoints()\nFrom (x, y) In GetPoints()\nLet (x, y) = GetPoint()\nSelect (x, y) = GetPoint() ' Can’t actually do this, breaking change.\n\n' Question: Superfluous parentheses seem not very VB-ish.\n```\n\nYes, but they need parenthesis. Resolves some ambiguities, such as the last example, which would be a breaking change.\n- Is there a special syntax for decomposing a tuple into separate values and assigning those values to multiple l-values?\n\n``` VB.NET\n(x, y) = GetPoint()\n```\n\nProbably. Though it will be the first time a statement in VB can begin with anything other than a keyword, an identifier, or a number.\n- Can operators “distribute” over tuple members provided the operator is defined on all members?\n\n``` VB.NET\nDim location = (0, 0)\nDim acceleration = (1, 2)\nFor i = 1 To 3\n    location += acceleration\nNext\n' location = (3, 6)\n```\n\nCute but nope.\n- Is it OK that tuple returns don’t allow naming return values but inferring return types for functions, properties, and multi-line lambdas.\n\n``` VB.NET\n' By default in VB, you can specify the name and shape of APIs without specifying any types.\nClass C\n    Private V\n    Property P\n    Sub S(a, ByRef b, Optional c = Nothing)\n    End Sub\n    Function F()\n    End Function\nEnd Class\n\n' This is already broken with Async and Iterator methods\nAsync Function FAsync()\nIterator Function EnumerateF()\n\nroot.ReplaceNodes(Function(original, rewritten) As (final, triviaPolicy)\n                      ' ...\n                      final = AddStuff(rewritten)\n                      triviaPolicy = TriviaPolicy.Preserve\n                  End Function)\n\n' Do we think this might be valuable in scripting?\n```\n\nThe (Type1, Type2) syntax is too compelling. It's much more likely to want to define a tuple with no names than one with inferred or dynamic types. \n"
  },
  {
    "path": "meetings/2016/README.md",
    "content": "# Visual Basic .NET Language Design Notes for 2016\n\nOverview of meetings and agendas for 2016\n\n\n## May 5, 2016\n\n[Visul Basic .NET Design Meeting Notes for May 5, 2016](LDM-2016-05-06.md)\n\n1. ByRef Returns\n2. Tuples\n"
  },
  {
    "path": "meetings/2017/README.md",
    "content": "# Visual Basic .NET Language Design Notes for 2017\n\nOverview of meetings and agendas for 2017\n\n**April**\n* [12th](vbldm-notes-2017.04.12.md)\n  * Proposal [#59](https://github.com/dotnet/vblang/issues/59): New conversion operator/syntax (`As Type`/`CVal`)\n\n**May**\n* [19th](vbldm-notes-2017.05.19.md)\n  * Default Interface Implementations\n\n**August**\n* [9th](vbldm-notes-2017.08.09.md)\n  * Issue [#37](https://github.com/dotnet/vblang/issues/37): Await in Catch/Finally\n  * Non-trailing named arguments\n* [23rd](vbldm-notes-2017.08.23.md)\n  * Scenario [#135](https://github.com/dotnet/vblang/issues/135): Late-binding without `Option Strict Off`\n    * Proposal [#136](https://github.com/dotnet/vblang/issues/136): `Dynamic` pseudo-type\n    * Proposal [#117](https://github.com/dotnet/vblang/issues/117): Method-scoped `Option` and `Imports` statements\n    * Proposal [#137](https://github.com/dotnet/vblang/issues/137): Late-bound member-access expressions\n    * Proposal [#43](https://github.com/dotnet/vblang/issues/43): Variable-scoped late-binding\n    * Proposal [#106](https://github.com/dotnet/vblang/issues/106): Erased interfaces\n  * Proposal [#152](https://github.com/dotnet/vblang/issues/152): `Out` arguments\n* [30th](vbldm-notes-2017.08.30.md)\n  * Nullable reference types\n\n**September**\n* 27th\n\n**October**\n* 4th\n* [18th](vbldm-notes-2017.10.18.md)\n  * Proposal [#101](https://github.com/dotnet/vblang/issues/101): JSON Literals\n    * Pattern matching\n  * Annotated types\n    * Proposal [#184](https://github.com/dotnet/vblang/issues/184): Tagged String literals (Related [#27](https://github.com/dotnet/vblang/issues/27): Guid literals)\n    * JSON types for JSON IntelliSense\n    * XML types for XML IntelliSense\n  * Proposal [#190](https://github.com/dotnet/vblang/issues/190): `Try` assignment\n\n**November**\n* [15th](vbldm-notes-2017.11.15.md)\n  * Proposal [#195](https://github.com/dotnet/vblang/issues/195) - `Static` Property Variables\n  * Proposal [#196](https://github.com/dotnet/vblang/issues/196) - Implicit Property Backing Fields\n  * Proposal [#197](https://github.com/dotnet/vblang/issues/197) - Inferred `Set` Parameter Type\n  * Scenario [#219](https://github.com/dotnet/vblang/issues/219) - Implementing INotifyPropertyChanged is Tedious\n    * Proposal [#107](https://github.com/dotnet/vblang/issues/107) - Replaceable Members\n    * Proposal [#198](https://github.com/dotnet/vblang/issues/198) - Bindable Classes and Properties\n    * Proposal [#107](https://github.com/dotnet/vblang/issues/194) - `WithPropertyEvents` Modifier to Enable Easy INotifyPropertyChanged Implementations\n    \n**December**\n* [6th](vbldm-notes-2017.12.06.md)\n  * Proposal [#25](https://github.com/dotnet/vblang/issues/25) - Range `1 To 10 Step 2` Expressions\n    * _Related: [#180](https://github.com/dotnet/vblang/issues/180) - For-loop should use larger type to avoid overflow exception_\n  * Proposal [#215](https://github.com/dotnet/vblang/issues/215) - Allow Attributes on Generic Type Parameters\n  * Proposal [#170](https://github.com/dotnet/vblang/issues/170) - New Tie-Breaker Rule for Resolving Ambiguity Between Overloads Which Differ By Refness of Arguments\n  * Proposal [#218](https://github.com/dotnet/vblang/issues/218) - Expression tree rewrite for string comparison in VB should product an operator invocation, not a method call to Operators.CompareString\n    * _Related: [#193](https://github.com/dotnet/vblang/issues/193) - Option Compare Ordinal (and OrdinalIgnoreCase?)_\n  * Proposal [#48](https://github.com/dotnet/vblang/issues/48) - Multiple `For` or `For Each` Control Variables Per Statement\n    * _Related: [#104](https://github.com/dotnet/vblang/issues/104) - Extend `For Each` Statement with Query Comprehensions_\n  * Proposal [#186](https://github.com/dotnet/vblang/issues/48) - `Exit For j` Statement to Break Out of Nested `For` and `For Each` Loops\n  * Proposal [#102](https://github.com/dotnet/vblang/issues/102) - Support Top-Level Statements in a Single Entry-Point File\n  * Scenario [#219](https://github.com/dotnet/vblang/issues/219) - Implementing INotifyPropertyChanged is Tedious\n    * Proposal [#107](https://github.com/dotnet/vblang/issues/107) - Replaceable Members\n    * Proposal [#198](https://github.com/dotnet/vblang/issues/198) - Bindable Classes and Properties\n    * Proposal [#107](https://github.com/dotnet/vblang/issues/194) - `WithPropertyEvents` Modifier to Enable Easy INotifyPropertyChanged Implementations\n"
  },
  {
    "path": "meetings/2017/vbldm-notes-2017.04.12.md",
    "content": "Agenda\r\n======\r\n\r\n-   New conversion operator/syntax\r\n\r\n-   GitHub repo review\r\n\r\nGuest attendee: Klaus Spoonman\r\n\r\nNew conversion operator/syntax\r\n==============================\r\n\r\nScenario\r\n--------\r\n\r\nToday VB has several casting syntaxes, each with subtle differences and performance implications. Nonetheless there are still some CLR conversions which are either inexpressible in VB or are only emitted with specific compilation options.\r\n\r\n### CType Conversions\r\n\r\nCType is the all-around conversion operator supporting the widest set of conversions in the language. CType has several short-hand conversion operators in the language, e.g. CStr, CInt, that are just aliases for CType with intrinsic destination types, e.g. CType(…, String). Depending on the situation CType may emit a single IL instruction, a method call, or a combination.\r\n\r\nCType supports the following conversion types:\r\n\r\n-   Runtime conversions\r\n\r\n    -   Boolean -&gt; Integer (True = -1)\r\n\r\n-   Unboxing conversion\r\n\r\n-   Reference conversions (upcasts/downcasts)\r\n\r\n-   Numeric conversions\r\n\r\n    -   Integral &lt;-&gt; Integral (opcode)\r\n\r\n    -   Floating point -&gt; Integral (Math.Round)\r\n\r\n-   Nullable conversions\r\n\r\n-   String conversions (Char &lt;-&gt; String, Char() &lt;-&gt; String)\r\n\r\n-   User-defined conversion operators\r\n\r\n-   Other language conversions\r\n\r\nCType does not support the following conversion types:\r\n\r\n-   Integer &lt;-&gt; Char (AscW, ChrW)\r\n\r\n-   Truncation\r\n\r\n-   Unchecked integral conversion (chopping)\r\n\r\nAdditionally CType will always behave like DirectCast for type parameter conversions.\r\n\r\n### DirectCast Conversions\r\n\r\nDirectCast supports native reference conversions only.\r\n\r\nProposal 1\r\n----------\r\n\r\n<https://github.com/dotnet/vblang/issues/59>\r\n\r\nAs Type\r\n-------\r\n\r\n-   Runtime conversions\r\n\r\n    -   Boolean -&gt; Integer (True = -1) (error)\r\n\r\n-   Unboxing conversion\r\n\r\n-   Reference conversions (upcasts/downcasts)\r\n\r\n-   Numeric conversions\r\n\r\n    -   Integral &lt;-&gt; Integral (opcode)\r\n\r\n    -   Floating point -&gt; Integral (Math.Round)\r\n\r\n-   Nullable conversions\r\n\r\n-   String conversions (Char &lt;-&gt; String, Char() &lt;-&gt; String)\r\n\r\n-   User-defined conversion operators\r\n\r\n-   Other language conversions\r\n\r\nTryCast like behavior – return null? Odd to throw sometimes and return null sometimes.\r\n\r\n(T)obj -&gt; Cast obj\r\n\r\nobj as T -&gt; TryCast(obj, T)\r\n\r\nProposal 2\r\n----------\r\n\r\nMagic method fix – emit special code for CInt(Math.Round(*floating-point*)) and CInt(Math.Truncate(*floating-point*)) and CInt(Int/Fix(*floating-point*))\r\n\r\nProposal 3\r\n----------\r\n\r\nExpand DirectCast to support native numeric conversions *but not* user-defined conversions.\r\n\r\nProposal 4\r\n==========\r\n\r\nChecked/Unchecked is orthogonal\r\n\r\nUpdate TryCast to convert to nullable value types.\r\n\r\nCVal(value, T) only for numeric types and enumerations and char.\r\n\r\nGitHub repo review\r\n==================\r\n"
  },
  {
    "path": "meetings/2017/vbldm-notes-2017.05.19.md",
    "content": "# Visual Basic Language Design Meeting Notes - 2017.05.19\n\n## Agenda\n* Default Interface Implementations\n\n## Discussion\n\n### Default Interface Implementations\n\n#### Q: Are there any syntactic ambiguities around default interface implementations in VB? In C# a definition with a body or without one can be determined by the presence or absence of a semicolon.\n\n**Follow-up: Need to look at parser and come back.**\n\n#### Modifiers\n\n| Modifier                                     | C#  | VB   | Notes |\n| -------------------------------------------- | --- | ---- | ----- |\n| Overridable (virtual) | Allowed, implied if there is a body | Same |  |\n| MustOverride (abstract) | Implied if (not static or private) and there is no body | Same |  |\n| NotOverridable (sealed) | Implied for static and private | Same | It's not permitted to make a NotOverridable Overrides. Means \"non virtual\" |\n| Public/Private/Friend | Allowed with normal meaning | Same |  |\n| Protected/Friend Protected/Private Protected | Allowed, but meaning is implementation specific |  |  |\n\n#### Allowed members in interfaces with bodies\n\n| Member | C#  | VB  | Notes |\n| ------ | --- | --- | ----- |\n| Instance methods | Yes |  |  |\n| Shared methods | Yes |  |  |\n| Instance fields | **No** |  |  |\n| Shared fields | Yes |  |  |\n| Instance constructors | No |  |  |\n| Shared constructors | TBD |  |  |\n| Instance finalizers | No |  |  |\n| Instance properties | Yes, but not auto |  |  |\n| Shared properties | Yes, auto is TBD |  |  |\n| Default properties (indexers) | N/A | Same as other properties |  |\n| Instance events | Yes, but must be Custom |  | Should have same restrictions as in classes (private `RaiseEvent`) |\n| Shared events | Yes, auto is TBD |  |  |\n| Nested types | Yes | Yes |  |\n| Operators | TBD |  |  |\n| Conversion operators | No | Same |  |\n\n**Follow-up: Verify event behavior makes sense with regard to WinRT events.**\n\n#### Q: Do we allow `Implements` clause?\n\n``` VB.NET\nInterface IBase\n\n    Sub M()\n\nEnd Interface \n\nInterface IDerived\n    Inherits IBase\n\n    ~~Overridable Sub N() Implements IBase.M~~\n\n    ~~End Sub~~\n\n    NotOverridable Sub N() Implements IBase.M\n\n    End Sub\nEnd Interface\n```\n\n**Yes**. `NotOverridable` allowed and implied.\n\n#### What does `MyClass` do in an interface?\nNothing special; it allows non-virtual calls.\n\n#### Q: Should we allow or forbid implicit interface implementations (like C#) now?\nBecause of the way the CLR looks up interface implementations (by name), if an interface declares an overridable member _and_ an implementor declares or inherits a public `Overridable`/`Overrides` member of the same name it will implicitly be picked up as the implementation/override of that interface member.\n\n**Options**\n* Make it an error\n* Recognize behavior (because we don't have a choice)\n* Allow `Overridable` or `MustOverride` methods to implement (interface members with bodies).\n\n**Decision Let's make it an error for now and evaluate implicit interface implementations separately.**\n"
  },
  {
    "path": "meetings/2017/vbldm-notes-2017.08.09.md",
    "content": "# Visual Basic Language Design Meeting - 2017.08.09\r\n\r\n### Agenda\r\n* Await in Catch/Finally\r\n* Non-trailing named arguments\r\n\r\n## Await in Catch/Finally\r\n\r\n**Differences from C#**\r\n\r\nVB allows jumping (`goto`) from the `Catch` block.\r\n\r\n``` VB.NET\r\nDim retryCount = 0\r\nTry\r\n    retry:\r\nCatch ex As Exception When retryCount < 3\r\n    retryCount += 1\r\n    GoTo retry\r\nEnd Try\r\n```\r\n\r\nDecision: The feature is approved in principle but needs its priority driven by other platform changes such as `IAsyncDisposable/Async Using`.\r\n\r\n## Non-Trailing Named Arguments\r\n\r\n### Attributes\r\nBecause in VB named argument syntax does not correspond to constructor arguments but field/property initialization this is not permitted in attribute.\r\n\r\n``` VB.NET\r\n<FooAttribute(0, Name:=\"A\")>\r\n```\r\n\r\n### Late-Binding\r\nLate-bound method invocations which have non-trailing named arguments raise a compile-time error.\r\n\r\nAction: Make sure we produce an error _after_ overload-resolution, not making method groups inapplicable.\r\n"
  },
  {
    "path": "meetings/2017/vbldm-notes-2017.08.23.md",
    "content": "# Visual Basic Language Design Meeting\r\nAugust 23rd, 2017\r\n\r\n## Agenda\r\n* Late-binding without `Option Strict Off`\r\n    * `Dynamic` pseudo-type\r\n    * Method-scoped `Option` and `Imports` statements\r\n    * Late-bound Member-Access expressions\r\n    * Variable-scoped late-binding\r\n    * Erased interfaces\r\n* `Out` arguments\r\n* Pipe-forward (`->`) operator\r\n\r\n## `Dynamic` pseudo-type\r\n\r\nFeels like it could be a light-weight solution.\r\n\r\nQ: What's the stack-ranking on this feature?\r\n\r\nQ: Is it just a safe alias for `Object` or is it more like C# `dynamic` in that it always late-binds even if a static member is available.\r\n\r\n## Method-scoped `Option` and `Imports` statements\r\n\r\nQ: Do we really want `Imports`? Seems kinda crazy.\r\nCould be useful, should break it out into another proposals.\r\n\r\nBetween this and a `Dynamic` type, I like this better.\r\n\r\nThis could dove-tail with an `Option Checked`.\r\n\r\n`Option`/`End Option` block. Blocked-scoped support types and namespaces in with block\r\n\r\n## Late-bound Member-Access expressions\r\n\r\n! means so much.\r\n\r\nThere's a feature here, but it might not add its weight.\r\nThe JSON thing is great. Oh, but it already works with ! so all the value just evaporated.\r\n\r\n## Erased interfaces\r\n\r\nNeeds more design\r\n\r\n## `Out` Arguments\r\n\r\nInvestigate C# -> VB -> C# and C# -> VB -> VB\r\n\r\nNew warning on a VB override\r\n\r\nRecognize the OutAttribute, require no In.\r\nDon't add an Out argument modifier\r\nOut parameter separately.\r\n\r\n"
  },
  {
    "path": "meetings/2017/vbldm-notes-2017.08.30.md",
    "content": "# Visual Basic Language Design Meeting - 2017.08.30\r\n\r\n### Agenda\r\n* Nullable reference type\r\n\r\n## Nullable reference types\r\nNot ready yet. Revisit after the C# Prototype is released and we have more user feedback and concrete design decisions. Also, the damnit operator `!` conflicts with both VBs dictionary-access operator `dict!key` and the type character for single-precision floating-point numbers `Dim radius!` so we'll have to resolve that.\r\n"
  },
  {
    "path": "meetings/2017/vbldm-notes-2017.10.18.md",
    "content": "# Visual Basic Language Design Meeting\nOctober 18th, 2017\n\n### Agenda\n* Proposal [#101](https://github.com/dotnet/vblang/issues/101): JSON Literals\n  * Pattern matching\n* Annotated types\n  * Proposal [#184](https://github.com/dotnet/vblang/issues/184): Tagged String literals (Related [#27](https://github.com/dotnet/vblang/issues/27): Guid literals)\n  * JSON types for JSON IntelliSense\n  * XML types for XML IntelliSense\n* Proposal [#190](https://github.com/dotnet/vblang/issues/190): `Try` assignment\n\n## Proposal [#101](https://github.com/dotnet/vblang/issues/101) - JSON Literals\n\nJSON is the _lingua franca_ of the cloud. First-class JSON support could be a strong attractant for first-time developers. The power of copy/paste/modify to jump start a project can't be overstated.\n\n``` VB.NET\n        Dim dow =\n            {\n               \"name\": NameOf(DayOfWeek),\n               \"type\": \"enum\",\n               \"subtype\": GetType(DayOfWeek).GetEnumUnderlyingType().Name,\n               \"members\": [\n                    (From f In GetType(DayOfWeek).GetFields(Reflection.BindingFlags.Public Or Reflection.BindingFlags.Static)\n                     Select {f.Name: CInt(f.GetValue(Nothing))})\n               ]\n            }\n```\n\n**Feedback**\n* If you want a top-level array we should drop the square brackets; the above code reads like \"member\" should be a one-element array whose first element is another array.\n  * The explicit syntax does allow interleaving fixed and generated elements in the list, but is that scenario worth it?\n* Embedded syntax, should there be any special syntax like XML's `<%= %>`? _No strong feelings_.\n* \"I like that it's so close to a general dictionary init syntax that it may be better thought of as that\" - I would say that new dictionary - followed by that syntax it should work. It could be a superset of JSON.\n  * The problem is the nested case. How do we know the List type? Do you restate the type or have a separate list syntax.\n\n### JSON Pattern Matching?\nRelated: [#139](https://github.com/dotnet/vblang/issues/139) - XML Patterns\n\nI think the principle for making a new \"literal\" or construction pattern is when the ceremony of creating an object(-graph) obscures the structure of the data itself. Therefore, I proposal the principle for introducing a pattern is when the ceremony of _inspecting_ and object(-graph) obscures the structure of the data.\n\nI haven't actually heard feedback that `.`, `!`, `.<>`, `.@`, and `...<>` obscure the structure of the underlying data when inspecting homogeneous collections. Therefore I believe the motivating example for any specialized patterns for JSON or XML would be dispatching over multiple possible structures nested within a larger one:\n\n``` VB.NET\nFor Each contact In account!contacts\n    Select Case contact\n        Case Match { \"type\": \"business\",\n                     \"company_name\": company,\n                     \"address\": address }\n\n            ' Handling for businesses.\n\n        Case Match { \"type\": \"individual\",\n                     \"email\": email }\n\n            ' Handling for individuals.\n\n        Case Match { \"type\": \"government\",\n                     \"agency\": agency,\n                     \"jurisdiction\": jurisdiction }\n\n            ' Handle government agency.\n\n    End Select\nNext\n``` \n\nIn the above example, each possible contact kind has different content. Inspecting and dispatching correctly would greatly obscure the actual structure of the data.\n\n* Decision: Table, wait for feedback/scenarios and more matching.\n\n## Annotated types\n\n### Proposal [#184](https://github.com/dotnet/vblang/issues/184)\nRelated: [#27](https://github.com/dotnet/vblang/issues/27) - GUID Literals\n\nAfter discussing the scenario for GUID literals with customers I don't believe they are necessary. There isn't a good case to be made for an expression typed as `System.Guid` as the dominant use case (attributes) can only take compile-time/CLR constants, i.e. strings. The only notable benefit I've heard from users is _validation_. This naturally leads one to consider an analyzer. The problem with the analyzer approach today is that 1) such an analyzer must inspect every string literal in the program, 2) such an analyzer would have to determine if a erroneously typed string were _intended_ to be a GUID before validating it.\n\nA simple general solution is a syntax that lets a user decorate a (magic) string literal with a bit of metadata. This metadata would (like a comment) have absolutely no effect on compilation. It would however make it trivial for a set of validation analyzers to target string literals _intended_ for validation _and_ to know what validation is required.  \n\nExample:\n\n``` VB.NET\n? \"{123e4567-e89b-12d3-a456-426655440000}\"#Guid\n```\n\nIn all ways such an annotated string literal would behave exactly as a string literal does today and the set of annotation identifiers would be open-ended. However, illustrative examples include: GUIDs, dates, URIs, IP addresses, paths, database connection strings, and format strings.\n\n**Feedback**\n* Using attributes would be better than a special tag.\n* Attribute should be on the producing APIs rather than the strings themselves. The advantage is that everyone can benefit without changing their code.\n  * Can you apply attributes to constants?\n* Could this be done with an analyzer? Does IOperation have the perf it needs to do this? _Test it_.\n\n**Bullets dodged**\n* **Discussion**: If the compiler understood annotations it could preserve them through type-inference at least.\n* **Question**: Could we add semantics that are generalizable? In a manner, nullable and tuple names are \"annotations\" applied to an underlying type. They enable us to report certain warnings, particularly around implicit conversions when, for example, element names are mismatched. Could be valuable in general to report conversion warnings between strings with different annotations or strings with and without annotations?\n* **Question**: Could this be further generalized to annotating any type?\n\n## XML and JSON\n\nIs there an even richer notion of an annotated type which could be used to add and track simple information about XML and JSON literals to better enable the IDE to provide completion when using XML-axis properties or the dictionary-access operator?\n\n``` VB.NET\nDim x As <contact>     ' Type: <contact>\nDim y = x.<address>    ' Type: <contact>.<address>\nDim z = y.<city>.Value\n```\n\n``` VB.NET\nDim a As {\"contact\"} ' Type: {\"contact\"}\nDim b = a!address    ' Type: {\"contact\"}.{\"address\"}\nDim c = b!city \n```\n\n**Feedback**\n* This is one end of the spectrum of providing a better tooling experience for untyped data over the wire. Type providers are on the other end.\n* We might be able to do a lot with no compiler changes and should investigate with IDE team.\n\n## Proposal [#190](https://github.com/dotnet/vblang/issues/190) - `Try` assignment\nRelated: [#175](https://github.com/dotnet/vblang/issues/175), [#159](https://github.com/dotnet/vblang/issues/159), [#132](https://github.com/dotnet/vblang/issues/132), [#67](https://github.com/dotnet/vblang/issues/67), [#60](https://github.com/dotnet/vblang/issues/60)\n\n**Feedback**\n* Are side-effects really that bad?\n* Syntax is weird because the right-hand side of the assignment can assign to the thing it's initializing; should it instead be forced to return a different value?\n  * But how would we represent the case where a failed \"Try\" should result in throwing or early exit?\n* Swift accomplishes this design with `if let` for positive cases and `guard let` for negative cases. Might that be a better design to explore?\n"
  },
  {
    "path": "meetings/2017/vbldm-notes-2017.11.15.md",
    "content": "# Visual Basic Language Design Meeting\nNovember 15th, 2017\n\n## Agenda\n* Proposal [#195](https://github.com/dotnet/vblang/issues/195) - `Static` Property Variables\n* Proposal [#196](https://github.com/dotnet/vblang/issues/196) - Implicit Property Backing Fields\n* Proposal [#197](https://github.com/dotnet/vblang/issues/197) - Inferred `Set` Parameter Type\n* Scenario [#219](https://github.com/dotnet/vblang/issues/219) - Implementing INotifyPropertyChanged is Tedious\n    * Proposal [#107](https://github.com/dotnet/vblang/issues/107) - Replaceable Members\n    * Proposal [#198](https://github.com/dotnet/vblang/issues/198) - Bindable Classes and Properties\n    * Proposal [#107](https://github.com/dotnet/vblang/issues/194) - `WithPropertyEvents` Modifier to Enable Easy INotifyPropertyChanged Implementations\n\n## Proposal [#195](https://github.com/dotnet/vblang/issues/195) - `Static` Property Variables\n\n**Decisions**\n* **Rejected**. We don't see why this one narrow use case for members nested within other members get's special treatment. If we want to enable nesting we'd look at local functions and types as well.\n\n## Proposal [#196](https://github.com/dotnet/vblang/issues/196) - Implicit Property Backing Fields\n\n**Decisions**\n* **Rejected**. The design team found this idea deeply unsettling.\n\n## Proposal [#197](https://github.com/dotnet/vblang/issues/197) - Inferred `Set` Parameter Type\n\n**Decisions**\n* **Approved-in-Principle**.\n\n**Discussion**\n\nTechnically the entire parameter list on `Set` is already optional and we could get most of the value of this proposal by stopping the IDE from generating it because an implicit parameter named `Value` is created. We could just color it blue. But it's also fairly easy to just do the \"inference\" as when we're creating the setter `MethodSymbol` we already have the type of the property in hand.\n\n## Scenario [#219](https://github.com/dotnet/vblang/issues/219) - Implementing INotifyPropertyChanged is Tedious\n\nThese three proposals fall on a spectrum from most general (#107) to most specific (#198), with #194 falling somewhere in between. We \n\nProposal #194 seems to strike a good balance. We like that it could support a few more scenarios than just `INotifyPropertyChanged`, e.g. logging, \"Freezable\" objects. How do we choose?\n\n* We know that we wouldn't want both `Bindable` properties and `WithPropertyEvents`; they're mutually exclusive.\n* We know that if we had either of the above that wouldn't stop us from doing `Replaces` w/ source generators at a future date.\n* We're fairly confident that if we had `Replaces` w/ source generators we wouldn't do `Bindable` or `WithPropertyEvents` as `INotifyPropertyChanged` is basically the poster child for the source generator feature.\n\nWe need to know the status of source generators and how far out they are before deciding. We should investigate and revisit with findings in a future meeting.\n\n**Decisions**\n* **Investigate status of source generators and revisit in future meeting**.\n\n### Proposal [#107](https://github.com/dotnet/vblang/issues/107) - Replaceable Members\n\nWe don't know the status of this and source generators. We should investigate and come back with findings in future meeting.\n\n### Proposal [#198](https://github.com/dotnet/vblang/issues/198) - Bindable Classes and Properties\n\n_\"Are the savings of this over #194 just the IDE automatically generating the bridge method? If so, we should go with the more general feature and just generate the correct code by default if you implement `INotifyPropertyChanged`\"_.\n\n### Proposal [#194](https://github.com/dotnet/vblang/issues/194) - `WithPropertyEvents` Modifier to Enable Easy INotifyPropertyChanged Implementations\n\nCan see a few use-cases for this. You could imagine implementing a \"freezable\" type immutable class whose properties all throw if you try to set them after the object has been \"frozen\". Need a better modifier though.\n"
  },
  {
    "path": "meetings/2017/vbldm-notes-2017.12.06.md",
    "content": "# Visual Basic Language Design Meeting\nDecember 6th, 2017\n\n## Agenda\n* Proposal [#25](https://github.com/dotnet/vblang/issues/25) - Range `1 To 10 Step 2` Expressions\n    * _Related: [#180](https://github.com/dotnet/vblang/issues/180) - For-loop should use larger type to avoid overflow exception_\n* Proposal [#215](https://github.com/dotnet/vblang/issues/215) - Allow Attributes on Generic Type Parameters\n* Proposal [#170](https://github.com/dotnet/vblang/issues/170) - New Tie-Breaker Rule for Resolving Ambiguity Between Overloads Which Differ By Refness of Arguments\n* Proposal [#218](https://github.com/dotnet/vblang/issues/218) - Expression tree rewrite for string comparison in VB should product an operator invocation, not a method call to Operators.CompareString\n    * _Related: [#193](https://github.com/dotnet/vblang/issues/193) - Option Compare Ordinal (and OrdinalIgnoreCase?)_\n* Proposal [#48](https://github.com/dotnet/vblang/issues/48) - Multiple `For` or `For Each` Control Variables Per Statement\n    * _Related: [#104](https://github.com/dotnet/vblang/issues/104) - Extend `For Each` Statement with Query Comprehensions_\n* Proposal [#186](https://github.com/dotnet/vblang/issues/48) - `Exit For j` Statement to Break Out of Nested `For` and `For Each` Loops\n* Proposal [#102](https://github.com/dotnet/vblang/issues/102) - Support Top-Level Statements in a Single Entry-Point File\n* Scenario [#219](https://github.com/dotnet/vblang/issues/219) - Implementing INotifyPropertyChanged is Tedious\n    * Proposal [#107](https://github.com/dotnet/vblang/issues/107) - Replaceable Members\n    * Proposal [#198](https://github.com/dotnet/vblang/issues/198) - Bindable Classes and Properties\n    * Proposal [#107](https://github.com/dotnet/vblang/issues/194) - `WithPropertyEvents` Modifier to Enable Easy INotifyPropertyChanged Implementations\n\n## Proposal [#25](https://github.com/dotnet/vblang/issues/25) - Range `1 To 10 Step 2` Expressions\n\n_Related: [#180](https://github.com/dotnet/vblang/issues/180) - For-loop should use larger type to avoid overflow exception_\n\nThis proposal was envisioned specifically for VB and from the `For` loop down, so to speak. Independently, [the C# Range proposal](https://github.com/dotnet/roslyn/blob/features/range/docs/features/range.md) was envisioned for C# and designed from `Span<T>`/slices up. After this morning's C# LDM it's clear that we'll need to reconcile the two designs to make sure both languages can share `Range` types and inter-operate nicely. As this is likely our last LDM in either language for the rest of 2017 due to holiday/vacations, we will review the broader VB design in the new year. \n\n**Decisions**\n* **Speclet needed**.\n\n## Proposal [#215](https://github.com/dotnet/vblang/issues/215) - Allow Attributes on Generic Type Parameters\n\n**Decisions**\n* **Approved-in-Principle**. This isn't on our backlog but provide it was of high quality we'd likely accept this as a community PR.\n\n## Proposal [#170](https://github.com/dotnet/vblang/issues/170) - New Tie-Breaker Rule for Resolving Ambiguity Between Overloads Which Differ By Refness of Arguments\n\n**Decisions**\n* **Approved-in-Principle**. We will likely need to do this to protect VB customers from breaks when API authors retro-fit `in` (readonly reference) parameter overloads on to existing methods.\n\n## Proposal [#218](https://github.com/dotnet/vblang/issues/218) - Expression tree rewrite for string comparison in VB should product an operator invocation, not a method call to Operators.CompareString\n\n_Related: [#193](https://github.com/dotnet/vblang/issues/193) - Option Compare Ordinal (and OrdinalIgnoreCase?)_\n\nEh, back compat concerns, trees, operators with methods, new VB runtime, fallbacks, LINQ providers should fix their stuff, CInt doesn't support binary literals or digit group separators, late-binding won't support the tie-breaker discussed in #170, needa solution.\n\n**Decisions**\n* **Speclet needed**.\n\n## Proposal [#48](https://github.com/dotnet/vblang/issues/48) - Multiple `For` or `For Each` Control Variables Per Statement\n\n_Related: [#104](https://github.com/dotnet/vblang/issues/104) - Extend `For Each` Statement with Query Comprehensions_\n\nVB already has a strong precedent for multiple consecutive statements/constructs of the same kind being combinable into a comma-separated list: `Imports`, `Dim`, `Next`, `From`, `Let`, `Case` (required in this case).\n\n**Decisions**\n* **Approved-in-Principle**. None of us could think of a good reason why this doesn't already work. Allowing the `For Each` case is virtually required by #104.\n\n## Proposal [#186](https://github.com/dotnet/vblang/issues/48) - `Exit For j` Statement to Break Out of Nested `For` and `For Each` Loops\n\nThe real motivator for this is that `Goto` is a code-smell and people want a less smelly solution to this problem.\n\n**Decisions**\n* **Approved-in-Principle, also do this for `Continue For` statement**.\n\n### Discussion\n\nWe use `Goto` all over the scanners and parsers in both languages and we don't feel bad about those uses because `Goto` seems the most appropriate way of expressing that control flow. And because you're going from a likely more descriptive label name to a likely brief control variable name this could actually be a less readable construct in many cases. But, VB already has a bit of a precedent here insofar as:\n\n1. The programmer can specify the specific block they want to exit at any time, e.g. `Exit Do`, `Exit While` to jump out of an outer loop or even out of an outer block via `Exit Select`.\n2. The `Next` statement already lets you specify multiple control variables to close multiple loops in one go.\n\n**Would it be better to have labeled loops like in Java?**\n \nMaybe, but doing the proposal doesn't preclude us doing what Java does later. And if your control variables are well named, e.g. `row` and `column` then requiring the programmer to label the entire loop might very well be redundant and people would complain about that.\n\n**Should we require or allow a comma-separated list of control variables like `Next`, e.g. `Continue For x, y`?**\nSeems reasonable\n\n**No**. In fact, for the `Continue` case that's not at all what's happening. One isn't continuing the inner loop _then_ continuing the outer one; one is simply skipping to the next iteration of the outer loop.\n\n## Proposal [#102](https://github.com/dotnet/vblang/issues/102) - Support Top-Level Statements in a Single Entry-Point File\n\nLast time we discussed this proposal we decided to take a wait-and-see approach with https://try.dot.net/. Today they use the scripting dialect of C# by virtue of using the Scripting API but based on discussions with them it would be beneficial to have the simplicity of top-level statements in the language(s) proper. For one, it means that all of the documentation sites/pages that are making use of trydotnet are technically teaching a slightly different version of the language with slightly different semantics. Let's try to reconcile the standard and scripting dialects in the new year.\n\n**Decisions**\n* **Deferred to January 2018**. \n\n## Scenario [#219](https://github.com/dotnet/vblang/issues/219) - Implementing INotifyPropertyChanged is Tedious\n\nIn our last deign meeting (two weeks ago) we looked at these three proposals on a spectrum from most general (#107) to most specific (#198), with #194 falling somewhere in between. The decision in that meeting was to take another look at our implementation concerns with [Source Generators](https://github.com/dotnet/roslyn/blob/features/range/docs/features/generators.md) to see if we could scope it down in such a way that it was achievable in the VB 16/C# 8 timeframe. Nope. While we bounced ideas around on how to constrain the behavior of generators to minimize the complexity and performance concerns it still feels like a _long_ lead to get it right both in design and implementation and especially iteration with the community for feedback. We absolutely cannot rush full meta-programming solution and our plate is pretty full already with HUGE ticket items for the next major version that generators are extremely unlikely to fit in either developer-time or calendar-time.\n\nProposal #194 seems to strike a good balance. We like that it could support a few more scenarios than just `INotifyPropertyChanged`, e.g. logging, \"Freezable\" objects.\n\n### Proposal [#107](https://github.com/dotnet/vblang/issues/107) - Replaceable Members\n\n**Decisions**\n* **Deferred to next release**.\n\n### Proposal [#198](https://github.com/dotnet/vblang/issues/198) - Bindable Classes and Properties\n\n**Decisions**\n* **Rejected**.\n\n### Proposal [#194](https://github.com/dotnet/vblang/issues/194) - `WithPropertyEvents` Modifier to Enable Easy INotifyPropertyChanged Implementations\n\n**Decisions**\n* **Approved for prototype/speclet**.\n"
  },
  {
    "path": "meetings/2018/README.md",
    "content": "# Visual Basic .NET Language Design Notes for 2018\n\nOverview of meetings and agendas for 2018\n\n## February\n\n* [7th](vbldm-notes-2018.02.07.md)\n  * C# Issue [#1208](hhttps://github.com/dotnet/csharplang/issues/1208) - C# Design Notes for nullable reference types\n  * Issue [#117](https://github.com/dotnet/vblang/issues/117) - Block-scoped Option Statements\n  * Issue [#211](https://github.com/dotnet/vblang/issues/211) - Discussion / proposal: usage of any installed programming language\n* 14th No meeting\n* [21st](vbldm-notes-2018.02.21.md)\n  * Community Update\n  * Upgrade Project - Discussion\n  * Private Protected - Discussion\n  * Issue [#37 Champion \"Await in Catch and Finally\"](https://github.com/dotnet/vblang/issues/37)\n  * Issue [#228 - Default property for reading and setting bit flags](https://github.com/dotnet/vblang/issues/228) (and others)\n  * [C# proposal: Default interface methods](https://github.com/dotnet/csharplang/blob/master/proposals/default-interface-methods.md)\n* [28th](vbldm-notes-2018.02.28.md)\n  * Implications of C# Range on Visual Basic\n  * Issue [#37 -Champion \"Await in Catch and Finally\"](https://github.com/dotnet/vblang/issues/37)\n  * C# Issue [#967 Proposal for tuple equality/inequality comparisons](https://github.com/dotnet/csharplang/pull/967)\n\n## March\n\n* Missed March 7 and 14\n* [21th](vbldm-notes-2018.03.21.md)\n  * MVP Summit recap\n  * Issue #86 [Optimize conversions from calls to Int/Fix functions and System.Math methods known to return whole Single/Double values to native opcodes](https://github.com/dotnet/vblang/issues/86)\n  * Issue #280 [Can The Visual Basic DLL Be Open Sourced?](https://github.com/dotnet/vblang/issues/280)\n  * Issue #282 [An update from the Design Safari on the `INotifyPropertyChanged` scenario](https://github.com/dotnet/vblang/issues/282)\n  * Anthony D. Green attended as a guest!\n\n## May\n\n* [30th](vbldm-notes-2018.05.30.md)\n  * Europe trip report, stability, possible survey\n  * Issue labels (marking what we've reviewed)\n  * Issue 305: In and Out operators\n  * Issue 304: Select TypeOf\n  * Issue 303: Null conditional operators for add/removeHandler\n  * Issue 301: Modify how literal strings are parsed\n  * Issue 167: Support for Return? construct\n\n## June\n\n*[13th](vbldm-notes-2018.06.13.md)\n  * Review process\n  * Issues reviewed\n\n## July-December\n\n* Issue review and Microsoft.VisualBasic.Runtime.dll planning\n\n## December\n\n* [19th](vbldm-notes-2018.12.19.md)\n  * Pattern Matching discussion/proposal from community\n"
  },
  {
    "path": "meetings/2018/vbldm-notes-2018.02.07.md",
    "content": "# Visual Basic Language Design Meeting\nFebruary 7,2018\n\n## Agenda\n* [C# Issue #1208 - C# Design Notes for nullable reference types](https://github.com/dotnet/csharplang/issues/1208)\n* [Issue #117 - Block-scoped Option Statements](https://github.com/dotnet/vblang/issues/117)\n* [Issue #211 - Discussion / proposal: usage of any installed programming language](https://github.com/dotnet/vblang/issues/211)\n\n## C# Issue [#1208](hhttps://github.com/dotnet/csharplang/issues/1208) - C# Design Notes for nullable reference types\n\n### Part 1: Implementing analysis\n\nC# has a prototype for \"nullable reference types\" which uses flow analysis to establish whether a reference is intended to allow null. \n\nThe user opts in per assembly. For other than a greenfield project, this results in a wall of compiler warnings, the user then works through these to resolve.\n\nThere are probably a significant number of VB (and C#) projects where retrofitting this behavior is not desirable. While these warnings are valuable, it's unclear how popular this feature will be. And it may feel like a \"not VB\" thing as we understand its usage.\n\nWe'll postpone this until we understand the uptake in C#.\n\n### Part 2: Marking an assemblies surface area with null intention\n\nIf a project opts into nullable reference warnings, it assumes all values received from assemblies that do not opt in may contain nulls. \n\nThere will be a technique for annotating assemblies' surface area for nullability. This is important for the .NET frameworks. It is not clear how this will work, and at least at the implementation level it won't be as simple as managing attributes. \n\nImplementing this would allow VB projects to express their nullability to C# projects, even if the VB project did not do null checks internally.\n\nIt is possible that VB could add the emitting attributes based on a simpler attributing system\n\nWe'll postpone this until we know how the framework will handle this scenario and how much interest there is in this cross language support.\n\n## Issue [#117](https://github.com/dotnet/vblang/issues/117) - Block-scoped Option Statements\n_Related: [#255](https://github.com/dotnet/vblang/issues/255) - Localised Compiler Options_\n\nThese issues suggest being able to limit the scope of Option Strict to a smaller block than the file.\n\nThis is a convenience feature. Options are set per file, not per class. This means that any code that needs looser Options could be refactored into another method and placed in a Partial class.\n\nConsidering all the options\n\n* Option Strict: Would provide value, possible to do\n* Option Explicit: Not seeing value, difficult to do\n* Option Compare: Not seeing high value, could create confusing code\n* Option Infer: This doesn't really make sense to us\n\nLeaving these two issues open for now, and requesting info on why #255 is not a duplicate. \n\n## Issue [#211](https://github.com/dotnet/vblang/issues/211) - Discussion / proposal: usage of any installed programming language\n\nFantastic idea, and too hard to do.\n\nLots of thought has gone into this over the years. It was considered in depth when Roslyn was designed, and has been considered since. It would require rewriting considerable parts of Roslyn.\n\nIt could be simplified somewhat if each type declaration was fully in one language or another. But, it would still need a new compiler and significant IDE work. \n\nAnd that would still leave open resolution of the many differences between C# and Visual Basic. The easiest of these differences to visualize are case sensitivity and overloads resolution.\n\nAfter rethinking again, the previous assessment that this is not practical stands. \n\nWe believe it is important to communicate this clearly to the community so that we can, move toward other tractable issues. We will not close the issue for now to allow further discussion.\n"
  },
  {
    "path": "meetings/2018/vbldm-notes-2018.02.21.md",
    "content": "# Visual Basic Language Design Meeting\n\nFebruary 21,2018\n\n## Agenda\n\n* Community Update\n* Upgrade Project - Discussion\n* Private Protected - Discussion\n* Issue [#37 -Champion \"Await in Catch and Finally\"](https://github.com/dotnet/vblang/issues/37)\n* Issue [#228 - Default property for reading and setting bit flags](https://github.com/dotnet/vblang/issues/228) (and others)\n* [C# proposal: Default interface methods](https://github.com/dotnet/csharplang/blob/master/proposals/default-interface-methods.md)\n\n## Community Update\n\n### Introduce?\n\nThere has been a request by the community for people to introduce themselves.\n\nThis will remain at the discretion of the individual.\n\n### Brice & EF\n\n@BriceLam has volunteered (side project) to maintain a repository for the development of a generator so migrations and reverse engineering work with VB projects.\n\nKathleen will help publicize.\n\nWhen the project nears completion, Kathleen will explore best permanent location with Brice and contributors.\n\nYeah Brice!\n\n### MVP Summit\n\nMVP Summit is March 5-8.\n\n#### Language Designers Panel\n\nKathleen will represent VB on the Language Designers Panel.\n\n#### Lunch session\n\nThere will be a lunch session on Visual Basic. Kathleen determined this odd time with Jeff to avoid placing it opposite a session with likely interest to VB developers. We assume all VB MVPs are also interested in other things.\n\n#### Hackathon\n\nThursday (March 8) at the MVP Summit there will be an MVP Hackathon.\n\nDo we want to organize something?\n\nNo, leave it to Brice on the EF generator and community for organization\n\n### Docs\n\nThere are some really out of date docs for VB and way too many docs for the docs teams to fix.\n\nKathleen will discuss with the community and hopefully get some help with this.\n\n### Blogpost with WebAPI example\n\n@KlausLoeffelmann is working on a blog post (with help from @obelink and others) that will illustrate VB working with a VB backend and an Angular front end.\n\nKathleen is working planning other blog posts.\n\n## Upgrade Project - Discussion\n\nThe customer problem: To change the version of VB a project is targeting, you have to edit the .vbproj file. Ick. Extra Ick because VB programmers put high value on simplicity/low ceremony.\n\nThe technical problem: 3-4 non-trivial features need to land to fix this. Want to do it, but won't be immediate.\n\nWith the delay, do we hold feature announcements or apologize that people have to edit right now?\n\nKathleen will corral the solution.\n\nDo not hold any announcements. The folks that want new features want them.\n\n## Private Protected - Discussion\n\nPrivate protected specifies that a member is only visible from code that is both within the same assembly and within a derived class.\n\nThe earlier decision was to parallel the IL names with VB styling and use FriendAndProtected and FriendOrProtected. FriendOrProtected would be a pretty listing fix for Protected Friend for symmetry.\n\nFor context, in C# this feature was requested loudly by a few people. An agonizing and relatively extreme attempt at a better named and the community accepted that the feature by any name was better than no feature. Thus it is `private protected` in C#. \n\nKathleen did not find an issue on this in VBLang.\n\nDuring implementation, we messed up. The feature was implemented in VB as `Private Protected` (in any order). The feature is currently present, but not announced. Because it is present, we will support `Private Protected` even if we did something else. \n\nClearly the earlier decision was more VB like. But, very few people care about the feature, it exists right now in VB as `Private Protected`, and coders may hear about the concept via C# blogs so parallel naming may have one advantage.\n\nDecision: Stick with what we've got because we've got it. If people use the feature and there is a push for clearer naming, deal with it then.\n\n## Issue [#37 - Champion \"Await in Catch and Finally\"](https://github.com/dotnet/vblang/issues/37)\n\nPartial discussion because @VSadov not present and he has the most history.\n\nThis was considered for an earlier release, but we ran out of time.\n\nIn general the work is similar to C#. But VB specific things, GoTo and OnError may make it more difficult.\n\nAt least some of the challenging scenarios aren't legal in async methods anyway.\n\nGoTo and OnError seem unlikely in \"modern\" code that would use Async. Perhaps we could narrow the scenarios to simplify implementation. \n\nReconsider with Vlad, probably next week.\n\nWe should check that this is important and how much work before we commit. Kathleen will see if a prioritization survey at the Summit makes sense and there will be time.\n\n## Issue [#228 - Default property for reading and setting bit flags](https://github.com/dotnet/vblang/issues/228) (and others)\n\nFlagged enums have challenges in both C# and VB. In VB they are rather painful. A solution at the API level would be great.\n\nAn enum constraint by itself does not allow this to be solved via extension methods. Darn.\n\nTabled for Kathleen to discuss with API team to see if this is on their radar.\n\n## [C# proposal: Default interface methods](https://github.com/dotnet/csharplang/blob/master/proposals/default-interface-methods.md)\n\nC# has a proposal for default interface members. A compelling scenario for this involves allowing interfaces to change over time without breaking all implementors. The implication is that people will then evolve interfaces, and if VB can't handle this, it will have a serious problem.\n\nC# and Runtime are designed and prototyped (for C# 8 timeframe). The design is not set.\n\nThere will still be issues with older compiler versions unable to access interfaces that have changed (C#/VB). So it's not clear how public interfaces will take advantage of this feature.\n\nTalk to @AnthonyDGreen for background.\n\nNo action."
  },
  {
    "path": "meetings/2018/vbldm-notes-2018.02.28.md",
    "content": "# Visual Basic Language Design Meeting\n\nFebruary 28,2018\n\n## Agenda\n\n* Implications of C# Range on Visual Basic\n* Issue [#37 -Champion \"Await in Catch and Finally\"](https://github.com/dotnet/vblang/issues/37)\n* C# Issue [#967 Proposal for tuple equality/inequality comparisons](https://github.com/dotnet/csharplang/pull/967)\n\n## Community Update\n\n### MVP Summit\n\nMVP Summit is March 5-8.\n\n## Implications of C# Range on Visual Basic\n\nThe C# LDM is discussing possibility adding operators to make range access easier. \n\nThis is to support programs that will use some of the new .NET Core API features for direct memory access and manipulation. These aren't expected to be high usage workflows in VB, but we don't want to block VB programmers from those scenarios.\n\nThe work to supply this feature will be about the same for Visual Basic, after the C# feature is specced. There is a high probability that there are more important features for VB. But, let's still take a look at syntax possibilities and more deeply at alternate approaches. \n\n### Potential Syntax\n\nSince the hat is currently used as a binary operator, it would be available as a unary operator.\n\n`.:` could be used for length.\n \nOpen ended `x..` and `..x` and `..` also work.\n\nThe To as a Range separator would be weird if the range was exclusive as anticipated. Not using that. `..` would work.\n\n```\nDim x = s.Slice(0..11) ' seems pretty VB like\n```\n\nWe believe that there is non-trivial amounts of VB code that are imprecise about the length of arrays - Dimming with the length instead of 1 minus the length. Consistent usually would generally allow this code to work fine, but if we allow counting from the end, and code has an array one to long, things will not work as expected. Nothing we can do about that.\n\nWait to see what C# does and whether we need syntax.\n\n### Using API Support\n\nIf index provides an implicit conversion from int, then VB can access the API. Or if integers are used, conversions to Range.\n \n```\nIndex i = Index.FromEnd(Int32 i)\n \nRange = New Range(2, Index.FromEnd(2))\nDim z1 = Slice(Range)\nDim z2 = Slice(New Range(2, Index.FromEnd(2))\n\nDim z3 = Slice(Range.StartAt(2))\nDim z4 = Slice(Range.Open)  ' maybe Range.All\nDim z5 = Slice(Range.EndAt(8))\nDim z6 = Slice(Range.FromEnd(2))\n```\n\nIt might be even cooler if there are conversions from tuples.\n\n```\n' Conversion from tuple of Index or integer\nDim z7 = Slice((2,3))\nDim s8 = Slice((2,Index.FromEnd(2)))\n```\n\nIf the API support is good enough, don't do the language work in VB. These APIs will allow older versions of Visual Basic (and C#) access these APIs and may come out reading more \"VB like\" than the dot dot range syntax. \n\nIf we can't get good enough for VB users, then reconsider.\n\nKathleen will discuss possibilities for API with API folks.\n\nNOTE: Following discussions with Immo on 3/1.\n\nThe API already has methods of the style discussed here. They do not have final names, so at the point that is firmed up, we can ensure it makes sense for VB. Conversions are possible, although Immo thought it was weird to go just one direction with the conversion and Range to Integer tuple is probably not sensible. \n\n## Issue [#37 -Champion \"Await in Catch and Finally\"](https://github.com/dotnet/vblang/issues/37)\n\nIn VB you can't Await in a Catch block. This makes it pretty much impossible to do some things after an exception that we assume user's would like to do. The language is blocking these scenarios, so can we fix it. \n\n@VSadov was present so we can complete last week's discussion.\n\nAwait in try catch is implemented by rewriting the code to use a complex state machine.\n\nIt is legal in VB (but not C#) to jump from inside a Catch to inside the Try. Await in catch in C# was implemented without support for this (obviously), and we aren't quite sure how to do it because nested Try/Catch create some interesting possibilities. \n\nIf we drop the difficult scenarios and provide support and disallow Await and these jumps to happen together, this is doable. \n\nLet's do it!\n\nKathleen to discuss resourcing.\n\n## C# Issue [#967 Proposal for tuple equality/inequality comparisons](https://github.com/dotnet/csharplang/pull/967)\n\nTuple equality is being considered for C#. Given that x and y are tuples\n\n```VB\nIf x.Equals(y) Then ' works today if they are of the same type\n\n' The following is not supported\nIf x = y Then ' in general probably means...\nIf x.First = y.First AndAlso x.Second = y.Second Then\n```\n\nEquality operator is a convenient and a manner of nicer style.\n\nSince the equality operator more different than Equals. It is not a reference equals, for example. Nullable value types also works some place in VB where it doesn't in C#.\n\nThis is likely to need different deep thought than C# (more than a port) to find VB behavior (quirks in a good way).\n\nMuch of the work in the feature comes when the types are different. Most of the value to the programmer occur when the types are the same.\n\nRan out of time to complete. \n"
  },
  {
    "path": "meetings/2018/vbldm-notes-2018.03.21.md",
    "content": "# Visual Basic Language Design Meeting\n\nMarch 21, 2018\n\n## Agenda\n\n* MVP Summit recap\n* Issue #86 [Optimize conversions from calls to Int/Fix functions and System.Math methods known to return whole Single/Double values to native opcodes](https://github.com/dotnet/vblang/issues/86)\n* Issue #280 [Can The Visual Basic DLL Be Open Sourced?](https://github.com/dotnet/vblang/issues/280)\n* Issue #282 [An update from the Design Safari on the `INotifyPropertyChanged` scenario](https://github.com/dotnet/vblang/issues/282)\n\nAnthony D. Green attended as a guest!\n\n## MVP Summit recap and poll discussion\n\nWe were able to communicate that helping with documentation counts as OSS contributions for MVP status and that testing is also considered. Need more work to track testing, but definitely issues raised on GitHub.\n\nWork was done on the EF Visual Basic generators at the Hackathon. This continues for now in [@BriceLam 's repo](https://github.com/bricelam/EFCore.VisualBasic)\n\n\n## Issue #86 [Optimize conversions from calls to Int/Fix functions and System.Math methods known to return whole Single/Double values to native opcodes](https://github.com/dotnet/vblang/issues/86)\n\nCInt and Fix call methods on System.Math, and are thus slow(ish).\n\nThere are two issues, this addressed only the optimization. This does not effect or comment on considering syntax enhancements.\n\nPeople that are currently using CInt(Fix()) want that optimized. While it seems slightly cryptic, it's the right way to get the truncated value and nothing else. This is what we can optimize.\n\nTreat it as an optimization, not a feature to keep it narrow and get it done.\n\nProbably some people that use CInt() probably don't care and do want optimization. But this is a breaking change and can't be done.\n\nDo we want an analyzer that finds slow CInts? It would change the semantics of the program. Probably won't do this. Folks might write this, that would be fine if they communicate usage. \n\nMaybe consider up-for-grabs once we have a proposal.\n\nAnthony has an analysis that he's going to send analysis that evaluates that results are identical.\n\nWhat about expression trees?\n\nExpression trees themselves will be unchanged. The IL output of expression trees is not expected to be high performance. Thus, plan to do what is easy. If code is shared, the optimization will also happen in the IL generation from expression trees.\n\nNeal will create an issue on Roslyn.\n\n## Issue #280 [Can The Visual Basic DLL Be Open Sourced?](https://github.com/dotnet/vblang/issues/280)\n\nIs this a request to build a new VB runtime that is based on .NET Core and standard?\n\nLooking at a new layering. Those things forever typed to Windows can't be handled the same way as things that could be in standard.\n\nWe'lll think further on this which needs discussion with the runtime folks.\n\nWe need more information on the goals of this request.\n\n## Issue #282 [An update from the Design Safari on the `INotifyPropertyChanged` scenario](https://github.com/dotnet/vblang/issues/282)\n\nWe spent the rest of the meeting with Anthony's demo for affecting behavior using attributes and compile time rewriting. Overall impression was positive. \n\n## Meetings\n\nWe will miss next week's meeting due to Kathleen's travel. "
  },
  {
    "path": "meetings/2018/vbldm-notes-2018.05.30.md",
    "content": "# Visual Basic Language Design Meeting\n\nMay 30, 2018\n\nWe have been largely on break because of travel, Build and other issues. \n\n## Agenda\n\n* Europe trip report, stability, possible survey\n* Issue labels (marking what we've reviewed)\n* Issue 305: In and Out operators\n* Issue 304: Select TypeOf\n* Issue 303: Null conditional operators for add/removeHandler\n* Issue 301: Modify how literal strings are parsed\n* Issue 167: Support for Return? construct\n\n## Europe trip report, stability, possible survey\n\nWe discussed stability, the current VB strategy and input I heard on my Europe trip. We believe the majority of Visual Basic customers (there are hundreds of thousands of quiet customers each month) primarily want VB to keep doing what it does now. It remains striking how few Visual Basic programmers we're able to hear from. We have a small group of important friends and a large number of silent users. We don't know what this larger group wants, they aren't asking us for features.\n\nWe will discuss with folks at Microsoft that know about such things the possibility of a survey to try to gather better information. There is no plan to change the strategy, although we'll continue to discuss how we communicate it effectively so that people know Microsoft remains committed to Visual Basic. The survey needs to go to VB programmers only (not a Twitter survey)\n\n## Issue labels\n\nKathleen will put together a document for review that clarifies how we communicate our review of issues. Initial thoughts: \n\n* \"LDM Reviewed: No plans\" as opposed to closing or rejected to avoid shutting down further discussion but communicating that we don't plan to move forward\n* \"LDM Thinking\"\n* Orthogonally, group issues that are related to larger areas, such as \"Pattern Matching\" and \"Flagged Enums\"\n\n## Issue #305 [In and Out operators](https://github.com/dotnet/vblang/issues/305)\n\nConsidered in three pieces: \n\n### In against a normal list (not types)\n\nThis does not seem to have much value - is not significantly more expressive even if shorter - than .Contains against the list. Not moving forward for this reason. \n\n### In against a list of types\n\nKathleen's alternative syntax is wrong. TypeOf...Is is not an exact match, but whether a cast can occur. This is a concern with this feature since there is already some confusion around how TypeOf...Is.\n\nThe correct syntax is a bit involved, but when would this be useful. You would branch, but would have to do additional casts. It seems much more likely that you'd do a series of If statements or similar.\n\nNot moving forward unless we see significant real world cases, and still have concerns. \n\n### Out\n\nThis is similar to Pattern Matching and Out variables in C#. Out variables are probably covered better in [#60](https://github.com/dotnet/vblang/issues/60) and pattern matching by [#124](https://github.com/dotnet/vblang/issues/124)\n\nLabels: Pattern Matching and LDM Reviewed: No Plans\n\n## Issue #304 [Select TypeOf](https://github.com/dotnet/vblang/issues/304)\n\nWill consider part of pattern matching. \n\nLabels: Pattern Matching and LDM Reviewed: No Plans\n\n## Issue #303 [Null conditional operators for add/removeHandler](https://github.com/dotnet/vblang/issues/303)\n\nAs suggested this would only work if special case lowering or similar occurs because the null is more or less on the assignment side. \n\nConsidered in relation to .NET 3 focus on WinForms/WPF. However, even in that context this would be quite rare (generally humans don't do the AddHandlers thing and generally all controls are instantiated.)\n\nReally seems like a side case.\n\nLabels: LDM Reviewed: No Plans\n\n## Issue #301 [Modify how literal strings are parsed.](https://github.com/dotnet/vblang/issues/301)\n\nTo summarize: Unicode is ugly. It's maybe a bit extra ugly in VB. \n\nWe considered `\\u3264`. VB has a bit of an advantage of C# here because it can avoid the `u`/`U` ugliness. We considered special casing in interpolated strings, but it seems more logical to just make it a literal if we did it. But it looks so not-VB!\n\nConsidered variations with trailing type character like `&H3264c`. That's only nominally better than `ChrW`. People are likely to use constants if they want clarity.\n\nLabels: LDM Thinking\n\n## Issue #167 [Proposal: Support for Return? construct](https://github.com/dotnet/vblang/issues/167)\n\nWe flipped over to #167 while looking at #303.\n\nWe think this is a bad idea. Control flow would be altered by a very subtle character. It's not the same meaning as other uses as ? (any alteration in control flow)\n\nLabels: LDM Reviewed: No Plans"
  },
  {
    "path": "meetings/2018/vbldm-notes-2018.06.13.md",
    "content": "# Visual Basic Language Design Meeting\n\nJune 13, 2018\n\nLast week's meeting subsumed with other issues.\n\n## Agenda\n\n* Review process\n* Issues reviewed\n\n## Review process\n\nWe'll review issues and use one of the following labels\n\n* **LDM In Process**: LDM review is in progress\n* **LDM Considering**: LDM reviewed and think this has merit\n* **LDM No Plans**: LDM reviewed and this feature is unlikely to move forward in the foreseeable future(*)\n* **LDM Rejected**: LDM reviewed and rejected\n\n(*) This is the description we decided after our first description didn't have as much transparency as we intended.\n\nWe will begin reviewing with issues that have been quiet for a couple of months. Our goals with this is not to disrupt active conversations.\n\nWe will put our logic in the issue itself, not in the meeting notes as we think it will be more accessible.\n\nA few notes on our overall thinking:\n\n* We will almost never make breaking changes to Visual Basic (often resulting in _Rejected_ label)\n  * There may be some extreme edge cases that we believe highly unlikely ever\n  * We may be forced, and we will do everything to avoid being forced\n  * We are just beginning planning for .NET Core 3 version of Visual Basic, but currently anticipate a very high bar for breaking changes.\n* We strongly believe that Visual Basic has a stance - a way of doing things. We will strive to maintain consistency with things being \"VB-like\" (often resulting in a No Plans or rejected label)\n* Our observation is that the vast majority of Visual Basic users are not asking for us for new features so our bar for expansion of the surface area - making a second way to do things - will be relatively high even when it's a good idea (often resulting in a _No Plans_ label)\n* Consistent with the [Visual Basic language strategy](https://blogs.msdn.microsoft.com/dotnet/2017/02/01/the-net-language-strategy/) C# will take the lead on some issues - particularly those that would involve changes to the CLR or .NET libraries. We'll note this and suggest discussion in [CSharpLang](https://github.com/dotnet/csharplang)\n\n# Reviewed\n\nLogic for the decisions are included in comments adjacent to the label change for these issues\n\n**No Plans**:\n* [#47](https://github.com/dotnet/vblang/issues/47)\n* [#256](https://github.com/dotnet/vblang/issues/256)\n* [#272](https://github.com/dotnet/vblang/issues/272)\n* [#244](https://github.com/dotnet/vblang/issues/244)\n* [#62](https://github.com/dotnet/vblang/issues/62)\n* [#229](https://github.com/dotnet/vblang/issues/229)\n\n**Rejected**:\n* [#288](https://github.com/dotnet/vblang/issues/288) \n\n"
  },
  {
    "path": "meetings/2018/vbldm-notes-2018.12.19.md",
    "content": "# Visual Basic Language Design Meeting\n\nDecember 19, 2018\n\nLast week's meeting subsumed with other issues.\n\n## Agenda\n\n* Pattern Matching discussion/proposal from community\n\nIt's been a while since we've had Language Design in our weekly meetings because folks on the LDM have been distracted with the VB runtime and have not been doing language work, since [it will be a while before we can implement new features](https://blogs.msdn.microsoft.com/vbteam/2018/11/12/visual-basic-in-net-core-3-0/). These realities and timeline haven't changed, but we had a fun meeting on pattern matching in relation to the [VBLang issue #337](https://github.com/dotnet/vblang/issues/337).\n\nIn general, we like to watch community issues - our involvement can be \"leading the witness\" and potentially miss exploring an avenue. In this case, the conversation had made significant progress and it was a good time to review, and it was requested.\n\nIt was really gratifying that we started with the initial issue and early comments, then had a very free-wheeling discussion on what it might look like, then found our conclusions were in very close alignment with [this summary of the community conversation to date](https://github.com/dotnet/vblang/issues/337#issuecomment-448427815). Fantastic job by the community at VBLang looking at the problems from many directions. \n\nWe all want to do pattern matching, it's the thing we are most excited about after C# interop issues. The time-frame we think is practical remains around VB.NET 16.2. And, while we are optimistic, like all such discussions, we are not making a commitment to doing this.\n\nFor background: a pattern is not an expression, but a thing that when matched results in an expression, in this context a Boolean expression.\n\n## Overall thoughts and criteria\n\n* No breaking changes.\n* Think ahead so the initial design doesn't box us away from things we might want later.\n* Where we need to make a decision, we will follow C# unless there is a compelling reason to avoid adding more subtle differences between the languages (many programmers work in C# and VB.NET).\n* Balancing the previous, we want pattern matching to be VB-like as possible - for example, C# restrictions regarding constant expressions may not be appropriate.\n* A phased release allows the community to understand concepts individually (this concept is not VB.NET specific, this was done in C#). The likely order (in separate, not necessarily sequential versions):\n  * Declaration pattern - type match with assignment equivalent and When clause\n  * Recursive patterns (including tuple patterns)\n  * Maybe _and_ and _or_ and _not_ patterns later (still uncertain on this)\n\n## Comments on summary posted Dec-18, 2018\n\nIt seems most appropriate to structure our thoughts in relation to [this comment's summary](https://github.com/dotnet/vblang/issues/337#issuecomment-448427815). \n\n#1. Both `Matches` and `Is` were discussed. We think `Is` will have ambiguity issues with the existing use for reference equality. We might be able to finesse the use of `Is` with operators, by expanding thinking about what a pattern is, but other scenarios are more problematic. `Matches` is the proposed keyword.\n\n```VB\nIf o Matches x As String\n   ' ...\nEnd If\n\nSelect Case o\n   Case x As String\n      ' ...\nEnd Select\n```\n\nNot all of us are happy with the reading of the `If` syntax. The human English wording would be more like \"If o matches string, put it in x as a string.\" While we didn't find an alternative in the meeting, we've since found [this suggestion by @AdamSpeight2008](https://github.com/dotnet/vblang/issues/119#issuecomment-313021036) which leads to considering the alternative:\n\n```VB\nIf o Matches String Into x\n   ' ...\nEnd If\n\nSelect Case o\n   Case String Into x\n      ' ...\nEnd Select\n```\n  \nThis will lead to a discussion about whether it is more important to read like English or to look like a declaration here.\n\nWe are not ready for a negation pattern, but think that would work better than a `DoesntMatch` keyword. \n\nWe agree that an additional keyword is not required in all `Case` cases, we haven't removed the possibility to remove ambiguity or to increase readibility.\n\n#2. We are a little confused. The effect of [#119](https://github.com/dotnet/vblang/issues/119#issue-239288726) seems desirable, but not sure whether this is a pattern or evaluation (or what distinctions matter here).\n\n#3. We thought about commas. If patterns are evaluated in certain scenarios, like method parameters, commas are a problem. For example, similar to a pattern in another thread was:\n\n```VB\nSelect Case o\n   Case 1 To 10, 47\n      ' stuff\nEnd Select\n```\n\nBut this syntax can't be used as a method argument, because it would be unclear whether 47 is a pattern or a second argument.\n\n```VB\nf(Matches 1 To 10, 47)\n```\n\nOur resolution was for the comma to remain a special feature of `Case`, not a part of the pattern syntax.\n\nThis also results in a natural answer for whether When should apply to each part of a multi-part Case match. This syntax might be expressed like (whether or not parens are ultimately legal syntax here):\n\n```VB\nSelect Case o\n   Case (x As String [When <expression>]), (y As Object [When <expression >])\n      ' ...\nEnd Select\n```\n\nCertainly everything that works in the context of a `Case` today should continue to work in a `Case`. But hesitate on moving syntax from `Case` to other places patterns can be used.\n\n#4. The linked \"full range of potential patterns\" is for F# and several of these are not available in other .NET languages. \n\nIt's not clear how variable introduction without typechecking would work, or how type checking without assignment differs from the available `TypeOf x  Is <type>`.\n\n#5. We like `When`. \n\n#6. Can we get clarity on this. Is this basically saying there can't be ambiguity and we can't break existing code? \n\n#7. Do you mean `Case` should not require `Is` where it does not require it today?\n\n8# i) We need some compelling cases for non-matches. The most compelling case for patterns is TypeCheck/assignment, and that doesn't seem to make sense for non-matches. \n\n#8 ii) If you mean exhaustiveness of cases in `Select Case`, we don't have this today and introducing it is backwards breaking. \n\n#8 iii) Need clarity on what this is saying\n\n#8 iv) Agree. We don't usually let variables be used before they are declared, so it would look quite weird to allow this in one case (`DoBottomLoopStatement`)\n\n## Current state of the grammar\n\nWe are very, very early in this process and this is open to a great deal of iteration, but the best current expression of the grammar is this, which is copied from [@zpitz summary of the community conversation here](https://github.com/dotnet/vblang/issues/337#issuecomment-448427815) with the changes noted:\n\n```\n// LDM: Throughout: \"PatternExpression\" has been replaced with \"Pattern\". \n// This probably needs a bit more work, because the implication is that \n// When is part of the pattern and some confusion in that part below. \n// The resolution needs to be clear that a pattern is not an expression. \n\nBooleanExpressionOrPattern\n    : BooleanExpression\n    | Expression 'Matches' Pattern\n    ;\n\n\n// If...Then..ElseIf blocks\n// LDM: The scope of introduced variables is the surrounding scope\n\nBlockIfStatement\n    : 'If' BooleanExpressionOrPattern 'Then'? StatementTerminator\n      Block?\n      ElseIfStatement*\n      ElseStatement?\n      'End' 'If' StatementTerminator\n    ;\n\nElseIfStatement\n    : ElseIf BooleanExpressionOrPattern 'Then'? StatementTerminator\n      Block?\n    ;\n\nLineIfThenStatement\n    : 'If' BooleanExpressionOrPattern 'Then' Statements ( 'Else' Statements )? StatementTerminator\n    ;\n\n\n// Loops\n// LDM thinks introduced variables scope to the While block\nWhileStatement\n    : 'While' BooleanExpressionOrPattern StatementTerminator\n      Block?\n      'End' 'While' StatementTerminator\n    ;\n\n// introducing variables with either While or Until could only be used \n// by the When clause, not within the block\n// LDM thinks probably within the block as well\nDoTopLoopStatement\n    : 'Do' ( WhileOrUntil BooleanExpressionOrPattern )? StatementTerminator\n      Block?\n      'Loop' StatementTerminator\n    ;\n\n// introducing variables with either While or Until could only be used \n// by the When clause, not within the block\nDoBottomLoopStatement\n    : 'Do' StatementTerminator\n      Block?\n      'Loop' WhileOrUntil BooleanExpressionOrPattern StatementTerminator\n    ;\n\nConditionalExpression\n    : 'If' OpenParenthesis BooleanExpressionOrPattern Comma Expression Comma Expression CloseParenthesis\n    | 'If' OpenParenthesis Expression Comma Expression CloseParenthesis\n    ;\n\n\n// Within a Case clause\n\nCaseStatement\n    : 'Case' Pattern StatementTerminator\n      Block?\n    ;\nWhat are the parts of a pattern expression?\n\nPattern\n    : Pattern ('When' BooleanExpression)?\n    ;\nWhat patterns should be supported from the start?\n\n\n// LDM reworded: \nMultiple Patterns\n    // multiple patterns are separately evaluated and each has it's own when clause\n    // multiple patterns are only supported in case\n    : Pattern ',' Pattern                    // OR pattern (already supported in Case)\n\nPatterns\n    // LDM wants to understand need for TypeCheck without assignemnt.\n    | 'As' TypeName                          // Type check pattern -- matches when subject is of TypeName\n    // LDM wants to understand usage without type\n    | 'Dim' Identifier ('As' TypeName)?      // Variable pattern -- introduces a new variable in child scope; as TypeName or Object\n    // LDM: Tentatively thinking of other Case syntax as a pattern may be useful, but these might remain specific to Case\n    | 'Is'? ComparisonOperator Expression    // Comparison pattern\n    | 'Like' StringExpression                // Like pattern\n    | Expression 'To' Expression             // Range pattern\n    | Expression                             // Expression pattern -- value/reference equality test against Expression\n    ;\n```\n\n## Other Notes\n\n* What does \"nested patterns\" mean? Maybe not V1\n* `If obj Is String Then Console.WriteLine(\"obj is a string\")` already available with `TypeOf..Is`\n* If we do _and_ and _or_ later, AndAlsoMatches/OrElseMatches is one option. Conjunctions are probably not in first or second version, C# thinking is these are much lower need/usage.\n* Probably add a discard identifier and a discard pattern\n"
  },
  {
    "path": "meetings/README.md",
    "content": "# Visual Basic .NET Language Design Meetings\n\nVisual Basic .NET Language Design Meetings (LDM for short) are meetings by the Visual Basic .NET Language Design Team and invited guests to investigate, design and ultimately decide on features to enter the Visual Basic .NET language. It is a creative meeting, where active design work happens, not just a decision body. \n\nEvery Visual Basic .NET language design meeting is represented by a meeting notes file in this folder.\n\n## Purpose of the meetings notes\n\nMeeting notes serve the triple purposes of\n\n- recording decisions so they can be acted upon\n- communicating our design thinking to the community so we can get feedback on them\n- recording rationale so we can return later and see why we did things the way we did\n\nAll have proven extremely useful over time.\n\n## Life cycle of meeting notes\n\n- If upcoming design meetings have a specific agenda, there may be a meeting notes file with that agenda even before the meeting happens\n- After the meeting notes will be saved directly here. \n- Usually they will be raw notes in need of subsequent cleaning up. If that's the case, they will be clearly marked as such, and a work item will track the task of cleaning up the notes.\n- When the notes are finalized, a notification is sent to the mailing list. Discussion can happen there.\n- If the notes impact current proposals, work items will track updating those proposals.\n- When updated, the proposals link back to the meeting where the proposal was discussed.\n\n## Style of design notes\n\nThe notes serve as the collective voice of the LDM. They cover not just the decisions but the discussion, options and rationale, so that others can follow along in the discussion and provide input to it, and so that we don't forget them for later.\n\nHowever, *the notes are not minutes*! They *never* state who said what in the meeting. They will occasionally mention people by name if they are visiting, provided input, should be collaborated with, etc. But the notes aim to represent the shared thinking of the room. If there's disagreement, they will report that, but they won't say who wants what.\n\nThis approach is intended to reinforce that the LDMs are a safe space, and a collaborative, creative effort. It is not a negotiation between representatives of different interests. It is not a voting body, and it is not a venue for posturing. Everybody cooperates towards the same end: creating the best language for today's and tomorrow's Visual Basic .NET developers.\n\n"
  },
  {
    "path": "meetings/notes-template.md",
    "content": "# Visual Basic Language Design Meeting\nMonth Day, Year\n\n## Agenda\n* [Proposal #Number - Title](#proposal-number---title)\n* [Scenario #Number - Title](#scenario-number---title)\n\n## Proposal [#Number](https://github.com/dotnet/vblang/issues/number) - Title\n_Related: [#Number](https://github.com/dotnet/vblang/issues/number) - Title_\n\n## Scenario [#Number](https://github.com/dotnet/vblang/issues/number) - Title\n_Related: [#Number](https://github.com/dotnet/vblang/issues/number) - Title_\n\n### Proposal [#Number](https://github.com/dotnet/vblang/issues/number) - Title\n_Related: [#Number](https://github.com/dotnet/vblang/issues/number) - Title_\n"
  },
  {
    "path": "proposals/README.md",
    "content": "# VB Language Proposals\n\nLanguage proposals are living documents describing the current thinking about a give language feature.\n\nProposals can be either *active*, *inactive*, *rejected* or *done*. *Active* proposals are stored directly in the proposals folder, *inactive* and *rejected* proposals are stored in the [inactive](proposals/inactive) and [rejected](proposals/rejected) subfolders, and *done* proposals are archived in a folder corresponding to the language version they are part of.\n\n## Lifetime of a proposal\n\nA proposal starts its life when the language design team decides that it might make a good addition to the language some day. Typically it will start out being *active*, but if we want to capture an idea without wanting to work on it right now, a proposal can also start out in the *inactive* subfolder. Proposals may even start out directly in the *rejected* state, if we want to make a record of something we don't intend to do. For instance, if a popular and recurring request is not possible to implement, we can capture that as a rejected proposal.\n\nThe proposal may start out as an idea on the mailing list, or it may come from discussions in the LDM, or arrive from many other fronts. The main thing is that the design team feels that it should be done, and that there's someone who is willing to write it up.\n\nA proposal is *active* if it is moving forward through design and implementation towards an upcoming release. Once it is completely *done*, i.e. an implementation has been merged into a release and the feature has been specified, it is moved into a subdirectory corresponding to its release.\n\nIf a feature turns out not to be likely to make it into the language at all, e.g. because it proves unfeasible, does not seem to add enough value or just isn't right for the language, it will be *rejected*, and moved to the corresponding subfolder. If a feature has reasonable promise but is not currently being prioritized to work on, it is *inactive* and will be moved to the corresponding subfolder. It is perfectly fine for work to happen on inactive or rejected proposals, and for them to be resurrected later. The categories are there to reflect current design intent.\n\n## Discussion of proposals\n\nFeedback and discussion happens on the VB design mailing list. When a new proposal is added, it should be announced on the mailing list.\n\n "
  },
  {
    "path": "proposals/inactive/README.md",
    "content": ""
  },
  {
    "path": "proposals/overload-resolution-priority.md",
    "content": "# Overload Resolution Priority\n\n## Summary\n[summary]: #summary\n\nWe introduced a new attribute, `System.Runtime.CompilerServices.OverloadResolutionPriority`, that can be used by API authors to adjust the relative priority of\noverloads within a single type as a means of steering API consumers to use specific APIs, even if those APIs would normally be considered ambiguous or otherwise\nnot be chosen by overload resolution rules. See [Overload Resolution Priority in C#](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-13.0/overload-resolution-priority.md).\n\n## Motivation\n[motivation]: #motivation\n\nAPI authors often run into an issue of what to do with a member after it has been obsoleted. For backwards compatibility purposes, many will keep the existing member around\nwith `ObsoleteAttribute` set to error in perpetuity, in order to avoid breaking consumers who upgrade binaries at runtime. This particularly hits plugin systems, where the\nauthor of a plugin does not control the environment in which the plugin runs. The creator of the environment may want to keep an older method present, but block access to it\nfor any newly developed code. However, `ObsoleteAttribute` by itself is not enough. The type or member is still visible in overload resolution, and may cause unwanted overload\nresolution failures when there is a perfectly good alternative, but that alternative is either ambiguous with the obsoleted member, or the presence of the obsoleted member causes\noverload resolution to end early without ever considering the good member. For this purpose, we want to have a way for API authors to guide overload resolution on resolving the\nambiguity, so that they can evolve their API surface areas and steer users towards performant APIs without having to compromise the user experience.\n\n## Detailed Design\n[detailed-design]: #detailed-design\n\n### Overload resolution priority\n\nWe define a new concept, ***overload_resolution_priority***, which is used during the process of overload resolution. ***overload_resolution_priority*** is a 32-bit integer\nvalue. All methods have an ***overload_resolution_priority*** of 0 by default, and this can be changed by applying\n[`OverloadResolutionPriorityAttribute`](#systemruntimecompilerservicesoverloadresolutionpriorityattribute) to a method. We update section \n[Overloaded Method Resolution](https://github.com/dotnet/vblang/blob/main/spec/overload-resolution.md#overloaded-method-resolution) of the VB specification as\nfollows (change in **bold**):\n\n> 2.  Next, eliminate all members from the set that are inaccessible or not applicable (Section [Applicability To Argument List](overload-resolution.md#applicability-to-argument-list)) to the argument list\n\n> **3. Then, the reduced set of candidate members is grouped by declaring type.\n>      If the member is an override, the declaring type and the ***overload_resolution_priority*** come from the least-derived declaration of that member.\n>      Within each group:**\n \n> - **A maximum ***overload_resolution_priority*** among candidates that do not utilize narrowing conversions or narrowing delegate relaxation is determined.**\n> - **All members that have a lower ***overload_resolution_priority*** than the maximum found during the previous step, if any, within its declaring type group are removed.**\n \n> **The reduced groups are then recombined into the set of candidates.**\n\n>  **4**.  Next, if one or more arguments are `AddressOf` or lambda expressions, then calculate the *delegate relaxation levels* for each such argument as below. If the worst (lowest) delegate relaxation level in `N` is worse than the lowest delegate relaxation level in `M`, then eliminate `N` from the set. The delegate relaxation levels are as follows:\n\nAs an example, this feature would cause the following code snippet to print \"I1\", rather than failing compilation due to an ambiguity:\n\n```vb\nPublic Interface I1\nEnd Interface\nPublic Interface I2\nEnd Interface\nPublic Interface I3\n    Inherits I1, I2\nEnd Interface\n\nPublic Class C\n    <OverloadResolutionPriority(1)>\n    Public Shared Sub M(x As I1)\n        System.Console.WriteLine(\"I1\")\n    End Sub\n    Public Shared Sub M(x As I2)\n        System.Console.WriteLine(\"I2\")\n    End Sub\nEnd Class\n\nPublic Class Program\n    Shared Sub Main()\n        Dim i3 As I3 = Nothing\n        C.M(i3)\n    End Sub\nEnd Class\n```\n\nNegative numbers are allowed to be used, and can be used to mark a specific overload as worse than all other default overloads.\n\nThe **overload_resolution_priority** of a member comes from the least-derived declaration of that member. **overload_resolution_priority** is not\ninherited or inferred from any interface members a type member may implement, and given a member `Mx` that implements an interface member `Mi`, no\nwarning is issued if `Mx` and `Mi` have different **overload_resolution_priorities**.\n\nThe candidates that utilize a narrowing conversion or a narrowing delegate relaxation are excluded from determining the maximum **overload_resolution_priority**\nbecause there is no guarantee that those candidates can be successfully invoked with the supplied arguments.\nFor example, consider the following scenario:\n``` vb\nModule Module1\n\n    Sub Main()\n        M1(New C0())\n    End Sub\n\n    <System.Runtime.CompilerServices.OverloadResolutionPriority(1)>\n    Sub M1(x As C1)\n    End Sub\n\n    Sub M1(x As C2)\n        System.Console.Write(2)\n    End Sub\nEnd Module\n\nClass C0\n    Public Shared Narrowing Operator CType(x As C0) As C1\n        Throw New System.InvalidCastException()\n    End Operator\n    Public Shared Widening Operator CType(x As C0) As C2\n        Return New C2()\n    End Operator\nEnd Class\n\nClass C1\nEnd Class\n\nClass C2\nEnd Class\n```\n\nWhen it is compiled with `Option Strict On`, `Sub M1(x As C1)` is not applicable because it cannot be called without a\nnarrowing conversion. The only applicable candidate is `M1(x As C2)` and it is called.\n\nWhen the code is compiled with `Option Strict Off`, both methods are applicable. If the priority was given to `Sub M1(x As C1)`,\na candidate that uses only widening conversions would be filtered out, resulting in an `InvalidCastException` thrown during execution.\n\nHere is another example:\n``` vb\nOption Strict Off\n\nModule Module1\n\n    Sub Main()\n        M1(CObj(New C2()))\n    End Sub\n\n    <System.Runtime.CompilerServices.OverloadResolutionPriority(1)>\n    Sub M1(x As I1)\n        System.Console.Write(1)\n    End Sub\n\n    Sub M1(x As I2)\n        System.Console.Write(2)\n    End Sub\nEnd Module\n\nInterface I1\nEnd Interface\n\nInterface I2\nEnd Interface\n\nClass C2\n    Implements I2\nEnd Class\n```\n\nIn this case both candidates require narrowing conversion. Since filtering doesn't happen, the result of overload resolution\nis a late-bound invocation, which determines that `Sub M1(x As I1)` is inapplicable and invokes `Sub M1(x As I2)`.\n\nIf the priority was given to `Sub M1(x As I1)` at compile time, it would remain the only applicable candidate and would be\ninvoked early-bound, resulting in an `InvalidCastException` thrown during execution.\n\n### `System.Runtime.CompilerServices.OverloadResolutionPriorityAttribute`\n\nThere is the following attribute in the BCL:\n\n```cs\nnamespace System.Runtime.CompilerServices;\n\n[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]\npublic sealed class OverloadResolutionPriorityAttribute(int priority) : Attribute\n{\n    public int Priority => priority;\n}\n```\n\nAll methods and properties in VB have a default ***overload_resolution_priority*** of 0, unless they are attributed with `OverloadResolutionPriorityAttribute`.\nIf they are attributed with that attribute, then their ***overload_resolution_priority*** is the integer value provided to the first argument of the attribute.\n\nBy analogy with C#, it is an error to apply `OverloadResolutionPriorityAttribute` to the following locations:\n\n* Property, or event accessors\n* Conversion operators\n* Finalizers\n* Shared constructors\n* Overriding properties\n* Overriding methods \n\nAttributes encountered on these locations in metadata effectively will have no impact in VB code.\n\n### Langversion Behavior\n\nOverload Resolution process does not perform filtering by ***overload_resolution_priority*** in VB < 17.13.\nNo errors or warnings issued by the Overload Resolution process due to the fact that ***overload_resolution_priority***\nwas ignored in this case.\n\nBy analogy with C#, a langversion error is issued when `OverloadResolutionPriorityAttribute` is applied in VB < 17.13.\n"
  },
  {
    "path": "proposals/proposal-DerestrictedOperators.md",
    "content": "# Derestricted Operators\n\n* [x] Proposed: [Complete](https://github.com/dotnet/vblang/issues/26)\n* [ ] Prototype: [Complete](https://github.com/PROTOTYPE_OWNER/roslyn/BRANCH_NAME)\n* [ ] Implementation: [In Progress](https://github.com/dotnet/roslyn/BRANCH_NAME)\n* [ ] Specification: [Not Started](pr/1)\n\n## Summary\n[summary]: #summary\n\nRemove some of the restriction placed on operators.\n\n## Motivation\n[motivation]: #motivation\n\nUnder the current rules of the VB.net language, some operators require to be implementation in complement pairs.\n\n[]\n\n| Op  | Comp |\n|----|----|\n|  <   |  =>  |\n|  <=  |  >   |\n|  >   |  <=  |\n|  >=  |  <   |\n|  <>  |  =   |\n|  =   |  <>  |\n| IsTrue | IsFalse |\n| IsFalse | IsTrue |\n\n```vb\nPublic Shared Operator <( x As Foo, y As Foo) As Boolean\n\nEnd Sub\n\nPublic Shared Operator >=( x As Foo, y As Foo) As Boolean\n\nEnd Sub\n```\n\nOr in proof of concept, commenting out the production of the error.\n```\n    diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_MatchingOperatorExpected2,\n      SyntaxFacts.GetText(OverloadResolution.GetOperatorTokenKind(nameOfThePair)),\n      method), method.Locations(0))\n```\n\n\n---------------\n## Detailed design\n[design]: #detailed-design\n\n\nThis proposal is to remove that restriction, by skip the following section of under a language feature conditional.\n[Source](https://github.com/dotnet/roslyn/blob/508c229005f4f6c556a54a78905971b1bc3bb9c7/src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMemberContainerTypeSymbol.vb#L3630)\n\n\n\nThis is the bulk of the proposal. Explain the design in enough detail for somebody familiar\nwith the language to understand, and for somebody familiar with the compiler to implement,  and include examples of how the feature is used. This section can start out light before the prototyping phase but should get into specifics and corner-cases as the feature is iteratively designed and implemented.\n\nExample code:\n\n```vbnet\nModule Module1\n\n    Sub Main()\n        Dim lower_limit = 0\n        Dim upper_limit = 100\n        Dim value_A = 50\n        Dim value_B = -10\n        Dim value_C = 180\n        Dim res_A = lower_limit.__ < value_A <= upper_limit\n        Dim res_B = lower_limit.__ < value_B <= upper_limit\n        Dim res_C = lower_limit.__ < value_C <= upper_limit\n\n    End Sub\n\nEnd Module\n\nPublic Class CMPOP_A(Of T As IComparable(Of T))\n\n    Private _Value As T\n\n    Sub New(value As T)\n        _Value = value\n    End Sub\n\n    ' First part of Range Check is done here. Also note we have to remember what the middle value is over to the next part.\n    Public Shared Operator <(x As CMPOP_A(Of T), y As T) As CMPOP_B(Of T)   ' <-- Not a Boolean\n        Return New CMPOP_B(Of T)(y, x._Value.CompareTo(y) < 0)\n    End Operator\n\n    Public Shared Operator <=(x As CMPOP_A(Of T), y As T) As CMPOP_B(Of T)   ' <-- Not a Boolean\n        Return New CMPOP_B(Of T)(y, x._Value.CompareTo(y) <= 0)\n    End Operator\n\nEnd Class\n\nPublic Class CMPOP_B(Of T As IComparable(Of T))\n\n    Private _Value As T\n    Private _State As Boolean\n\n    Sub New(Value As T, state As Boolean)\n        _Value = Value\n        _State = state\n    End Sub\n\n    ' If the State is False already it skips the comparison and returns False.\n    Public Shared Operator <(x As CMPOP_B(Of T), y As T) As Boolean\n        Return x._State AndAlso (x._Value.CompareTo(y) < 0)\n    End Operator\n\n    Public Shared Operator <=(x As CMPOP_B(Of T), y As T) As Boolean\n        Return x._State AndAlso (x._Value.CompareTo(y) <= 0)\n    End Operator\n\nEnd Class\n\nPublic Module Exts\n    <Runtime.CompilerServices.Extension>\n    Public Function __(Of T As IComparable(Of T))(value As T) As CMPOP_A(Of T)\n        Return New CMPOP_A(Of T)(value)\n    End Function\nEnd Module\n\n\n```\n\nWhen trying to use a now non-existent operator.\n\neg\n```vb\nDim res_A = lower_limit.__ > value_A <= upper_limit\n```\n\n`Error\tBC30452\tOperator '>' is not defined for types 'CMPOP_A(Of Integer)' and 'Integer'.`\n\n\n\n\n\n\n## Drawbacks\n[drawbacks]: #drawbacks\n\nWhy should we *not* do this?\n\n## Alternatives\n[alternatives]: #alternatives\n\nChange the error, to a warning.\n\n## Unresolved questions\n[unresolved]: #unresolved-questions\n\nWhat parts of the design are still TBD?"
  },
  {
    "path": "proposals/proposal-Implicit-default-optional-parameters.md",
    "content": "# Implicit Default Optional Parameters\n\n* [x] Proposed\n* [x] Prototype: [Complete](https://github.com/AdamSpeight2008/roslyn-AdamSpeight2008/tree/master_Feature_ImplicitDefaultOptionalParameter)\n* [x] Implementation: [In Progress](https://github.com/AdamSpeight2008/roslyn-AdamSpeight2008/tree/PostDev15_Feature_ImplicitDefaultOptionalParameters)\n* [ ] Unit Tests\n* [x] Code Diagnostic Tool. \n* [ ] Specification: [Not Started](pr/1)\n\n## Summary\n[summary]: #summary\nAssume an implicit default value for optional parameter.\n\n## Motivation\n[motivation]: #motivation\n\nSimplifies the type of the more common usage case, that of using the default value of the associated type as the default to value of the parameter.\nEg `Foo(Optional size As String = Nothing)` to `Foo(Optional size As String)`\n\n## Detailed design\n[design]: #detailed-design\n\nThe grammar definition for an `Optional Parameter` is something similar to this.\n\n```\nOptionalParameter ::= \"Optional\" ParameterName Typing? DefaultToValue?\n           Typing ::= \"As\" TypeIdentifier\n   DefaultToValue ::= \"=\" ( \"Nothing\" | ConstantValue )\n```\n\n**Examples**    \nThe following forms will be support by this proposal, which in essence the type of the optional parameter must be specified. \n```vb.net\nFoo( Optional arg1 As String )           ' --> Foo( Optional arg1 As String = Nothing )\nFoo( Optional arg2 As String = Nothing ) ' --> Foo( Optional arg2 As String = Nothing )\nFoo( Optional arg4 As Integer )          ' --> Foo( Optional arg4 As Integer = Nothing )\nFoo( Optional arg5 As Integer = 0 )      ' --> Foo( Optional arg5 As Integer = 0 )\nFoo( Optional arg6 As Integer = 1 )      ' --> Foo( Optional arg6 As Integer = 1 )\n```\nOptional Parameters that don't specify a will function as existing (where the type is defined to object).    \nAs not to introduce a breaking change. *(As pointed out by @AnthonyDGreen)*\n```vb.net\nFoo( Optional arg0 )                     ' --> Foo( Optional arg0 As Object = Nothing )\nFoo( Optional arg3 = \"\" )                ' --> Foo( Optional arg3 As String = \"\" )\nFoo( Optional arg7 = 7 )                 ' --> Foo( Optional arg7 As Integer = 7 )\n```\n\n\n## Potential Usage\n[potential]: #potential\nUsing the following code authored by @AnthonyDGreen\n```VB.NET\nImports System.Console\nImports System.IO\n\nModule Program\n\n    Sub Main()\n        Dim log = New StringWriter()\n\n        Dim nothingDefaultCount = 0,\n            nonNothingDefaultCount = 0\n\n        For Each filename In Directory.EnumerateFiles(\"<roslyn-repo-path>\", \"*.vb\", SearchOption.AllDirectories)\n            Dim tree = VisualBasicSyntaxTree.ParseText(File.ReadAllText(filename))\n\n            Dim root = tree.GetRoot()\n\n            For Each decl In root.DescendantNodes.OfType(Of ParameterSyntax)\n                If decl.Default Is Nothing Then Continue For\n\n                If decl.Default.Value.IsKind(SyntaxKind.NothingLiteralExpression) OrElse\n                   decl.Default.Value.IsKind(SyntaxKind.FalseLiteralExpression) OrElse\n                   decl.Default.Value.ToString() = \"0\" _\n                Then\n                    nothingDefaultCount += 1\n                Else\n                    nonNothingDefaultCount += 1\n\n                    Dim text = decl.ToString()\n                    WriteLine(text)\n                    log.WriteLine(text)\n                End If\n            Next\n        Next\n\n        WriteLine(nothingDefaultCount)\n        WriteLine(nonNothingDefaultCount)\n\n        My.Computer.Clipboard.SetText(log.ToString())\n    End Sub\nEnd Module\n```\nRunning it on my roslyn repo clone it reports that of all the optional parameter declarations in VB in Roslyn 2229 out of 2612 of them, or > 85% use the default value of the parameter type as the default value of the parameter. So your suggestion would clean up 85% of the uses of Optional in Roslyn. Sounds like value to me!\n\n## Invariants\n[invariants]: #invariants\n\nThe following invariants must be preserved to maintain compatibility with legacy / preexisting code.\n\n`CallerInfoAttributes`\n\n**Legacy**\n```VB.net\nImports System.Runtime.CompilerServices\nModule Module1\n\n    Sub Main()\n        Dim r = Foo()\n        Console.WriteLine(r)\n    End Sub\n\n    Function Foo(<CallerLineNumber> Optional x As Integer = 0) As Integer\n        Console.WriteLine(x)\n        Return x\n    End Function\n\nEnd Module\n```\n**With Feature**\n```vb.net\nImports System.Runtime.CompilerServices\nModule Module1\n\n    Sub Main()\n        Dim r = Foo()\n        Console.WriteLine(r)\n    End Sub\n\n    Function Foo(<CallerLineNumber> Optional x As Integer) As Integer\n        Console.WriteLine(x)\n        Return x\n    End Function\n\nEnd Module\n```\n**Output**\n```\nR=5\nX=5\n```\n\n\n\n\n## Drawbacks\n[drawbacks]: #drawbacks\n\nWhy should we *not* do this?\n\n## Alternatives\n[alternatives]: #alternatives\n\nWhat other designs have been considered? What is the impact of not doing this?\n\n## Unresolved questions\n[unresolved]: #unresolved-questions\n\nWhat parts of the design are still TBD?\n"
  },
  {
    "path": "proposals/proposal-template.md",
    "content": "# FEATURE_NAME\n\n* [x] Proposed\n* [ ] Prototype: [Complete](https://github.com/PROTOTYPE_OWNER/roslyn/BRANCH_NAME)\n* [ ] Implementation: [In Progress](https://github.com/dotnet/roslyn/BRANCH_NAME)\n* [ ] Specification: [Not Started](pr/1)\n\n## Summary\n[summary]: #summary\n\nOne para explanation of the feature.\n\n## Motivation\n[motivation]: #motivation\n\nWhy are we doing this? What use cases does it support? What is the expected outcome?\n\n## Detailed design\n[design]: #detailed-design\n\nThis is the bulk of the proposal. Explain the design in enough detail for somebody familiar\nwith the language to understand, and for somebody familiar with the compiler to implement,  and include examples of how the feature is used. This section can start out light before the prototyping phase but should get into specifics and corner-cases as the feature is iteratively designed and implemented.\n\nExample code:\n\n```VB.NET\n' Creates an IEnumerable object that goes from 1 to 10.\nDim range = 1 To 10\n```\n\n## Drawbacks\n[drawbacks]: #drawbacks\n\nWhy should we *not* do this?\n\n## Alternatives\n[alternatives]: #alternatives\n\nWhat other designs have been considered? What is the impact of not doing this?\n\n## Unresolved questions\n[unresolved]: #unresolved-questions\n\nWhat parts of the design are still TBD?"
  },
  {
    "path": "proposals/rejected/README.md",
    "content": ""
  },
  {
    "path": "spec/README.md",
    "content": "Visual Basic Language Specification\n=====================================\n__Version 11__\n\n(This document is also available for download: [vb.pdf](http://ljw1004.github.io/vbspec/Visual%20Basic%20Language%20Specification.pdf?raw=true) and [vb.docx](http://ljw1004.github.io/vbspec/Visual%20Basic%20Language%20Specification.docx?raw=true))\n\n* [Introduction](introduction.md#introduction)\n    * [Grammar Notation](introduction.md#grammar-notation)\n    * [Compatibility](introduction.md#compatibility)\n* [Lexical Grammar](lexical-grammar.md#lexical-grammar)\n    * [Characters and Lines](lexical-grammar.md#characters-and-lines)\n    * [Identifiers](lexical-grammar.md#identifiers)\n    * [Keywords](lexical-grammar.md#keywords)\n    * [Literals](lexical-grammar.md#literals)\n    * [Separators](lexical-grammar.md#separators)\n    * [Operator Characters](lexical-grammar.md#operator-characters)\n* [Preprocessing Directives](preprocessing-directives.md#preprocessing-directives)\n    * [Conditional Compilation](preprocessing-directives.md#conditional-compilation)\n    * [External Source Directives](preprocessing-directives.md#external-source-directives)\n    * [Region Directives](preprocessing-directives.md#region-directives)\n    * [External Checksum Directives](preprocessing-directives.md#external-checksum-directives)\n* [General Concepts](general-concepts.md#general-concepts)\n    * [Declarations](general-concepts.md#declarations)\n    * [Scope](general-concepts.md#scope)\n    * [Inheritance](general-concepts.md#inheritance)\n    * [Implementation](general-concepts.md#implementation)\n    * [Polymorphism](general-concepts.md#polymorphism)\n    * [Accessibility](general-concepts.md#accessibility)\n    * [Type and Namespace Names](general-concepts.md#type-and-namespace-names)\n    * [Variables](general-concepts.md#variables)\n    * [Generic Types and Methods](general-concepts.md#generic-types-and-methods)\n* [Attributes](attributes.md#attributes)\n    * [Attribute Classes](attributes.md#attribute-classes)\n    * [Attribute Blocks](attributes.md#attribute-blocks)\n* [Source Files and Namespaces](source-files-and-namespaces.md#source-files-and-namespaces)\n    * [Program Startup and Termination](source-files-and-namespaces.md#program-startup-and-termination)\n    * [Compilation Options](source-files-and-namespaces.md#compilation-options)\n    * [Imports Statement](source-files-and-namespaces.md#imports-statement)\n    * [Namespaces](source-files-and-namespaces.md#namespaces)\n* [Types](types.md#types)\n    * [Value Types and Reference Types](types.md#value-types-and-reference-types)\n    * [Interface Implementation](types.md#interface-implementation)\n    * [Primitive Types](types.md#primitive-types)\n    * [Enumerations](types.md#enumerations)\n    * [Classes](types.md#classes)\n    * [Structures](types.md#structures)\n    * [Standard Modules](types.md#standard-modules)\n    * [Interfaces](types.md#interfaces)\n    * [Arrays](types.md#arrays)\n    * [Delegates](types.md#delegates)\n    * [Partial types](types.md#partial-types)\n    * [Constructed Types](types.md#constructed-types)\n    * [Special Types](types.md#special-types)\n* [Conversions](conversions.md#conversions)\n    * [Implicit and Explicit Conversions](conversions.md#implicit-and-explicit-conversions)\n    * [Boolean Conversions](conversions.md#boolean-conversions)\n    * [Numeric Conversions](conversions.md#numeric-conversions)\n    * [Reference Conversions](conversions.md#reference-conversions)\n    * [Array Conversions](conversions.md#array-conversions)\n    * [Value Type Conversions](conversions.md#value-type-conversions)\n    * [String Conversions](conversions.md#string-conversions)\n    * [Widening Conversions](conversions.md#widening-conversions)\n    * [Narrowing Conversions](conversions.md#narrowing-conversions)\n    * [Type Parameter Conversions](conversions.md#type-parameter-conversions)\n    * [User-Defined Conversions](conversions.md#user-defined-conversions)\n    * [Native Conversions](conversions.md#native-conversions)\n    * [Dominant Type](conversions.md#dominant-type)\n* [Type Members](type-members.md#type-members)\n    * [Interface Method Implementation](type-members.md#interface-method-implementation)\n    * [Methods](type-members.md#methods)\n    * [Constructors](type-members.md#constructors)\n    * [Events](type-members.md#events)\n    * [Constants](type-members.md#constants)\n    * [Instance and Shared Variables](type-members.md#instance-and-shared-variables)\n    * [Properties](type-members.md#properties)\n    * [Operators](type-members.md#operators)\n* [Statements](statements.md#statements)\n    * [Control Flow](statements.md#control-flow)\n    * [Local Declaration Statements](statements.md#local-declaration-statements)\n    * [With Statement](statements.md#with-statement)\n    * [SyncLock Statement](statements.md#synclock-statement)\n    * [Event Statements](statements.md#event-statements)\n    * [Assignment Statements](statements.md#assignment-statements)\n    * [Invocation Statements](statements.md#invocation-statements)\n    * [Conditional Statements](statements.md#conditional-statements)\n    * [Loop Statements](statements.md#loop-statements)\n    * [Exception-Handling Statements](statements.md#exception-handling-statements)\n    * [Branch Statements](statements.md#branch-statements)\n    * [Array-Handling Statements](statements.md#array-handling-statements)\n    * [Using statement](statements.md#using-statement)\n    * [Await Statement](statements.md#await-statement)\n    * [Yield Statement](statements.md#yield-statement)\n* [Expressions](expressions.md#expressions)\n    * [Expression Classifications](expressions.md#expression-classifications)\n    * [Constant Expressions](expressions.md#constant-expressions)\n    * [Late-Bound Expressions](expressions.md#late-bound-expressions)\n    * [Simple Expressions](expressions.md#simple-expressions)\n    * [Type Expressions](expressions.md#type-expressions)\n    * [Member Access Expressions](expressions.md#member-access-expressions)\n    * [Dictionary Member Access Expressions](expressions.md#dictionary-member-access-expressions)\n    * [Invocation Expressions](expressions.md#invocation-expressions)\n    * [Overload Resolution](overload-resolution.md)\n      * [Specificity of members/types given an argument list](overload-resolution.md#specificity-of-memberstypes-given-an-argument-list)\n      * [Genericity](overload-resolution.md#genericity)\n      * [Applicability to Argument List](overload-resolution.md#applicability-to-argument-list)\n      * [Passing Arguments, and Picking Arguments for Optional Parameters](overload-resolution.md#passing-arguments-and-picking-arguments-for-optional-parameters)\n      * [Conditional Methods](overload-resolution.md#conditional-methods)\n      * [Type Argument Inference](overload-resolution.md#type-argument-inference)\n    * [Index Expressions](expressions.md#index-expressions)\n    * [New Expressions](expressions.md#new-expressions)\n    * [Cast Expressions](expressions.md#cast-expressions)\n    * [Operator Expressions](expressions.md#operator-expressions)\n    * [Arithmetic Operators](expressions.md#arithmetic-operators)\n    * [Relational Operators](expressions.md#relational-operators)\n    * [Like Operator](expressions.md#like-operator)\n    * [Concatenation Operator](expressions.md#concatenation-operator)\n    * [Logical Operators](expressions.md#logical-operators)\n    * [Shift Operators](expressions.md#shift-operators)\n    * [Boolean Expressions](expressions.md#boolean-expressions)\n    * [Lambda Expressions](expressions.md#lambda-expressions)\n    * [Query Expressions](expressions.md#query-expressions)\n    * [Conditional Expressions](expressions.md#conditional-expressions)\n    * [XML Literal Expressions](expressions.md#xml-literal-expressions)\n    * [XML Member Access Expressions](expressions.md#xml-member-access-expressions)\n    * [Await Operator](expressions.md#await-operator)\n* [Documentation Comments](documentation-comments.md#documentation-comments)\n    * [Documentation Comment Format](documentation-comments.md#documentation-comment-format)\n    * [Recommended tags](documentation-comments.md#recommended-tags)\n    * [ID Strings](documentation-comments.md#id-strings)\n    * [Documentation comments example](documentation-comments.md#documentation-comments-example)\n* Grammar: [vb.html](http://ljw1004.github.io/vbspec/vb.html). Or download in ANTLR format: [vb.g4](http://ljw1004.github.io/vbspec/vb.g4?raw=true).\n\n\n*Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0.  See [License.txt](https://github.com/dotnet/roslyn/blob/master/License.txt) for license information.*\n \n"
  },
  {
    "path": "spec/attributes.md",
    "content": "# Attributes in Visual Basic\n\nThe Visual Basic language enables the programmer to specify modifiers on declarations, which represent information about the entities being declared. For example, affixing a class method with the modifiers `Public`, `Protected`, `Friend`, `Protected Friend`, or `Private` specifies its accessibility.\n\nIn addition to the modifiers defined by the language, Visual Basic also enables programmers to create new modifiers, called *attributes*, and to use them when declaring new entities. These new modifiers, which are defined through the declaration of attribute classes, are then assigned to entities through *attribute blocks*.\n\n__Note.__ Attributes may be retrieved at run time through the .NET Framework's reflection APIs. These APIs are outside the scope of this specification.\n\nFor instance, a framework might define a `Help` attribute that can be placed on program elements such as classes and methods to provide a mapping from program elements to documentation, as the following example demonstrates:\n\n```vb\n<AttributeUsage(AttributeTargets.All)> _\nPublic Class HelpAttribute\n    Inherits Attribute\n\n    Public Sub New(urlValue As String)\n        Me.UrlValue = urlValue\n    End Sub\n\n    Public Topic As String\n    Private UrlValue As String\n\n    Public ReadOnly Property Url() As String\n        Get\n            Return UrlValue\n        End Get\n    End Property\nEnd Class\n```\n\nThe example defines an attribute class named `HelpAttribute`, or `Help` for short, that has one positional parameter (`UrlValue`) and one named argument (`Topic`).\n\nThe next example shows several uses of the attribute:\n\n```vb\n<Help(\"http://www.example.com/.../Class1.htm\")> _\nPublic Class Class1\n    <Help(\"http://www.example.com/.../Class1.htm\", Topic:=\"F\")> _\n    Public Sub F()\n    End Sub\nEnd Class\n```\n\nThe next example checks to see if `Class1` has a `Help` attribute, and writes out the associated `Topic` and `Url` values if the attribute is present.\n\n```vb\nModule Test\n    Sub Main()\n        Dim type As Type = GetType(Class1)\n        Dim arr() As Object = _\n            type.GetCustomAttributes(GetType(HelpAttribute), True)\n\n        If arr.Length = 0 Then\n            Console.WriteLine(\"Class1 has no Help attribute.\")\n        Else\n            Dim ha As HelpAttribute = CType(arr(0), HelpAttribute)\n            Console.WriteLine(\"Url = \" & ha.Url & \", Topic = \" & ha.Topic)\n        End If\n    End Sub\nEnd Module\n```\n\n## Attribute Classes\n\nAn *attribute class* is a non-generic class that derives from `System.Attribute` and is not `MustInherit`. The attribute class may have a `System.AttributeUsage` attribute that declares what the attribute is valid on, whether it may be used multiple times in a declaration, and whether it is inherited. The following example defines an attribute class named `SimpleAttribute` that can be placed on class declarations and interface declarations:\n\n```vb\n<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Interface)> _\nPublic Class SimpleAttribute\n    Inherits System.Attribute\nEnd Class\n```\n\nThe next example shows a few uses of the `Simple` attribute. Although the attribute class is named `SimpleAttribute`, uses of this attribute may omit the `Attribute` suffix, thus shortening the name to `Simple`:\n\n```vb\n<Simple> Class Class1\nEnd Class\n\n<Simple> Interface Interface1\nEnd Interface\n```\n\nIf the attribute lacks a `System.AttributeUsage`, then the attribute can be placed on any target (equivalent to `AttributeTargets.All`). The `System.AttributeUsage` attribute has a variable initializer, `AllowMultiple`, which specifies whether the indicated attribute can be specified more than once for a given declaration. If `AllowMultiple` for an attribute is `True`, it is a *multiple-use attribute class*, and can be specified more than once on a declaration. If `AllowMultiple` for an attribute is `False` or unspecified for an attribute, it is a *single-use attribute class*, and can be specified at most once on a declaration.\n\nThe following example defines a multiple-use attribute class named `AuthorAttribute`:\n\n```vb\n<AttributeUsage(AttributeTargets.Class, AllowMultiple:=True)> _\nPublic Class AuthorAttribute\n    Inherits System.Attribute\n\n    Private _Value As String\n\n    Public Sub New(value As String)\n        Me._Value = value\n    End Sub\n\n    Public ReadOnly Property Value() As String\n        Get\n            Return _Value\n        End Get\n    End Property\nEnd Class\n```\n\nThe example shows a class declaration with two uses of the `Author` attribute:\n\n```vb\n<Author(\"Maria Hammond\"), Author(\"Ramesh Meyyappan\")> _\nClass Class1\nEnd Class\n```\n\nThe `System.AttributeUsage` attribute has a public instance variable, `Inherited`, that specifies whether the attribute, when specified on a base type, is also inherited by types that derive from this base type. If the `Inherited` public instance variable is not initialized, a default value of `False` is used. Properties and events do not inherit attributes, although the methods defined by properties and events do. Interfaces do not inherit attributes.\n\nIf a single-use attribute is both inherited and specified on a derived type, the attribute specified on the derived type overrides the inherited attribute. If a multiple-use attribute is both inherited and specified on a derived type, both attributes are specified on the derived type. For example:\n\n```vb\n<AttributeUsage(AttributeTargets.Class, AllowMultiple:=True, _\n                Inherited:=True) > _\nClass MultiUseAttribute\n    Inherits System.Attribute\n\n    Public Sub New(value As Boolean)\n    End Sub\nEnd Class\n\n<AttributeUsage(AttributeTargets.Class, Inherited:=True)> _\nClass SingleUseAttribute\n    Inherits Attribute\n\n    Public Sub New(value As Boolean)\n    End Sub\nEnd Class\n\n<SingleUse(True), MultiUse(True)> Class Base\nEnd Class\n\n' Derived has three attributes defined on it: SingleUse(False),\n' MultiUse(True) and MultiUse(False)\n<SingleUse(False), MultiUse(False)> _\nClass Derived\n    Inherits Base\nEnd Class\n```\n\nThe positional parameters of the attribute are defined by the parameters of the public constructors of the attribute class. Positional parameters must be `ByVal` and may not specify `ByRef`. Public instance variables and properties are defined by public read-write properties or instance variables of the attribute class. The types that can be used in positional parameters and public instance variables and properties are restricted to attribute types. A type is an attribute type if it is one of the following:\n\n* Any primitive type except for `Date` and `Decimal`.\n\n* The type `Object`.\n\n* The type `System.Type`.\n\n* An enumerated type, provided that it and the types in which it is nested (if any) have `Public` accessibility.\n\n* A one-dimensional array of one of the previous types in this list.\n\n## Attribute Blocks\n\nAttributes are specified in *attribute blocks*. Each attribute block is delimited by angle brackets (\"<>\"), and multiple attributes can be specified in a comma-separated list within an attribute block or in multiple attribute blocks. The order in which attributes are specified is not significant. For example, the attribute blocks `<A, B>`, `<B, A>`, `<A> <B>` and `<B> <A>` are all equivalent.\n\n```antlr\nAttributes\n    : AttributeBlock+\n    ;\n\nAttributeBlock\n    : LineTerminator? '<' AttributeList LineTerminator? '>' LineTerminator?\n    ;\n\nAttributeList\n    : Attribute ( Comma Attribute )*\n    ;\n\nAttribute\n    : ( AttributeModifier ':' )? SimpleTypeName\n    ( OpenParenthesis AttributeArguments? CloseParenthesis )?\n    ;\n\nAttributeModifier\n    : 'Assembly' | 'Module'\n    ;\n```\n\nAn attribute may not be specified on a kind of declaration it does not support, and single-use attributes may not be specified more than once in an attribute block. The example below causes errors both because it attempts to use `HelpString` on the interface `Interface1` and more than once on the declaration of `Class1`.\n\n```vb\n<AttributeUsage(AttributeTargets.Class)> _\nPublic Class HelpStringAttribute\n    Inherits System.Attribute\n\n    Private InternalValue As String\n\n    Public Sub New(value As String)\n        Me.InternalValue = value\n    End Sub\n\n    Public ReadOnly Property Value() As String\n        Get\n            Return InternalValue\n        End Get\n    End Property\nEnd Class\n\n' Error: HelpString only applies to classes.\n<HelpString(\"Description of Interface1\")> _\nInterface Interface1\n    Sub Sub1()\nEnd Interface\n\n' Error: HelpString is single-use.\n<HelpString(\"Description of Class1\"), _\n    HelpString(\"Another description of Class1\")> _\nPublic Class Class1\nEnd Class\n```\n\nAn attribute consists of an optional attribute modifier, an attribute name, an optional list of positional arguments, and variable/property initializers. If there are no parameters or initializers, the parentheses may be omitted. If an attribute has a modifier, it must be in an attribute block at the top of a source file.\n\nIf a source file contains an attribute block at the top of the file that specifies attributes for the assembly or module that will contain the source file, each attribute in the attribute block must be prefixed by both the `Assembly` or `Module` modifier and a colon.\n\n\n### Attribute Names\n\nThe name of an attribute specifies an attribute class. By convention, attribute classes are named with the suffix `Attribute`. Uses of an attribute may either include or omit this suffix. Consequently the name of an attribute class that corresponds to an attribute identifier is either the identifier itself or the concatenation of the qualified identifier and `Attribute`. When the compiler resolves an attribute name, it appends `Attribute` to the name and tries the lookup. If that lookup fails, the compiler tries the lookup without the suffix. For example, uses of an attribute class `SimpleAttribute` may omit the `Attribute` suffix, thus shortening the name to `Simple`:\n\n```vb\n<Simple> Class Class1\nEnd Class\n\n<Simple> Interface Interface1\nEnd Interface\n```\n\nThe example above is semantically equivalent to the following:\n\n```vb\n<SimpleAttribute> Class Class1\nEnd Class\n\n<SimpleAttribute> Interface Interface1\nEnd Interface\n```\n\nIn general, attributes named with the suffix `Attribute` are preferred. The following example shows two attribute classes named `T` and `T``Attribute`.\n\n```vb\n<AttributeUsage(AttributeTargets.All)> _\nPublic Class T\n    Inherits System.Attribute\nEnd Class\n\n<AttributeUsage(AttributeTargets.All)> _\nPublic Class TAttribute\n    Inherits System.Attribute\nEnd Class\n\n' Refers to TAttribute.\n<T> Class Class1 \nEnd Class\n\n' Refers to TAttribute.\n<TAttribute> Class Class2 \nEnd Class\n```\n\nBoth the attribute block `<T>` and the attribute block `<TAttribute>` refer to the attribute class named `TAttribute`. It is not possible to use `T` as an attribute until you remove the declaration for class `TAttribute`.\n\n### Attribute Arguments\n\nArguments to an attribute may take two forms: *positional arguments* and *instance variable/property initializers*. Any positional arguments to the attribute must precede the instance variable/property initializers. A positional argument consists of a constant expression, a one-dimensional array-creation expression or a `GetType` expression. An instance variable/property initializer consists of an identifier, which can match keywords, followed by a colon and equal sign, and terminated by a constant expression or a `GetType` expression.\n\nGiven an attribute with attribute class `T`, positional argument list `P`, and instance variable/property initializer list `N`, these steps determine whether the arguments are valid:\n\n1. Follow the compile-time processing steps for compiling an expression of the form `New T(P)`. This either results in a compile-time error or determines a constructor on `T` that is most applicable to the argument list.\n\n2. If the constructor determined in step 1 has parameters that are not attribute types or is inaccessible at the declaration site, a compile-time error occurs.\n\n3. For each instance variable/property initializer `Arg` in `N`, let `Name` be the identifier of the instance variable/property initializer `Arg`. `Name` must identify a non-`Shared`, writeable, `Public` instance variable or parameterless property on `T` whose type is an attribute type. If `T` has no such instance variable or property, a compile-time error occurs.\n\nFor example:\n\n```vb\n<AttributeUsage(AttributeTargets.All)> _\nPublic Class GeneralAttribute\n    Inherits Attribute\n\n    Public Sub New(x As Integer)\n    End Sub\n\n    Public Sub New(x As Double)\n    End Sub\n\n    Public y As Type\n\n    Public Property z As Integer\n        Get\n        End Get\n\n        Set\n        End Set\n    End Property\nEnd Class\n\n' Calls the first constructor.\n<General(10, z:=30, y:=GetType(Integer))> _\nClass C1\nEnd Class\n\n' Calls the second constructor.\n<General(10.5, z:=10)> _\nClass C2\nEnd Class\n```\n\nType parameters cannot be used anywhere in attribute arguments. However, constructed types may be used:\n\n```vb\n<AttributeUsage(AttributeTargets.All)> _\nClass A \n   Inherits System.Attribute \n\n   Public Sub New(t As Type)\n   End Sub \nEnd Class\n\nClass List(Of T) \n    ' Error: attribute argument cannot use type parameter\n    <A(GetType(T))> Dim t1 As T \n\n    ' OK: closed type\n    <A(GetType(List(Of Integer)))> Dim y As Integer\nEnd Class\n```\n\n\n```antlr\nAttributeArguments\n    : AttributePositionalArgumentList\n    | AttributePositionalArgumentList Comma VariablePropertyInitializerList\n    | VariablePropertyInitializerList\n    ;\n\nAttributePositionalArgumentList\n    : AttributeArgumentExpression? ( Comma AttributeArgumentExpression? )*\n    ;\n\nVariablePropertyInitializerList\n    : VariablePropertyInitializer ( Comma VariablePropertyInitializer )*\n    ;\n\nVariablePropertyInitializer\n    : IdentifierOrKeyword ColonEquals AttributeArgumentExpression\n    ;\n\nAttributeArgumentExpression\n    : ConstantExpression\n    | GetTypeExpression\n    | ArrayExpression\n    ;\n```\n"
  },
  {
    "path": "spec/conversions.md",
    "content": "# Conversions in Visual Basic\n\nConversion is the process of changing a value from one type to another. For example, a value of type `Integer` can be converted to a value of type `Double`, or a value of type `Derived` can be converted to a value of type `Base`, assuming that `Base` and `Derived` are both classes and `Derived` inherits from `Base`. Conversions may not require the value itself to change (as in the latter example), or they may require significant changes in the value representation (as in the former example).\n\nConversions may either be widening or narrowing. A *widening conversion* is a conversion from a type to another type whose value domain is at least as big, if not bigger, than the original type's value domain. Widening conversions should never fail. A *narrowing conversion* is a conversion from a type to another type whose value domain is either smaller than the original type's value domain or sufficiently unrelated that extra care must be taken when doing the conversion (for example, when converting from `Integer` to `String`). Narrowing conversions, which may entail loss of information, can fail.\n\nThe identity conversion (i.e. a conversion from a type to itself) and default value conversion (i.e. a conversion from `Nothing`) are defined for all types.\n\n## Implicit and Explicit Conversions\n\nConversions can be either *implicit* or *explicit*. Implicit conversions occur without any special syntax. The following is an example of implicit conversion of an `Integer` value to a `Long` value:\n\n```vb\nModule Test\n    Sub Main()\n        Dim intValue As Integer = 123\n        Dim longValue As Long = intValue\n\n        Console.WriteLine(intValue & \" = \" & longValue)\n    End Sub\nEnd Module\n```\n\nExplicit conversions, on the other hand, require cast operators. Attempting to do an explicit conversion on a value without a cast operator causes a compile-time error. The following example uses an explicit conversion to convert a `Long` value to an `Integer` value.\n\n```vb\nModule Test\n    Sub Main()\n        Dim longValue As Long = 134\n        Dim intValue As Integer = CInt(longValue)\n\n        Console.WriteLine(longValue & \" = \" & intValue)\n    End Sub\nEnd Module\n```\n\nThe set of implicit conversions depends on the compilation environment and the `Option Strict` statement. If strict semantics are being used, only widening conversions may occur implicitly. If permissive semantics are being used, all widening and narrowing conversions (in other words, all conversions) may occur implicitly.\n\n## Boolean Conversions\n\nAlthough `Boolean` is not a numeric type, it does have narrowing conversions to and from the numeric types as if it were an enumerated type. The literal `True` converts to the literal `255` for `Byte`, `65535` for `UShort`, `4294967295` for `UInteger`, `18446744073709551615` for `ULong`, and to the expression `-1` for `SByte`, `Short`, `Integer`, `Long`, `Decimal`, `Single`, and `Double`. The literal `False` converts to the literal `0`. A zero numeric value converts to the literal `False`. All other numeric values convert to the literal `True`.\n\nThere is a narrowing conversion from Boolean to String, converting to either `System.Boolean.TrueString` or `System.Boolean.FalseString`. There is also a narrowing conversion from `String` to `Boolean`: if the string was equal to `TrueString` or `FalseString` (in the current culture, case-insensitively) then it uses the appropriate value; otherwise it attempts to parse the string as a numeric type (in hex or octal if possible, otherwise as a float) and uses the above rules; otherwise it throws `System.InvalidCastException`.\n\n## Numeric Conversions\n\nNumeric conversions exist between the types `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, `Long`, `Decimal`, `Single` and `Double`, and all enumerated types. When being converted, enumerated types are treated as if they were their underlying types. When converting to an enumerated type, the source value is not required to conform to the set of values defined in the enumerated type. For example:\n\n```vb\nEnum Values\n    One\n    Two\n    Three\nEnd Enum\n\nModule Test\n    Sub Main()\n        Dim x As Integer = 5\n\n        ' OK, even though there is no enumerated value for 5.\n        Dim y As Values = CType(x, Values)\n    End Sub\nEnd Module\n```\n\nNumeric conversions are processed at run-time as follows:\n\n* For a conversion from a numeric type to a wider numeric type, the value is simply converted to the wider type. Conversions from `UInteger`, `Integer`, `ULong`, `Long`, or `Decimal` to `Single` or `Double` are rounded to the nearest `Single` or `Double` value. While this conversion may cause a loss of precision, it will never cause a loss of magnitude.\n\n* For a conversion from an integral type to another integral type, or from `Single`, `Double`, or `Decimal` to an integral type, the result depends on whether integer overflow checking is on:\n\n  *If integer overflow is being checked:*\n\n  * If the source is an integral type, the conversion succeeds if the source argument is within the range of the destination type. The conversion throws a `System.OverflowException` exception if the source argument is outside the range of the destination type.\n\n  * If the source is `Single`, `Double`, or `Decimal`, the source value is rounded up or down to the nearest integral value, and this integral value becomes the result of the conversion. If the source value is equally close to two integral values, the value is rounded to the value that has an even number in the least significant digit position. If the resulting integral value is outside the range of the destination type, a `System.OverflowException` exception is thrown.\n\n  *If integer overflow is not being checked:*\n\n  * If the source is an integral type, the conversion always succeeds and simply consists of discarding the most significant bits of the source value.\n\n  * If the source is `Single`, `Double`, or `Decimal`, the conversion always succeeds and simply consists of rounding the source value towards the nearest integral value. If the source value is equally close to two integral values, the value is always rounded to the value that has an even number in the least significant digit position.\n\n* For a conversion from `Double` to `Single`, the `Double` value is rounded to the nearest `Single` value. If the `Double` value is too small to represent as a `Single`, the result becomes positive zero or negative zero. If the `Double` value is too large to represent as a `Single`, the result becomes positive infinity or negative infinity. If the `Double` value is `NaN`, the result is also `NaN`.\n\n* For a conversion from `Single` or `Double` to `Decimal`, the source value is converted to `Decimal` representation and rounded to the nearest number after the 28th decimal place if required. If the source value is too small to represent as a `Decimal`, the result becomes zero. If the source value is `NaN`, infinity, or too large to represent as a `Decimal`, a `System.OverflowException` exception is thrown.\n\n* For a conversion from `Double` to `Single`, the `Double` value is rounded to the nearest `Single` value. If the `Double` value is too small to represent as a `Single`, the result becomes positive zero or negative zero. If the `Double` value is too large to represent as a `Single`, the result becomes positive infinity or negative infinity. If the `Double` value is `NaN`, the result is also `NaN`.\n\n## Reference Conversions\n\nReference types may be converted to a base type, and vice versa. Conversions from a base type to a more derived type only succeed at run time if the value being converted is a null value, the derived type itself, or a more derived type.\n\nClass and interface types can be cast to and from any interface type. Conversions between a type and an interface type only succeed at run time if the actual types involved have an inheritance or implementation relationship. Because an interface type will always contain an instance of a type that derives from `Object`, an interface type can also always be cast to and from `Object`.\n\n__Note.__ It is not an error to convert a `NotInheritable` classes to and from interfaces that it does not implement because classes that represent COM classes may have interface implementations that are not known until run time. \n\nIf a reference conversion fails at run time, a `System.InvalidCastException` exception is thrown.\n\n### Reference Variance Conversions\n\nGeneric interfaces or delegates may have variant type parameters that allow conversions between compatible variants of the type. Therefore, at runtime a conversion from a class type or an interface type to an interface type that is variant compatible with an interface type it inherits from or implements will succeed. Similarly, delegate types can be cast to and from variant compatible delegate types. For example, the delegate type\n\n```vb\nDelegate Function F(Of In A, Out R)(a As A) As R\n```\n\nwould allow a conversion from `F(Of Object, Integer)` to `F(Of String, Integer)`. That is, a delegate `F` which takes `Object` may be safely used as a delegate `F` which takes `String`. When the delegate is invoked, the target method will be expecting an object, and a string is an object.\n\nA generic delegate or interface type `S(Of S1,...,Sn)` is said to be *variant compatible* with a generic interface or delegate type `T(Of T1,...,Tn)` if:\n\n* `S` and `T` are both constructed from the same generic type `U(Of U1,...,Un)`.\n\n* For each type parameter `Ux`:\n\n  * If the type parameter was declared without variance then `Sx` and `Tx` must be the same type.\n\n  * If the type parameter was declared `In` then there must be a widening identity, default, reference, array, or type parameter conversion from `Sx` to `Tx`.\n\n  * If the type parameter was declared `Out` then there must be a widening identity, default, reference, array, or type parameter conversion from `Tx` to `Sx`.\n\nWhen converting from a class to a generic interface with variant type parameters, if the class implements more than one variant compatible interface the conversion is ambiguous if there is not a non-variant conversion. For example:\n\n```vb\nClass Base\nEnd Class\n\nClass Derived1\n    Inherits Base\nEnd Class\n\nClass Derived2\n    Inherits Base\nEnd Class\n\nClass OneAndTwo\n    Implements IEnumerable(Of Derived1)\n    Implements IEnumerable(Of Derived2)\nEnd Class\n\nClass BaseAndOneAndTwo\n    Implements IEnumerable(Of Base)\n    Implements IEnumerable(Of Derived1)\n    Implements IEnumerable(Of Derived2)\nEnd Class\n\nModule Test\n    Sub Main()\n        ' Error: conversion is ambiguous\n        Dim x As IEnumerable(Of Base) = New OneAndTwo()\n\n        ' OK, will pick up the direct implementation of IEnumerable(Of Base)\n        Dim y as IEnumerable(Of Base) = New BaseAndOneAndTwo()\n    End Sub\nEnd Module\n```\n\n### Anonymous Delegate Conversions\n\nWhen an expression classified as a lambda method is reclassified as a value in a context where there is no target type (for example, `Dim x = Function(a As Integer, b As Integer) a + b`), or where the target type is not a delegate type, the type of the resulting expression is an anonymous delegate type equivalent to the signature of the lambda method. This anonymous delegate type has a conversion to any compatible delegate type: a compatible delegate type is any delegate type that can be created using a delegate creation expression with the anonymous delegate type's `Invoke` method as a parameter. For example:\n\n```vb\n' Anonymous delegate type similar to Func(Of Object, Object, Object)\nDim x = Function(x, y) x + y\n\n' OK because delegate type is compatible\nDim y As Func(Of Integer, Integer, Integer) = x\n```\n\nNote that the types `System.Delegate` and `System.MulticastDelegate` are not themselves considered delegate types (even though all delegate types inherit from them). Also, note that the conversion from anonymous delegate type to a compatible delegate type is not a reference conversion.\n\n## Array Conversions\n\nBesides the conversions that are defined on arrays by virtue of the fact that they are reference types, several special conversions exist for arrays.\n\nFor any two types `A` and `B`, if they are both reference types or type parameters not known to be value types, and if `A` has a reference, array, or type parameter conversion to `B`, a conversion exists from an array of type `A` to an array of type `B` with the same rank. This relationship is known as *array covariance*. Array covariance in particular means that an element of an array whose element type is `B` may actually be an element of an array whose element type is `A`, provided that both `A` and `B` are reference types and that `B` has a reference conversion or array conversion to `A`. In the following example, the second invocation of `F` causes a `System.ArrayTypeMismatchException` exception to be thrown because the actual element type of `b` is `String`, not `Object`:\n\n```vb\nModule Test\n    Sub F(ByRef x As Object)\n    End Sub\n\n    Sub Main()\n        Dim a(10) As Object\n        Dim b() As Object = New String(10) {}\n        F(a(0)) ' OK.\n        F(b(1)) ' Not allowed: System.ArrayTypeMismatchException.\n   End Sub\nEnd Module\n```\n\nBecause of array covariance, assignments to elements of reference type arrays include a run-time check that ensures that the value being assigned to the array element is actually of a permitted type.\n\n```vb\nModule Test\n    Sub Fill(array() As Object, index As Integer, count As Integer, _\n            value As Object)\n        Dim i As Integer\n\n        For i = index To (index + count) - 1\n            array(i) = value\n        Next i\n    End Sub\n\n    Sub Main()\n        Dim strings(100) As String\n\n        Fill(strings, 0, 101, \"Undefined\")\n        Fill(strings, 0, 10, Nothing)\n        Fill(strings, 91, 10, 0)\n    End Sub\nEnd Module\n```\n\nIn this example, the assignment to `array(i)` in method `Fill` implicitly includes a run-time check that ensures that the object referenced by the variable `value` is either `Nothing` or an instance of a type that is compatible with the actual element type of array `array`. In method `Main`, the first two invocations of method `Fill` succeed, but the third invocation causes a `System.ArrayTypeMismatchException` exception to be thrown upon executing the first assignment to `array(i)`. The exception occurs because an `Integer` cannot be stored in a `String` array.\n\nIf one of the array element types is a type parameter whose type turns out to be a value type at runtime, a `System.InvalidCastException` exception will be thrown. For example:\n\n```vb\nModule Test\n    Sub F(Of T As U, U)(x() As T)\n        Dim y() As U = x\n    End Sub\n\n    Sub Main()\n        ' F will throw an exception because Integer() cannot be\n        ' converted to Object()\n        F(New Integer() { 1, 2, 3 })\n    End Sub\nEnd Module\n```\n\nConversions also exist between an array of an enumerated type and an array of the enumerated type's underlying type or an array of another enumerated type with the same underlying type, provided the arrays have the same rank.\n\n```vb\nEnum Color As Byte\n    Red\n    Green\n    Blue\nEnd Enum\n\nModule Test\n    Sub Main()\n        Dim a(10) As Color\n        Dim b() As Integer\n        Dim c() As Byte\n\n        b = a    ' Error: Integer is not the underlying type of Color\n        c = a    ' OK\n        a = c    ' OK\n    End Sub\nEnd Module\n```\n\nIn this example, an array of `Color` is converted to and from an array of `Byte`, `Color`'s underlying type. The conversion to an array of `Integer`, however, will be an error because `Integer` is not the underlying type of `Color`.\n\nA rank-1 array of type `A()` also has an array conversion to the collection interface types `IList(Of B)`, `IReadOnlyList(Of B)`, `ICollection(Of B)`, `IReadOnlyCollection(Of B)` and `IEnumerable(Of B)` found in `System.Collections.Generic`, so long as one of the following is true:\n\n- `A` and `B` are both reference types or type parameters not known to be value types; and `A` has a widening reference, array or type parameter conversion to `B`; or\n- `A` and `B` are both enumerated types of the same underlying type; or\n- one of `A` and `B` is an enumerated type, and the other is its underlying type.\n\nAny array of type A with any rank also has an array conversion to the non-generic collection interface types `IList`, `ICollection` and `IEnumerable` found in `System.Collections`.\n\nIt is possible to iterate over the resulting interfaces using `For Each`, or through invoking the `GetEnumerator` methods directly. In the case of rank-1 arrays converted generic or non-generic forms of `IList` or `ICollection`, it is also possible to get elements by index. In the case of rank-1 arrays converted to generic or non-generic forms of `IList`, it is also possible to set elements by index, subject to the same runtime array covariance checks as described above. The behavior of all other interface methods is undefined by the VB language specification; it is up to the underlying runtime.\n\n## Value Type Conversions\n\nA value type value can be converted to one of its base reference types or an interface type that it implements through a process called *boxing*. When a value type value is boxed, the value is copied from the location where it lives onto the .NET Framework heap. A reference to this location on the heap is then returned and can be stored in a reference type variable. This reference is also referred to as a *boxed* instance of the value type. The boxed instance has the same semantics as a reference type instead of a value type.\n\nBoxed value types can be converted back to their original value type through a process called *unboxing*. When a boxed value type is unboxed, the value is copied from the heap into a variable location. From that point on, it behaves as if it was a value type. When unboxing a value type, the value must be a null value or an instance of the value type. Otherwise a `System.InvalidCastException` exception is thrown. If the value is an instance of an enumerated type, that value can also be unboxed to the enumerated type's underlying type or another enumerated type that has the same underlying type. A null value is treated as if it were the literal `Nothing`.\n\nTo support nullable value types well, the value type `System.Nullable(Of T)` is treated specially when doing boxing and unboxing. Boxing a value of type `Nullable(Of T)` results in a boxed value of type `T` if the value's `HasValue` property is `True` or a value of `Nothing` if the value's `HasValue` property is `False`. Unboxing a value of type `T` to `Nullable(Of T)` results in an instance of `Nullable(Of T)` whose `Value` property is the boxed value and whose `HasValue` property is `True`. The value `Nothing` can be unboxed to `Nullable(Of T)` for any `T` and results in a value whose `HasValue` property is `False`. Because boxed value types behave like reference types, it is possible to create multiple references to the same value. For the primitive types and enumerated types, this is irrelevant because instances of those types are *immutable*. That is, it is not possible to modify a boxed instance of those types, so it is not possible to observe the fact that there are multiple references to the same value.\n\nStructures, on the other hand, may be mutable if its instance variables are accessible or if its methods or properties modify its instance variables. If one reference to a boxed structure is used to modify the structure, then all references to the boxed structure will see the change. Because this result may be unexpected, when a value typed as `Object` is copied from one location to another boxed value types will automatically be cloned on the heap instead of merely having their references copied. For example:\n\n```vb\nClass Class1\n    Public Value As Integer = 0\nEnd Class\n\nStructure Struct1\n    Public Value As Integer\nEnd Structure\n\nModule Test\n    Sub Main()\n        Dim val1 As Object = New Struct1()\n        Dim val2 As Object = val1\n\n        val2.Value = 123\n\n        Dim ref1 As Object = New Class1()\n        Dim ref2 As Object = ref1\n\n        ref2.Value = 123\n\n        Console.WriteLine(\"Values: \" & val1.Value & \", \" & val2.Value)\n        Console.WriteLine(\"Refs: \" & ref1.Value & \", \" & ref2.Value)\n    End Sub\nEnd Module\n```\n\nThe output of the program is:\n\n```console\nValues: 0, 123\nRefs: 123, 123\n```\n\nThe assignment to the field of the local variable `val2` does not impact the field of the local variable `val1` because when the boxed `Struct1` was assigned to `val2`, a copy of the value was made. In contrast, the assignment `ref2.Value = 123` affects the object that both `ref1` and `ref2` references.\n\n__Note.__ Structure copying is not done for boxed structures typed as `System.ValueType` because it is not possible to late bind off of `System.ValueType`.\n\nThere is one exception to the rule that boxed value types will be copied on assignment. If a boxed value type reference is stored within another type, the inner reference will not be copied. For example:\n\n```vb\nStructure Struct1\n    Public Value As Object\nEnd Structure\n\nModule Test\n    Sub Main()\n        Dim val1 As Struct1\n        Dim val2 As Struct1\n\n        val1.Value = New Struct1()\n        val1.Value.Value = 10\n\n        val2 = val1\n        val2.Value.Value = 123\n        Console.WriteLine(\"Values: \" & val1.Value.Value & \", \" & _\n            val2.Value.Value)\n    End Sub\nEnd Module\n```\n\nThe output of the program is:\n\n```console\nValues: 123, 123\n```\n\nThis is because the inner boxed value is not copied when the value is copied. Thus, both `val1.Value` and `val2.Value` have a reference to the same boxed value type.\n\n__Note.__ The fact that inner boxed value types are not copied is a limitation of the .NET type system -- to ensure that all inner boxed value types were copied whenever a value of type `Object` was copied would be prohibitively expensive.\n\nAs previously described, boxed value types can only be unboxed to their original type. Boxed primitive types, however, are treated specially when typed as `Object`. They can be converted to any other primitive type that they have a conversion to. For example:\n\n```vb\nModule Test\n    Sub Main()\n        Dim o As Object = 5\n        Dim b As Byte = CByte(o)  ' Legal\n        Console.WriteLine(b) ' Prints 5\n    End Sub\nEnd Module\n```\n\nNormally, the boxed `Integer` value `5` could not be unboxed into a `Byte` variable. However, because `Integer` and `Byte` are primitive types and have a conversion, the conversion is allowed.\n\nIt is important to note that converting a value type to an interface is different than a generic argument constrained to an interface. When accessing interface members on a constrained type parameter (or calling methods on `Object`), boxing does not occur as it does when a value type is converted to an interface and an interface member is accessed. For example, suppose an interface `ICounter` contains a method `Increment` which can be used to modify a value. If `ICounter` is used as a constraint, the implementation of the `Increment` method is called with a reference to the variable that `Increment` was called on, not a boxed copy:\n\n```vb\nInterface ICounter\n    Sub Increment()\n    ReadOnly Property Value() As Integer\nEnd Interface\n\nStructure Counter\n    Implements ICounter\n\n    Dim _value As Integer\n\n    Property Value() As Integer Implements ICounter.Value\n        Get\n            Return _value\n        End Get\n    End Property\n\n    Sub Increment() Implements ICounter.Increment\n       value += 1\n    End Sub\nEnd Structure\n\nModule Test\n      Sub Test(Of T As ICounter)(x As T)\n         Console.WriteLine(x.value)\n         x.Increment()                     ' Modify x\n         Console.WriteLine(x.value)\n         CType(x, ICounter).Increment()    ' Modify boxed copy of x\n         Console.WriteLine(x.value)\n      End Sub\n\n      Sub Main()\n         Dim x As Counter\n         Test(x)\n      End Sub\nEnd Module\n```\n\nThe first call to `Increment` modifies the value in the variable `x`. This is not equivalent to the second call to `Increment`, which modifies the value in a boxed copy of `x`. Thus, the output of the program is:\n\n```console\n0\n1\n1\n```\n\n### Nullable Value Type Conversions\n\nA value type `T` can convert to and from the nullable version of the type, `T?`. The conversion from `T?` to `T` throws a `System.InvalidOperationException` exception if the value being converted is `Nothing`. Also, `T?` has a conversion to a type `S` if `T` has an intrinsic conversion to `S`. And if `S` is a value type, then the following intrinsic conversions exist between `T?` and `S?`:\n\n* A conversion of the same classification (narrowing or widening) from `T?` to `S?`.\n\n* A conversion of the same classification (narrowing or widening) from `T` to `S?`.\n\n* A narrowing conversion from `S?` to `T`.\n\nFor example, an intrinsic widening conversion exists from `Integer?` to `Long?` because an intrinsic widening conversion exists from `Integer` to `Long`:\n\n```vb\nDim i As Integer? = 10\nDim l As Long? = i\n```\n\nWhen converting from `T?` to `S?`, if the value of `T?` is `Nothing`, then the value of `S?` will be `Nothing`. When converting from `S?` to `T` or `T?` to `S`, if the value of `T?` or `S?` is `Nothing`, a `System.InvalidCastException` exception will be thrown.\n\nBecause of the behavior of the underlying type `System.Nullable(Of T)`, when a nullable value type `T?` is boxed, the result is a boxed value of type `T`, not a boxed value of type `T?`. And, conversely, when unboxing to a nullable value type `T?`, the value will be wrapped by `System.Nullable(Of T)`, and `Nothing` will be unboxed to a null value of type `T?`. For example:\n\n```vb\nDim i1? As Integer = Nothing\nDim o1 As Object = i1\n\nConsole.WriteLine(o1 Is Nothing)                    ' Will print True\no1 = 10\ni1 = CType(o1, Integer?)\nConsole.WriteLine(i1)                               ' Will print 10\n```\n\nA side effect of this behavior is that a nullable value type `T?` appears to implement all of the interfaces of `T`, because converting a value type to an interface requires the type to be boxed. As a result, `T?` is convertible to all the interfaces that `T` is convertible to. It is important to note, however, that a nullable value type `T?` does not actually implement the interfaces of `T` for the purposes of generic constraint checking or reflection. For example:\n\n```vb\nInterface I1\nEnd Interface\n\nStructure T1\n    Implements I1\n    ...\nEnd Structure\n\nModule Test\n    Sub M1(Of T As I1)(ByVal x As T)\n    End Sub\n\n    Sub Main()\n        Dim x? As T1 = Nothing\n        Dim y As I1 = x                ' Valid\n        M1(x)                          ' Error: x? does not satisfy I1 constraint\n    End Sub\nEnd Module\n```\n\n## String Conversions\n\nConverting `Char` into `String` results in a string whose first character is the character value. Converting `String` into `Char` results in a character whose value is the first character of the string. Converting an array of `Char` into `String` results in a string whose characters are the elements of the array. Converting `String` into an array of `Char` results in an array of characters whose elements are the characters of the string.\n\nThe exact conversions between `String` and `Boolean`, `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, `Long`, `Decimal`, `Single`, `Double`, `Date`, and vice versa, are beyond the scope of this specification and are implementation dependent with the exception of one detail. String conversions always consider the current culture of the run-time environment. As such, they must be performed at run time.\n\n## Widening Conversions\n\nWidening conversions never overflow but may entail a loss of precision. The following conversions are widening conversions:\n\n__Identity/Default conversions__\n\n* From a type to itself.\n\n* From an anonymous delegate type generated for a lambda method reclassification to any delegate type with an identical signature.\n\n* From the literal `Nothing` to a type.\n\n__Numeric conversions__\n\n* From `Byte` to `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, `Long`, `Decimal`, `Single`, or `Double`.\n\n* From `SByte` to `Short`, `Integer`, `Long`, `Decimal`, `Single`, or `Double`.\n\n* From `UShort` to `UInteger`, `Integer`, `ULong`, `Long`, `Decimal`, `Single`, or `Double`.\n\n* From `Short` to `Integer`, `Long`, `Decimal`, `Single` or `Double`.\n\n* From `UInteger` to `ULong`, `Long`, `Decimal`, `Single`, or `Double`.\n\n* From `Integer` to `Long`, `Decimal`, `Single` or `Double`.\n\n* From `ULong` to `Decimal`, `Single`, or `Double`.\n\n* From `Long` to `Decimal`, `Single` or `Double`.\n\n* From `Decimal` to `Single` or `Double`.\n\n* From `Single` to `Double`.\n\n* From the literal `0` to an enumerated type. (__Note.__ The conversion from `0` to any enumerated type is widening to simplify testing flags. For example, if `Values` is an enumerated type with a value `One`, you could test a variable `v` of type `Values` by saying `(v And Values.One) = 0`.)\n\n* From an enumerated type to its underlying numeric type, or to a numeric type that its underlying numeric type has a widening conversion to.\n\n* From a constant expression of type `ULong`, `Long`, `UInteger`, `Integer`, `UShort`, `Short`, `Byte`, or `SByte` to a narrower type, provided the value of the constant expression is within the range of the destination type. (__Note.__ Conversions from `UInteger` or `Integer` to `Single`, `ULong` or `Long` to `Single` or `Double`, or `Decimal` to `Single` or `Double` may cause a loss of precision, but will never cause a loss of magnitude. The other widening numeric conversions never lose any information.)\n\n__Reference conversions__\n\n* From a reference type to a base type.\n\n* From a reference type to an interface type, provided that the type implements the interface or a variant compatible interface.\n\n* From an interface type to `Object`.\n\n* From an interface type to a variant compatible interface type.\n\n* From a delegate type to a variant compatible delegate type. (__Note.__ Many other reference conversions are implied by these rules. For example, anonymous delegates are reference types that inherit from `System.MulticastDelegate`; array types are reference types that inherit from `System.Array`; anonymous types are reference types that inherit from `System.Object`.)\n\n__Anonymous Delegate conversions__\n\n* From an anonymous delegate type generated for a lambda method reclassification to any wider delegate type.\n\n__Array conversions__\n\n* From an array type `S` with an element type `Se` to an array type `T` with an element type `Te`, provided all of the following are true:\n\n  * `S` and `T` differ only in element type.\n\n  * Both `Se` and `Te` are reference types or are type parameters known to be a reference type.\n\n  * A widening reference, array, or type parameter conversion exists from `Se` to `Te`.\n\n* From an array type `S` with an enumerated element type `Se` to an array type `T` with an element type `Te`, provided all of the following are true:\n\n  * `S` and `T` differ only in element type.\n\n  * `Te` is the underlying type of `Se`.\n\n* From an array type `S` of rank 1 with an enumerated element type `Se`, to `System.Collections.Generic.IList(Of Te)`, `IReadOnlyList(Of Te)`, `ICollection(Of Te)`, `IReadOnlyCollection(Of Te)`, and `IEnumerable(Of Te)`, provided one of the following is true:\n\n  * Both `Se` and `Te` are reference types or are type parameters known to be a reference type, and a widening reference, array, or type parameter conversion exists from `Se` to `Te`; or\n\n  * `Te` is the underlying type of `Se`; or\n\n  * `Te` is identical to `Se`\n\n__Value Type conversions__\n\n* From a value type to a base type.\n\n* From a value type to an interface type that the type implements.\n\n__Nullable Value Type conversions__\n\n* From a type `T` to the type `T?`.\n\n* From a type `T?` to a type `S?`, where there is a widening conversion from the type `T` to the type `S`.\n\n* From a type `T` to a type `S?`, where there is a widening conversion from the type `T` to the type `S`.\n\n* From a type `T?` to an interface type that the type `T` implements.\n\n__String conversions__\n\n* From `Char` to `String`.\n\n* From `Char()` to `String`.\n\n__Type Parameter conversions__\n\n* From a type parameter to `Object`.\n\n* From a type parameter to an interface type constraint or any interface variant compatible with an interface type constraint.\n\n* From a type parameter to an interface implemented by a class constraint.\n\n* From a type parameter to an interface variant compatible with an interface implemented by a class constraint.\n\n* From a type parameter to a class constraint, or a base type of the class constraint.\n\n* From a type parameter `T` to a type parameter constraint `Tx`, or anything `Tx` has a widening conversion to.\n\n## Narrowing Conversions\n\nNarrowing conversions are conversions that cannot be proved to always succeed, conversions that are known to possibly lose information, and conversions across domains of types sufficiently different to merit narrowing notation. The following conversions are classified as narrowing conversions:\n\n__Boolean conversions__\n\n* From `Boolean` to `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, `Long`, `Decimal`, `Single`, or `Double`.\n\n* From `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, `Long`, `Decimal`, `Single`, or `Double` to `Boolean`.\n\n__Numeric conversions__\n\n* From `Byte` to `SByte`.\n\n* From `SByte` to `Byte`, `UShort`, `UInteger`, or `ULong`.\n\n* From `UShort` to `Byte`, `SByte`, or `Short`.\n\n* From `Short` to `Byte`, `SByte`, `UShort`, `UInteger`, or `ULong`.\n\n* From `UInteger` to `Byte`, `SByte`, `UShort`, `Short`, or `Integer`.\n\n* From `Integer` to `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, or `ULong`.\n\n* From `ULong` to `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, or `Long`.\n\n* From `Long` to `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, or `ULong`.\n\n* From `Decimal` to `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, or `Long`.\n\n* From `Single` to `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, `Long`, or `Decimal`.\n\n* From `Double` to `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, `Long`, `Decimal`, or `Single`.\n\n* From a numeric type to an enumerated type.\n\n* From an enumerated type to a numeric type its underlying numeric type has a narrowing conversion to.\n\n* From an enumerated type to another enumerated type.\n\n__Reference conversions__\n\n* From a reference type to a more derived type.\n\n* From a class type to an interface type, provided the class type does not implement the interface type or an interface type variant compatible with it.\n\n* From an interface type to a class type.\n\n* From an interface type to another interface type, provided there is no inheritance relationship between the two types and provided they are not variant compatible.\n\n__Anonymous Delegate conversions__\n\n* From an anonymous delegate type generated for a lambda method reclassification to any narrower delegate type.\n\n__Array conversions__\n\n* From an array type `S` with an element type `Se`, to an array type `T` with an element type `Te`, provided that all of the following are true:\n\n  * `S` and `T` differ only in element type.\n  * Both `Se` and `Te` are reference types or are type parameters not known to be value types.\n  * A narrowing reference, array, or type parameter conversion exists from `Se` to `Te`.\n\n* From an array type `S` with an element type `Se` to an array type `T` with an enumerated element type `Te`, provided all of the following are true:\n\n  * `S` and `T` differ only in element type.\n  * `Se` is the underlying type of `Te` , or they are both different enumerated types that share the same underlying type.\n\n* From an array type `S` of rank 1 with an enumerated element type `Se`, to `IList(Of Te)`, `IReadOnlyList(Of Te)`, `ICollection(Of Te)`, `IReadOnlyCollection(Of Te)` and `IEnumerable(Of Te)`, provided one of the following is true:\n\n  * Both `Se` and `Te` are reference types or are type parameters known to be a reference type, and a narrowing reference, array, or type parameter conversion exists from `Se` to `Te`; or\n  * `Se` is the underlying type of `Te`, or they are both different enumerated types that share the same underlying type.\n\n__Value type conversions__\n\n* From a reference type to a more derived value type.\n\n* From an interface type to a value type, provided the value type implements the interface type.\n\n__Nullable Value Type conversions__\n\n* From a type `T?` to a type `T`.\n\n* From a type `T?` to a type `S?`, where there is a narrowing conversion from the type `T` to the type `S`.\n\n* From a type `T` to a type `S?`, where there is a narrowing conversion from the type `T` to the type `S`.\n\n* From a type `S?` to a type `T`, where there is a conversion from the type `S` to the type `T`.\n\n__String conversions__\n\n* From `String` to `Char`.\n\n* From `String` to `Char()`.\n\n* From `String` to `Boolean` and from `Boolean` to `String`.\n\n* Conversions between `String` and `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, `Long`, `Decimal`, `Single`, or `Double`.\n\n* From `String` to `Date` and from `Date` to `String`.\n\n__Type Parameter conversions__\n\n* From `Object` to a type parameter.\n\n* From a type parameter to an interface type, provided the type parameter is not constrained to that interface or constrained to a class that implements that interface.\n\n* From an interface type to a type parameter.\n\n* From a type parameter to a derived type of a class constraint.\n\n* From a type parameter `T` to anything a type parameter constraint `Tx` has a narrowing conversion to.\n\n## Type Parameter Conversions\n\nType parameters' conversions are determined by the constraints, if any, put on them. A type parameter `T` can always be converted to itself, to and from `Object`, and to and from any interface type. Note that if the type `T` is a value type at run-time, converting from `T` to `Object` or an interface type will be a boxing conversion and converting from `Object` or an interface type to `T` will be an unboxing conversion. A type parameter with a class constraint `C` defines additional conversions from the type parameter to `C` and its base classes, and vice versa. A type parameter `T` with a type parameter constraint `Tx` defines a conversion to `Tx` and anything `Tx` converts to.\n\nAn array whose element type is a type parameter with an interface constraint `I` has the same covariant array conversions as an array whose element type is `I`, provided that the type parameter also has a `Class` or class constraint (since only reference array element types can be covariant). An array whose element type is a type parameter with a class constraint `C` has the same covariant array conversions as an array whose element type is `C`.\n\nThe above conversions rules do not permit conversions from unconstrained type parameters to non-interface types, which may be surprising. The reason for this is to prevent confusion about the semantics of such conversions. For example, consider the following declaration:\n\n```vb\nClass X(Of T)\n    Public Shared Function F(t As T) As Long \n        Return CLng(t)    ' Error, explicit conversion not permitted\n    End Function\nEnd Class\n```\n\nIf the conversion of `T` to `Integer` were permitted, one might easily expect that `X(Of Integer).F(7)` would return `7L`. However, it would not, because numeric conversions are only considered when the types are known to be numeric at compile time. In order to make the semantics clear, the above example must instead be written:\n\n```vb\nClass X(Of T)\n    Public Shared Function F(t As T) As Long\n        Return CLng(CObj(t))    ' OK, conversions permitted\n    End Function\nEnd Class\n```\n\n## User-Defined Conversions\n\n*Intrinsic conversions* are conversions defined by the language (i.e. listed in this specification), while *user-defined conversions* are defined by overloading the `CType` operator. When converting between types, if no intrinsic conversions are applicable then user-defined conversions will be considered. If there is a user-defined conversion that is *most specific* for the source and target types, then the user-defined conversion will be used. Otherwise, a compile-time error results. The most specific conversion is the one whose operand is \"closest\" to the source type and whose result type is \"closest\" to the target type. When determining what user-defined conversion to use, the most specific widening conversion will be used; if no widening conversion is most specific, the most specific narrowing conversion will be used. If there is no most specific narrowing conversion, then the conversion is undefined and a compile-time error occurs.\n\nThe following sections cover how the most specific conversions are determined. They use the following terms:\n\nIf an intrinsic widening conversion exists from a type `A` to a type `B`, and if neither `A` nor `B` are interfaces, then `A` is *encompassed* by `B`, and `B` *encompasses* `A`.\n\nThe *most encompassing* type in a set of types is the one type that encompasses all other types in the set. If no single type encompasses all other types, then the set has no most encompassing type. In intuitive terms, the most encompassing type is the \"largest\" type in the set -- the one type to which each of the other types can be converted through a widening conversion.\n\nThe *most encompassed* type in a set of types is the one type that is encompassed by all other types in the set. If no single type is encompassed by all other types, then the set has no most encompassed type. In intuitive terms, the most encompassed type is the \"smallest\" type in the set -- the one type that can be converted to each of the other types through a narrowing conversion.\n\nWhen collecting the candidate user-defined conversions for a type `T?`, the user-defined conversion operators defined by `T` are used instead. If the type being converted to is also a nullable value type, then any of `T`'s user-defined conversions operators that involve only non-nullable value types are lifted. A conversion operator from `T` to `S` is lifted to be a conversion from `T?` to `S?` and is evaluated by converting `T?` to `T`, if necessary, then evaluating the user-defined conversion operator from `T` to `S` and then converting `S` to `S?`, if necessary. If the value being converted is `Nothing`, however, a lifted conversion operator converts directly into a value of `Nothing` typed as `S?`. For example:\n\n```vb\nStructure S\n    ...\nEnd Structure\n\nStructure T\n    Public Shared Widening Operator CType(ByVal v As T) As S\n        ...\n    End Operator\nEnd Structure\n\nModule Test\n    Sub Main()\n        Dim x As T?\n        Dim y As S?\n\n        y = x                ' Legal: y is still null\n        x = New T()\n        y = x                ' Legal: Converts from T to S\n    End Sub\nEnd Module\n```\n\nWhen resolving conversions, user-defined conversions operators are always preferred over lifted conversion operators. For example:\n\n```vb\nStructure S\n    ...\nEnd Structure\n\nStructure T\n    Public Shared Widening Operator CType(ByVal v As T) As S\n        ...\n    End Operator\n\n    Public Shared Widening Operator CType(ByVal v As T?) As S?\n        ...\n    End Operator\nEnd Structure\n\nModule Test\n    Sub Main()\n        Dim x As T?\n        Dim y As S?\n\n        y = x                ' Calls user-defined conversion, not lifted conversion\n    End Sub\nEnd Module\n```\n\nAt run-time, evaluating a user-defined conversion can involve up to three steps:\n\n1. First, the value is converted from the source type to the operand type using an intrinsic conversion, if necessary.\n\n2. Then, the user-defined conversion is invoked.\n\n3. Finally, the result of the user-defined conversion is converted to the target type using an intrinsic conversion, if necessary.\n\nIt is important to note that evaluation of a user-defined conversion will never involve more than one user-defined conversion operator.\n\n### Most Specific Widening Conversion\n\nDetermining the most specific user-defined widening conversion operator between two types is accomplished using the following steps:\n\n1. First, all of the candidate conversion operators are collected. The candidate conversion operators are all of the user-defined widening conversion operators in the source type and all of the user-defined widening conversion operators in the target type.\n\n2. Then, all non-applicable conversion operators are removed from the set. A conversion operator is applicable to a source type and target type if there is an intrinsic widening conversion operator from the source type to the operand type and there is an intrinsic widening conversion operator from the result of the operator to the target type. If there are no applicable conversion operators, then there is no most specific widening conversion.\n\n3. Then, the most specific source type of the applicable conversion operators is determined:\n\n   * If any of the conversion operators convert directly from the source type, then the source type is the most specific source type.\n\n   * Otherwise, the most specific source type is the most encompassed type in the combined set of source types of the conversion operators. If no most encompassed type can be found, then there is no most specific widening conversion.\n\n4. Then, the most specific target type of the applicable conversion operators is determined:\n\n   * If any of the conversion operators convert directly to the target type, then the target type is the most specific target type.\n\n   * Otherwise, the most specific target type is the most encompassing type in the combined set of target types of the conversion operators. If no most encompassing type can be found, then there is no most specific widening conversion.\n\n5. Then, if exactly one conversion operator converts from the most specific source type to the most specific target type, then this is the most specific conversion operator. If more than one such operator exists, then there is no most specific widening conversion.\n\n### Most Specific Narrowing Conversion\n\nDetermining the most specific user-defined narrowing conversion operator between two types is accomplished using the following steps:\n\n1. First, all of the candidate conversion operators are collected. The candidate conversion operators are all of the user-defined conversion operators in the source type and all of the user-defined conversion operators in the target type.\n\n2. Then, all non-applicable conversion operators are removed from the set. A conversion operator is applicable to a source type and target type if there is an intrinsic conversion operator from the source type to the operand type and there is an intrinsic conversion operator from the result of the operator to the target type. If there are no applicable conversion operators, then there is no most specific narrowing conversion.\n\n3. Then, the most specific source type of the applicable conversion operators is determined:\n\n   * If any of the conversion operators convert directly from the source type, then the source type is the most specific source type.\n\n   * Otherwise, if any of the conversion operators convert from types that encompass the source type, then the most specific source type is the most encompassed type in the combined set of source types of those conversion operators. If no most encompassed type can be found, then there is no most specific narrowing conversion.\n\n   * Otherwise, the most specific source type is the most encompassing type in the combined set of source types of the conversion operators. If no most encompassing type can be found, then there is no most specific narrowing conversion.\n\n4. Then, the most specific target type of the applicable conversion operators is determined:\n\n   * If any of the conversion operators convert directly to the target type, then the target type is the most specific target type.\n\n   * Otherwise, if any of the conversion operators convert to types that are encompassed by the target type, then the most specific target type is the most encompassing type in the combined set of source types of those conversion operators. If no most encompassing type can be found, then there is no most specific narrowing conversion.\n\n   * Otherwise, the most specific target type is the most encompassed type in the combined set of target types of the conversion operators. If no most encompassed type can be found, then there is no most specific narrowing conversion.\n\n5. Then, if exactly one conversion operator converts from the most specific source type to the most specific target type, then this is the most specific conversion operator. If more than one such operator exists, then there is no most specific narrowing conversion.\n\n## Native Conversions\n\nSeveral of the conversions are classified as *native conversions* because they are supported natively by the .NET Framework. These conversions are ones that can be optimized through the use of the `DirectCast` and `TryCast` conversion operators, as well as other special behaviors. The conversions classified as native conversions are: identity conversions, default conversions, reference conversions, array conversions, value type conversions, and type parameter conversions.\n\n## Dominant Type\n\nGiven a set of types, it is often necessary in situations such as type inference to determine the *dominant type* of the set. The dominant type of a set of types is determined by first removing any types that one or more other types do not have an implicit conversion to. If there are no types left at this point, there is no dominant type. The dominant type is then the most encompassed of the remaining types. If there is more than one type that is most encompassed, then there is no dominant type.\n"
  },
  {
    "path": "spec/documentation-comments.md",
    "content": "# Documentation Comments\n\nDocumentation comments are specially formatted comments in the source that can be analyzed to produce documentation about the code they are attached to. The basic format for documentation comments is XML. When the compiling code with documentation comments, the compiler may optionally emit an XML file that represents the sum total of the documentation comments in the source. This XML file can then be used by other tools to produce printed or online documentation.\n\nThis chapter describes document comments and recommended XML tags to use with document comments.\n\n## Documentation Comment Format\n\nDocument comments are special comments that begin with `'''`, three single quote marks. They must immediately precede the type (such as a class, delegate, or interface) or type member (such as a field, event, property, or method) that they document. A document comment on a partial method declaration will be replaced by the document comment on the method that supplies its body, if there is one. All adjacent document comments are appended together to produce a single document comment. If there is a whitespace character following the `'''` characters, then that whitespace character is not included in the concatenation. For example:\n\n```vb\n''' <remarks>\n''' Class <c>Point</c> models a point in a two-dimensional plane.\n''' </remarks>\nPublic Class Point \n   ''' <remarks>\n   ''' Method <c>Draw</c> renders the point.\n   ''' </remarks>\n   Sub Draw()\n   End Sub\nEnd Class\n```\n\nDocumentation comments must be well formed XML according to https://www.w3.org/TR/REC-xml. If the XML is not well formed, a warning is generated and the documentation file will contain a comment saying that an error was encountered.\n\nAlthough developers are free to create their own set of tags, a recommended set is defined in the next section. Some of the recommended tags have special meanings:\n\n* The `<param>` tag is used to describe parameters. The parameter specified by a `<param>` tag must exist and all parameters of the type member must be described in the documentation comment. If either condition is not true, the compiler issues a warning.\n\n* The `cref` attribute can be attached to any tag to provide a reference to a code element. The code element must exist; at compile-time the compiler replaces the name with the ID string representing the member. If the code element does not exist, the compiler issues a warning. When looking for a name described in a `cref` attribute, the compiler respects `Imports` statements that appear within the containing source file.\n\n* The `<summary>` tag is intended to be used by a documentation viewer to display additional information about a type or member.\n\nNote that the documentation file does not provide full information about a type and members, only what is contained in the document comments. To get more information about a type or member, the documentation file must be used in conjunction with reflection on the actual type or member.\n\n## Recommended tags\n\nThe documentation generator must accept and process any tag that is valid according to the rules of XML. The following tags provide commonly used functionality in user documentation:\n\n`<c>` Sets text in a code-like font\n\n`<code>` Sets one or more lines of source code or program output in a code-like font\n\n`<example>` Indicates an example\n\n`<exception>` Identifies the exceptions a method can throw\n\n`<include>` Includes an external XML document\n\n`<list>` Creates a list or table\n\n`<para>` Permits structure to be added to text\n\n`<param>` Describes a parameter for a method or constructor\n\n`<paramref>` Identifies that a word is a parameter name\n\n`<permission>` Documents the security accessibility of a member\n\n`<remarks>` Describes a type\n\n`<returns>` Describes the return value of a method\n\n`<see>` Specifies a link\n\n`<seealso>` Generates a See Also entry\n\n`<summary>` Describes a member of a type\n\n`<typeparam>` Describes a type parameter\n\n`<value>` Describes a property\n\n### &lt;c&gt;\n\nThis tag specifies that a fragment of text within a description should use a font like that used for a block of code. (For lines of actual code, use `<code>`.)\n\n__Syntax:__\n\n```xml\n<c>text to be set like code</c>\n```\n\n__Example:__\n\n```vb\n''' <remarks>\n''' Class <c>Point</c> models a point in a two-dimensional plane.\n''' </remarks>\nPublic Class Point \nEnd Class\n```\n\n### &lt;code&gt;\n\nThis tag specifies that one or more lines of source code or program output should use a fixed-width font. (For small code fragments, use `<c>`.)\n\n__Syntax:__\n\n```xml\n<code>source code or program output</code>\n```\n\n__Example:__\n\n```vb\n''' <summary>\n''' This method changes the point's location by the given x- and \n''' y-offsets.\n''' <example>\n''' For example:\n''' <code>\n'''    Dim p As Point = New Point(3,5)\n'''    p.Translate(-1,3)\n''' </code>\n''' results in <c>p</c>'s having the value (2,8).\n''' </example>\n''' </summary>\nPublic Sub Translate(x As Integer, y As Integer)\n    Me.x += x\n    Me.y += y\nEnd Sub\n```\n\n### &lt;example&gt;\n\nThis tag allows example code within a comment to show how an element can be used. Ordinarily, this will involve use of the tag `<code>` as well.\n\n__Syntax:__\n\n```xml\n<example>description</example>\n```\n\n__Example:__\n\nSee `<code>` for an example.\n\n### &lt;exception&gt;\n\nThis tag provides a way to document the exceptions a method can throw.\n\n__Syntax:__\n\n```xml\n<exception cref=\"member\">description</exception>\n```\n\n__Example:__\n\n```vb\nPublic Module DataBaseOperations\n    ''' <exception cref=\"MasterFileFormatCorruptException\"></exception>\n    ''' <exception cref=\"MasterFileLockedOpenException\"></exception>\n    Public Sub ReadRecord(flag As Integer)\n        If Flag = 1 Then\n            Throw New MasterFileFormatCorruptException()\n        ElseIf Flag = 2 Then\n            Throw New MasterFileLockedOpenException()\n        End If\n        ' ...\n    End Sub\nEnd Module\n```\n\n### &lt;include&gt;\n\nThis tag is used to include information from an external well-formed XML document. An XPath expression is applied to the XML document to specify what XML should be included from the document. The `<include>` tag is then replaced with the selected XML from the external document.\n\n__Syntax:__\n\n```xml\n<include file=\"filename\" path=\"xpath\">\n```\n\n__Example:__\n\nIf the source code contained a declaration like the following:\n\n```vb\n''' <include file=\"docs.xml\" path=\"extra/class[@name=\"IntList\"]/*\" />\n```\n\nand the external file docs.xml had the following contents\n\n```xml\n<?xml version=\"1.0\"?>\n<extra>\n    <class name=\"IntList\">\n        <summary>\n            Contains a list of integers.\n        </summary>\n    </class>\n    <class name=\"StringList\">\n        <summary>\n            Contains a list of strings.\n        </summary>\n    </class>\n</extra>\n```\n\nthen the same documentation is output as if the source code contained:\n\n```xml\n''' <summary>\n''' Contains a list of integers.\n''' </summary>\n```\n\n### &lt;list&gt;\n\nThis tag is used to create a list or table of items. It may contain a `<listheader>` block to define the heading row of either a table or definition list. (When defining a table, only an entry for term in the heading need be supplied.)\n\nEach item in the list is specified with an `<item>` block. When creating a definition list, both term and description must be specified. However, for a table, bulleted list, or numbered list, only description need be specified.\n\n__Syntax:__\n\n```xml\n<list type=\"bullet\" | \"number\" | \"table\">\n    <listheader>\n        <term>term</term>\n        <description>description</description>\n    </listheader>\n    <item>\n        <term>term</term>\n        <description>description</description>\n    </item>\n    ...\n    <item>\n        <term>term</term>\n        <description>description</description>\n    </item>\n</list>\n```\n\n__Example:__\n\n```vb\nPublic Class TestClass\n    ''' <remarks>\n    ''' Here is an example of a bulleted list:\n    ''' <list type=\"bullet\">\n    '''     <item>\n    '''        <description>Item 1.</description>\n    '''     </item>\n    '''     <item>\n    '''         <description>Item 2.</description>\n    '''     </item>\n    ''' </list>\n    ''' </remarks>\n    Public Shared Sub Main()\n    End Sub\nEnd Class\n```\n\n### &lt;para&gt;\n\nThis tag is for use inside other tags, such as `<remarks>` or `<returns>`, and permits structure to be added to text.\n\n__Syntax:__\n\n```xml\n<para>content</para>\n```\n\n__Example:__\n\n```vb\n''' <summary>\n''' This is the entry point of the Point class testing program.\n''' <para>This program tests each method and operator, and\n''' is intended to be run after any non-trvial maintenance has\n''' been performed on the Point class.</para>\n''' </summary>\nPublic Shared Sub Main()\nEnd Sub\n```\n\n### &lt;param&gt;\n\nThis tag describes a parameter for a method, constructor, or indexed property.\n\n__Syntax:__\n\n```xml\n<param name=\"name\">description</param>\n```\n\n__Example:__\n\n```vb\n''' <summary>\n''' This method changes the point's location to the given\n''' coordinates.\n''' </summary>\n''' <param name=\"x\"><c>x</c> is the new x-coordinate.</param>\n''' <param name=\"y\"><c>y</c> is the new y-coordinate.</param>\nPublic Sub Move(x As Integer, y As Integer)\n    Me.x = x\n    Me.y = y\nEnd Sub\n```\n\n### &lt;paramref&gt;\n\nThis tag indicates that a word is a parameter. The documentation file can be processed to format this parameter in some distinct way.\n\n__Syntax:__\n\n```xml\n<paramref name=\"name\"/>\n```\n\n__Example:__\n\n```vb\n''' <summary>\n''' This constructor initializes the new Point to\n''' (<paramref name=\"x\"/>,<paramref name=\"y\"/>).\n''' </summary>\n''' <param name=\"x\"><c>x</c> is the new Point's x-coordinate.</param>\n''' <param name=\"y\"><c>y</c> is the new Point's y-coordinate.</param>\nPublic Sub New(x As Integer, y As Integer)\n    Me.x = x\n    Me.y = y\nEnd Sub\n```\n\n### &lt;permission&gt;\n\nThis tag documents the security accessibility of a member\n\n__Syntax:__\n\n```xml\n<permission cref=\"member\">description</permission>\n```\n\n__Example:__\n\n```vb\n''' <permission cref=\"System.Security.PermissionSet\">Everyone can\n''' access this method.</permission>\nPublic Shared Sub Test()\nEnd Sub\n```\n\n### &lt;remarks&gt;\n\nThis tag specifies overview information about a type. (Use `<summary>` to describe the members of a type.)\n\n__Syntax:__\n\n```xml\n<remarks>description</remarks>\n```\n\n__Example:__\n\n```vb\n''' <remarks>\n''' Class <c>Point</c> models a point in a two-dimensional plane.\n''' </remarks>\nPublic Class Point \nEnd Class\n```\n\n### &lt;returns&gt;\n\nThis tag describes the return value of a method.\n\n__Syntax:__\n\n```xml\n<returns>description</returns>\n```\n\n__Example:__\n\n```vb\n''' <summary>\n''' Report a point's location as a string.\n''' </summary>\n''' <returns>\n''' A string representing a point's location, in the form (x,y), without\n''' any leading, training, or embedded whitespace.\n''' </returns>\nPublic Overrides Function ToString() As String\n    Return \"(\" & x & \",\" & y & \")\"\nEnd Sub\n```\n\n### &lt;see&gt;\n\nThis tag allows a link to be specified within text. (Use `<seealso>` to indicate text that is to appear in a See Also section.)\n\n__Syntax:__\n\n```xml\n<see cref=\"member\"/>\n```\n\n__Example:__\n\n```vb\n''' <summary>\n''' This method changes the point's location to the given\n''' coordinates.\n''' </summary>\n''' <see cref=\"Translate\"/>\nPublic Sub Move(x As Integer, y As Integer)\n    Me.x = x\n    Me.y = y\nEnd Sub\n\n''' <summary>\n''' This method changes the point's location by the given x- and\n''' y-offsets.\n''' </summary>\n''' <see cref=\"Move\"/>\nPublic Sub Translate(x As Integer, y As Integer)\n    Me.x += x\n    Me.y += y\nEnd Sub\n```\n\n### &lt;seealso&gt;\n\nThis tag generates an entry for the See Also section. (Use `<see>` to specify a link from within text.)\n\n__Syntax:__\n\n```xml\n<seealso cref=\"member\"/>\n```\n\n__Example:__\n\n```vb\n''' <summary>\n''' This method determines whether two Points have the same location.\n''' </summary>\n''' <seealso cref=\"operator==\"/>\n''' <seealso cref=\"operator!=\"/>\nPublic Overrides Function Equals(o As Object) As Boolean\n    ' ...\nEnd Function\n```\n\n### &lt;summary&gt;\n\nThis tag describes a type member. (Use `<remarks>` to describe a type itself.)\n\n__Syntax:__\n\n```xml\n<summary>description</summary>\n```\n\n__Example:__\n\n```vb\n''' <summary>\n''' This constructor initializes the new Point to (0,0).\n''' </summary>\nPublic Sub New()\n    Me.New(0,0)\nEnd Sub\n```\n\n### &lt;typeparam&gt;\n\nThis tag describes a type parameter.\n\n__Syntax:__\n\n```xml\n<typeparam name=\"name\">description</typeparam>\n```\n\n__Example:__\n\n```vb\n''' <typeparam name=\"T\">\n''' The base item type. Must implement IComparable.\n''' </typeparam>\nPublic Class ItemManager(Of T As IComparable)\nEnd Class\n```\n\n### &lt;value&gt;\n\nThis tag describes a property.\n\n__Syntax:__\n\n```xml\n<value>property description</value>\n```\n\n__Example:__\n\n```vb\n''' <value>\n''' Property <c>X</c> represents the point's x-coordinate.\n''' </value>\nPublic Property X() As Integer\n    Get\n        Return _x\n    End Get\n    Set (Value As Integer)\n        _x = Value\n    End Set\nEnd Property\n```\n\n## ID Strings\n\nWhen generating the documentation file, the compiler generates an ID string for each element in the source code that is tagged with a documentation comment that uniquely identifies it. This ID string can be used by external tools to identify which element in a compiled assembly corresponds to the document comment.\n\nID strings are generated as follows:\n\nNo white space is placed in the string.\n\nThe first part of the string identifies the kind of member being documented, via a single character followed by a colon. The following kinds of members are defined, with the corresponding character in parenthesis after it: events (E), fields (F), methods including constructors and operators (M), namespaces (N), properties (P) and types (T). An exclamation point (!) indicates an error occurred while generating the ID string, and the rest of the string provides information about the error.\n\nThe second part of the string is the fully qualified name of the element, starting at the global namespace. The name of the element, its enclosing type(s), and namespace are separated by periods. If the name of the item itself has periods, they are replaced by the pound sign (#). (It is assumed that no element has this character in its name.) The name of a type with type parameters ends with a backquote (`) followed by a number that represents the number of type parameters on the type. It is important to remember that because nested types have access to the type parameters of the types containing them, nested types implicitly contain the type parameters of their containing types, and those types are counted in their type parameter totals in this case.\n\nFor methods and properties with arguments, the argument list follows, enclosed in parentheses. For those without arguments, the parentheses are omitted. The arguments are separated by commas. The encoding of each argument is the same as a CLI signature, as follows: Arguments are represented by their fully qualified name. For example, `Integer` becomes `System.Int32`, `String` becomes `System.String`, `Object` becomes `System.Object`, and so on. Arguments having the `ByRef` modifier have a '@' following their type name. Arguments having the `ByVal`, `Optional` or `ParamArray` modifier have no special notation. Arguments that are arrays are represented as `[lowerbound:size, ..., lowerbound:size]` where the number of commas is the rank - 1, and the lower bounds and size of each dimension, if known, are represented in decimal. If a lower bound or size is not specified, it is omitted. If the lower bound and size for a particular dimension are omitted, the ':' is omitted as well. Arrays of arrays are represented by one \"`[]`\" per level.\n\n### ID string examples\n\nThe following examples each show a fragment of VB code, along with the ID string produced from each source element capable of having a documentation comment:\n\nTypes are represented using their fully qualified name.\n\n```vb\nEnum Color\n    Red\n    Blue\n    Green\nEnd Enum\n\nNamespace Acme\n    Interface IProcess\n    End Interface\n\n    Structure ValueType\n        ...\n    End Structure\n\n    Class Widget\n        Public Class NestedClass\n        End Class\n\n        Public Interface IMenuItem\n        End Interface\n\n        Public Delegate Sub Del(i As Integer)\n\n        Public Enum Direction\n            North\n            South\n            East\n            West\n        End Enum\n    End Class\nEnd Namespace\n\n\"T:Color\"\n\"T:Acme.IProcess\"\n\"T:Acme.ValueType\"\n\"T:Acme.Widget\"\n\"T:Acme.Widget.NestedClass\"\n\"T:Acme.Widget.IMenuItem\"\n\"T:Acme.Widget.Del\"\n\"T:Acme.Widget.Direction\"\n```\n\nFields are represented by their fully qualified name.\n\n```vb\nNamespace Acme\n    Structure ValueType\n        Private total As Integer\n    End Structure\n\n    Class Widget\n        Public Class NestedClass\n            Private value As Integer\n        End Class\n\n        Private message As String\n        Private Shared defaultColor As Color\n        Private Const PI As Double = 3.14159\n        Protected ReadOnly monthlyAverage As Double\n        Private array1() As Long\n        Private array2(,) As Widget\n    End Class\nEnd Namespace\n\n\"F:Acme.ValueType.total\"\n\"F:Acme.Widget.NestedClass.value\"\n\"F:Acme.Widget.message\"\n\"F:Acme.Widget.defaultColor\"\n\"F:Acme.Widget.PI\"\n\"F:Acme.Widget.monthlyAverage\"\n\"F:Acme.Widget.array1\"\n\"F:Acme.Widget.array2\"\n```\n\nConstructors.\n\n```vb\nNamespace Acme\n    Class Widget\n        Shared Sub New()\n        End Sub\n\n        Public Sub New()\n        End Sub\n\n        Public Sub New(s As String)\n        End Sub\n    End Class\nEnd Namespace\n\n\"M:Acme.Widget.#cctor\"\n\"M:Acme.Widget.#ctor\"\n\"M:Acme.Widget.#ctor(System.String)\"\n```\n\nMethods.\n\n```vb\nNamespace Acme\n    Structure ValueType\n        Public Sub M(i As Integer)\n        End Sub\n    End Structure\n\n    Class Widget\n        Public Class NestedClass\n            Public Sub M(i As Integer)\n            End Sub\n        End Class\n\n        Public Shared Sub M0()\n        End Sub\n\n        Public Sub M1(c As Char, ByRef f As Float, _\n            ByRef v As ValueType)\n        End Sub\n\n        Public Sub M2(x1() As Short, x2(,) As Integer, _\n            x3()() As Long)\n        End Sub\n\n        Public Sub M3(x3()() As Long, x4()(,,) As Widget)\n        End Sub\n\n        Public Sub M4(Optional i As Integer = 1)\n\n        Public Sub M5(ParamArray args() As Object)\n        End Sub\n    End Class\nEnd Namespace\n\n\"M:Acme.ValueType.M(System.Int32)\"\n\"M:Acme.Widget.NestedClass.M(System.Int32)\"\n\"M:Acme.Widget.M0\"\n\"M:Acme.Widget.M1(System.Char,System.Single@,Acme.ValueType@)\"\n\"M:Acme.Widget.M2(System.Int16[],System.Int32[0:,0:],System.Int64[][])\"\n\"M:Acme.Widget.M3(System.Int64[][],Acme.Widget[0:,0:,0:][])\"\n\"M:Acme.Widget.M4(System.Int32)\"\n\"M:Acme.Widget.M5(System.Object[])\"\n```\n\nProperties.\n\n```vb\nNamespace Acme\n    Class Widget\n        Public Property Width() As Integer\n            Get\n            End Get\n            Set (Value As Integer)\n            End Set\n        End Property\n\n        Public Default Property Item(i As Integer) As Integer\n            Get\n            End Get\n            Set (Value As Integer)\n            End Set\n        End Property\n\n        Public Default Property Item(s As String, _\n            i As Integer) As Integer\n            Get\n            End Get\n            Set (Value As Integer)\n            End Set\n        End Property\n    End Class\nEnd Namespace\n\n\"P:Acme.Widget.Width\"\n\"P:Acme.Widget.Item(System.Int32)\"\n\"P:Acme.Widget.Item(System.String,System.Int32)\"\n```\n\nEvents   \n\n```vb\nNamespace Acme\n    Class Widget\n        Public Event AnEvent As EventHandler\n        Public Event AnotherEvent()\n    End Class\nEnd Namespace\n\n\"E:Acme.Widget.AnEvent\"\n\"E:Acme.Widget.AnotherEvent\"\n```\n\nOperators.\n\n```vb\nNamespace Acme\n    Class Widget\n        Public Shared Operator +(x As Widget) As Widget\n        End Operator\n\n        Public Shared Operator +(x1 As Widget, x2 As Widget) As Widget\n        End Operator\n    End Class\nEnd Namespace\n\n\"M:Acme.Widget.op_UnaryPlus(Acme.Widget)\"\n\"M:Acme.Widget.op_Addition(Acme.Widget,Acme.Widget)\"\n```\n\nConversion operators have a trailing `~` followed by the return type.\n\n```vb\nNamespace Acme\n    Class Widget\n        Public Shared Narrowing Operator CType(x As Widget) As _\n            Integer\n        End Operator\n\n        Public Shared Widening Operator CType(x As Widget) As Long\n        End Operator\n    End Class\nEnd Namespace\n\n\"M:Acme.Widget.op_Explicit(Acme.Widget)~System.Int32\"\n\"M:Acme.Widget.op_Implicit(Acme.Widget)~System.Int64\"\n```\n\n## Documentation comments example\n\nThe following example shows the source code of a `Point` class:\n\n```vb\nNamespace Graphics\n    ''' <remarks>\n    ''' Class <c>Point</c> models a point in a two-dimensional\n    ''' plane.\n    ''' </remarks>\n    Public Class Point\n        ''' <summary>\n        ''' Instance variable <c>x</c> represents the point's x-coordinate.\n        ''' </summary>\n        Private _x As Integer\n\n        ''' <summary>\n        ''' Instance variable <c>y</c> represents the point's y-coordinate.\n        ''' </summary>\n        Private _y As Integer\n\n        ''' <value>\n        ''' Property <c>X</c> represents the point's x-coordinate.\n        ''' </value>\n        Public Property X() As Integer\n            Get\n                Return _x\n            End Get\n            Set(Value As Integer)\n                _x = Value\n            End Set\n        End Property\n\n        ''' <value>\n        ''' Property <c>Y</c> represents the point's y-coordinate.\n        ''' </value>\n        Public Property Y() As Integer\n            Get\n                Return _y\n            End Get\n            Set(Value As Integer)\n                _y = Value\n            End Set\n        End Property\n\n        ''' <summary>\n        ''' This constructor initializes the new Point to (0,0).\n        ''' </summary>\n        Public Sub New()\n            Me.New(0, 0)\n        End Sub\n\n        ''' <summary>\n        ''' This constructor initializes the new Point to\n        ''' (<paramref name=\"x\"/>,<paramref name=\"y\"/>).\n        ''' </summary>\n        ''' <param name=\"x\"><c>x</c> is the new Point's\n        ''' x-coordinate.</param>\n        ''' <param name=\"y\"><c>y</c> is the new Point's\n        ''' y-coordinate.</param>\n        Public Sub New(x As Integer, y As Integer)\n            Me.X = x\n            Me.Y = y\n        End Sub\n\n        ''' <summary>\n        ''' This method changes the point's location to the given\n        ''' coordinates.\n        ''' </summary>\n        ''' <param name=\"x\"><c>x</c> is the new x-coordinate.</param>\n        ''' <param name=\"y\"><c>y</c> is the new y-coordinate.</param>\n        ''' <see cref=\"Translate\"/>\n        Public Sub Move(x As Integer, y As Integer)\n            Me.X = x\n            Me.Y = y\n        End Sub\n\n        ''' <summary>\n        ''' This method changes the point's location by the given x- and\n        ''' y-offsets.\n        ''' <example>\n        ''' For example:\n        ''' <code>\n        '''    Dim p As Point = New Point(3, 5)\n        '''    p.Translate(-1, 3)\n        ''' </code>\n        ''' results in <c>p</c>'s having the value (2,8).\n        ''' </example>\n        ''' </summary>\n        ''' <param name=\"x\"><c>x</c> is the relative x-offset.</param>\n        ''' <param name=\"y\"><c>y</c> is the relative y-offset.</param>\n        ''' <see cref=\"Move\"/>\n        Public Sub Translate(x As Integer, y As Integer)\n            Me.X += x\n            Me.Y += y\n        End Sub\n\n        ''' <summary>\n        ''' This method determines whether two Points have the same\n        ''' location.\n        ''' </summary>\n        ''' <param name=\"o\"><c>o</c> is the object to be compared to the\n        ''' current object.</param>\n        ''' <returns>\n        ''' True if the Points have the same location and they have the\n        ''' exact same type; otherwise, false.\n        ''' </returns>\n        ''' <seealso cref=\"Operator op_Equality\"/>\n        ''' <seealso cref=\"Operator op_Inequality\"/>\n        Public Overrides Function Equals(o As Object) As Boolean\n            If o Is Nothing Then\n                Return False\n            End If\n            If o Is Me Then\n                Return True\n            End If\n            If Me.GetType() Is o.GetType() Then\n                Dim p As Point = CType(o, Point)\n                Return (X = p.X) AndAlso (Y = p.Y)\n            End If\n            Return False\n        End Function\n\n        ''' <summary>\n        ''' Report a point's location as a string.\n        ''' </summary>\n        ''' <returns>\n        ''' A string representing a point's location, in the form\n        ''' (x,y), without any leading, training, or embedded whitespace.\n        ''' </returns>\n        Public Overrides Function ToString() As String\n            Return \"(\" & X & \",\" & Y & \")\"\n        End Function\n\n        ''' <summary>\n        ''' This operator determines whether two Points have the\n        ''' same location.\n        ''' </summary>\n        ''' <param name=\"p1\"><c>p1</c> is the first Point to be compared.\n        ''' </param>\n        ''' <param name=\"p2\"><c>p2</c> is the second Point to be compared.\n        ''' </param>\n        ''' <returns>\n        ''' True if the Points have the same location and they \n        ''' have the exact same type; otherwise, false.\n        ''' </returns>\n        ''' <seealso cref=\"Equals\"/>\n        ''' <seealso cref=\"op_Inequality\"/>\n        Public Shared Operator =(p1 As Point, p2 As Point) As Boolean\n            If p1 Is Nothing OrElse p2 Is Nothing Then\n                Return False\n            End If\n            If p1.GetType() Is p2.GetType() Then\n                Return (p1.X = p2.X) AndAlso (p1.Y = p2.Y)\n            End If\n            Return False\n        End Operator\n\n        ''' <summary>\n        ''' This operator determines whether two Points have the\n        ''' same location.\n        ''' </summary>\n        ''' <param name=\"p1\"><c>p1</c> is the first Point to be comapred.\n        ''' </param>\n        ''' <param name=\"p2\"><c>p2</c> is the second Point to be compared.\n        ''' </param>\n        ''' <returns>\n        ''' True if the Points do not have the same location and\n        ''' the exact same type; otherwise, false.\n        ''' </returns>\n        ''' <seealso cref=\"Equals\"/>\n        ''' <seealso cref=\"op_Equality\"/>\n        Public Shared Operator <>(p1 As Point, p2 As Point) As Boolean\n            Return Not p1 = p2\n        End Operator\n\n        ''' <summary>\n        ''' This is the entry point of the Point class testing program.\n        ''' <para>This program tests each method and operator, and\n        ''' is intended to be run after any non-trvial maintenance has\n        ''' been performed on the Point class.</para>\n        ''' </summary>\n        Public Shared Sub Main()\n            ' class test code goes here\n        End Sub\n    End Class\nEnd Namespace\n```\n\nHere is the output produced when given the source code for class `Point`, shown above:\n\n```xml\n<?xml version=\"1.0\"?>\n<doc>\n    <assembly>\n        <name>Point</name>\n    </assembly>\n    <members>\n        <member name=\"T:Graphics.Point\">\n            <remarks>Class <c>Point</c> models a point in a\n            two-dimensional plane. </remarks>\n        </member>\n        <member name=\"F:Graphics.Point.x\">\n            <summary>Instance variable <c>x</c> represents the point's\n            x-coordinate.</summary>\n        </member>\n        <member name=\"F:Graphics.Point.y\">\n            <summary>Instance variable <c>y</c> represents the point's\n            y-coordinate.</summary>\n        </member>\n        <member name=\"M:Graphics.Point.#ctor\">\n            <summary>This constructor initializes the new Point to\n            (0,0).</summary>\n        </member>\n        <member name=\"M:Graphics.Point.#ctor(System.Int32,System.Int32)\">\n            <summary>This constructor initializes the new Point to\n            (<paramref name=\"x\"/>,<paramref name=\"y\"/>).</summary>\n            <param><c>x</c> is the new Point's x-coordinate.</param>\n            <param><c>y</c> is the new Point's y-coordinate.</param>\n        </member>\n        <member name=\"M:Graphics.Point.Move(System.Int32,System.Int32)\">\n            <summary>This method changes the point's location to\n            the given coordinates.</summary>\n            <param><c>x</c> is the new x-coordinate.</param>\n            <param><c>y</c> is the new y-coordinate.</param>\n            <see cref=\n            \"M:Graphics.Point.Translate(System.Int32,System.Int32)\"/>\n        </member>\n        <member name=\n        \"M:Graphics.Point.Translate(System.Int32,System.Int32)\">\n            <summary>This method changes the point's location by the given\n            x- and y-offsets.\n            <example>For example:\n            <code>\n            Point p = new Point(3,5);\n            p.Translate(-1,3);\n            </code>\n            results in <c>p</c>'s having the value (2,8).\n            </example>\n            </summary>\n            <param><c>x</c> is the relative x-offset.</param>\n            <param><c>y</c> is the relative y-offset.</param>\n            <see cref=\"M:Graphics.Point.Move(System.Int32,System.Int32)\"/>\n        </member>\n        <member name=\"M:Graphics.Point.Equals(System.Object)\">\n            <summary>This method determines whether two Points have the\n            same location.</summary>\n            <param><c>o</c> is the object to be compared to the current\n            object.</param>\n            <returns>True if the Points have the same location and they\n            have the exact same type; otherwise, false.</returns>\n            <seealso cref=\n            \"M:Graphics.Point.op_Equality(Graphics.Point,Graphics.Point)\"\n            />\n            <seealso cref=\n           \"M:Graphics.Point.op_Inequality(Graphics.Point,Graphics.Point)\"\n            />\n        </member>\n        <member name=\"M:Graphics.Point.ToString\">\n            <summary>Report a point's location as a string.</summary>\n            <returns>A string representing a point's location, in the form\n            (x,y), without any leading, training, or embedded\n            whitespace.</returns>\n        </member>\n        <member name=\n        \"M:Graphics.Point.op_Equality(Graphics.Point,Graphics.Point)\">\n            <summary>This operator determines whether two Points have the\n            same location.</summary>\n            <param><c>p1</c> is the first Point to be compared.</param>\n            <param><c>p2</c> is the second Point to be compared.</param>\n            <returns>True if the Points have the same location and they\n            have the exact same type; otherwise, false.</returns>\n            <seealso cref=\"M:Graphics.Point.Equals(System.Object)\"/>\n            <seealso cref=\n           \"M:Graphics.Point.op_Inequality(Graphics.Point,Graphics.Point)\"\n            />\n        </member>\n        <member name=\n        \"M:Graphics.Point.op_Inequality(Graphics.Point,Graphics.Point)\">\n            <summary>This operator determines whether two Points have the\n            same location.</summary>\n            <param><c>p1</c> is the first Point to be compared.</param>\n            <param><c>p2</c> is the second Point to be compared.</param>\n            <returns>True if the Points do not have the same location and\n            the exact same type; otherwise, false.</returns>\n            <seealso cref=\"M:Graphics.Point.Equals(System.Object)\"/>\n            <seealso cref=\n            \"M:Graphics.Point.op_Equality(Graphics.Point,Graphics.Point)\"\n            />\n        </member>\n        <member name=\"M:Graphics.Point.Main\">\n            <summary>This is the entry point of the Point class testing\n            program.\n            <para>This program tests each method and operator, and\n            is intended to be run after any non-trvial maintenance has\n            been performed on the Point class.</para>\n            </summary>\n        </member>\n        <member name=\"P:Graphics.Point.X\">\n            <value>Property <c>X</c> represents the point's\n            x-coordinate.</value>\n        </member>\n        <member name=\"P:Graphics.Point.Y\">\n            <value>Property <c>Y</c> represents the point's\n            y-coordinate.</value>\n        </member>\n    </members>\n</doc>\n```\n"
  },
  {
    "path": "spec/expressions.md",
    "content": "# Expressions in Visual Basic\n\nAn expression is a sequence of operators and operands that specifies a computation of a value, or that designates a variable or constant. This chapter defines the syntax, order of evaluation of operands and operators, and meaning of expressions.\n\n```antlr\nExpression\n    : SimpleExpression\n    | TypeExpression\n    | MemberAccessExpression\n    | DictionaryAccessExpression\n    | InvocationExpression\n    | IndexExpression\n    | NewExpression\n    | CastExpression\n    | OperatorExpression\n    | ConditionalExpression\n    | LambdaExpression\n    | QueryExpression\n    | XMLLiteralExpression\n    | XMLMemberAccessExpression\n    ;\n```\n\n## Expression Classifications\n\nEvery expression is classified as one of the following:\n\n* *A value.* Every value has an associated type.\n\n* *A variable.* Every variable has an associated type, namely the declared type of the variable.\n\n* *A namespace.* An expression with this classification can only appear as the left side of a member access. In any other context, an expression classified as a namespace causes a compile-time error.\n\n* *A type.* An expression with this classification can only appear as the left side of a member access. In any other context, an expression classified as a type causes a compile-time error.\n\n* *A method group,* which is a set of methods overloaded on the same name. A method group may have an associated target expression and an associated type argument list.\n\n* *A method pointer,* which represents the location of a method. A method pointer may have an associated target expression and an associated type argument list.\n\n* *A lambda method,* which is an anonymous method.\n\n* *A property group,* which is a set of properties overloaded on the same name. A property group may have an associated target expression.\n\n* *A property access.* Every property access has an associated type, namely the type of the property. A property access may have an associated target expression.\n\n* *A late-bound access,* which represents a method or property access deferred until run-time. A late-bound access may have an associated target expression and an associated type argument list. The type of a late-bound access is always `Object`.\n\n* *An event access.* Every event access has an associated type, namely the type of the event. An event access may have an associated target expression. An event access may appear as the first argument of the `RaiseEvent`, `AddHandler`, and `RemoveHandler` statements. In any other context, an expression classified as an event access causes a compile-time error.\n\n* *An array literal,* which represents the initial values of an array whose type has not yet been determined.\n\n* *Void.* This occurs when the expression is an invocation of a subroutine, or an await operator expression with no result. An expression classified as void is only valid in the context of an invocation statement or an await statement.\n\n* *A default value.* Only the literal `Nothing` produces this classification.\n\nThe final result of an expression is usually a value or a variable, with the other categories of expressions functioning as intermediate values that are only permitted in certain contexts.\n\nNote that expressions whose type is a type parameter can be used in statements and expressions that require the type of an expression to have certain characteristics (such as being a reference type, value type, deriving from some type, etc.) if the constraints imposed on the type parameter satisfy those characteristics.\n\n### Expression Reclassification\n\nNormally, when an expression is used in a context that requires a classification different from that of the expression, a compile-time error occurs -- for example, attempting to assign a value to a literal. However, in many cases it is possible to change an expression's classification through the process of *reclassification*.\n\nIf reclassification succeeds, then the reclassification is judged as widening or narrowing. Unless otherwise noted, all the reclassifications in this list are widening.\n\nThe following types of expressions can be reclassified:\n\n* A variable can be reclassified as a value. The value stored in the variable is fetched.\n\n* A method group can be reclassified as a value. The method group expression is interpreted as an invocation expression with the associated target expression and type parameter list, and empty parentheses (that is, `f` is interpreted as `f()` and `f(Of Integer)` is interpreted as `f(Of Integer)()`). This reclassification may result in the expression being further reclassified as void.\n\n* A method pointer can be reclassified as a value. This reclassification can only occur in the context of a conversion where the target type is known. The method pointer expression is interpreted as the argument to a delegate instantiation expression of the appropriate type with the associated type argument list. For example:\n    \n    ```vb\n    Delegate Sub D(i As Integer)\n    \n    Module Test\n        Sub F(i As Integer)\n        End Sub\n    \n        Sub Main()\n            Dim del As D\n    \n            ' The next two lines are equivalent.\n            del = AddressOf F\n            del = New D(AddressOf F)\n        End Sub\n    End Module\n    ```\n\n* A lambda method can be reclassified as a value. If the reclassification occurs in the context of a conversion where the target type is known, then one of two reclassifications can occur:\n    \n  1. If the target type is a delegate type, the lambda method is interpreted as the argument to a delegate-construction expression of the appropriate type.\n    \n  2. If the target type is `System.Linq.Expressions.Expression(Of T)`, and `T` is a delegate type, then the lambda method is interpreted as if it was being used in delegate-construction expression for `T` and then converted to an expression tree.\n    \n  An async or iterator lambda method may only be interpreted as the argument to a delegate-construction expression, if the delegate has no ByRef parameters.\n    \n  If conversion from any of the delegate's parameter types to the corresponding lambda parameter types is a narrowing conversion, then the reclassification is judged as narrowing; otherwise it is widening.\n    \n  __Note.__ The exact translation between lambda methods and expression trees may not be fixed between versions of the compiler and is beyond the scope of this specification. For Microsoft Visual Basic 11.0, all lambda expressions may be converted to expression trees subject to the following restrictions: (1) 1.  Only single-line lambda expressions without ByRef parameters may be converted to expression trees. Of the single-line `Sub` lambdas, only invocation statements may be converted to expression trees. (2) Anonymous type expressions cannot be converted to expression trees if an earlier field initializer is used to initialize a subsequent field initializer, e.g. `New With {.a=1, .b=.a}`. (3) Object initializer expressions cannot be converted to expression trees if a member of the current object being initialized is used in one of the field initializers, e.g. `New C1 With {.a=1, .b=.Method1()}`. (4) Multi-dimensional array creation expressions can only be converted to expression trees if they declare their element type explicitly. (5) Late-binding expressions cannot be converted to expression trees. (6) When a variable or field is passed ByRef to an invocation expression but does not have exactly the same type as the ByRef parameter, or when a property is passed ByRef, normal VB semantics are that a copy of the argument is passed ByRef and its final value is then copied back into the variable or field or property. In expression trees, the copy-back does not happen. (7) All these restrictions apply to nested lambda expressions as well.\n    \n  If the target type is not known, then the lambda method is interpreted as the argument to a delegate instantiation expression of an anonymous delegate type with the same signature of the lambda method. If strict semantics are being used and the type of any of the parameters are omitted, a compile-time error occurs; otherwise, `Object` is substituted for any missing parameter type. For example:\n    \n  ```vb\n  Module Test\n      Sub Main()\n          ' Type of x will be equivalent to Func(Of Object, Object, Object)\n          Dim x = Function(a, b) a + b\n  \n          ' Type of y will be equivalent to Action(Of Object, Object)\n          Dim y = Sub(a, b) Console.WriteLine(a + b)\n      End Sub\n  End Module\n  ```\n\n* A property group can be reclassified as a property access. The property group expression is interpreted as an index expression with empty parentheses (that is, `f` is interpreted as `f()`).\n\n* A property access can be reclassified as a value. The property access expression is interpreted as an invocation expression of the `Get` accessor of the property. If the property has no getter, then a compile-time error occurs.\n\n* A late-bound access can be reclassified as a late-bound method or late-bound property access. In a situation where a late-bound access can be reclassified both as a method access and as a property access, reclassification to a property access is preferred.\n\n* A late-bound access can be reclassified as a value.\n\n* An array literal can be reclassified as a value. The type of the value is determined as follows:\n\n  1. If the reclassification occurs in the context of a conversion where the target type is known and the target type is an array type, then the array literal is reclassified as a value of type T(). If the target type is `System.Collections.Generic.IList(Of T)`, `IReadOnlyList(Of T)`, `ICollection(Of T)`, `IReadOnlyCollection(Of T)`, or `IEnumerable(Of T)`, and the array literal has one level of nesting, then the array literal is reclassified as a value of type `T()`.\n\n  2. Otherwise, the array literal is reclassified to a value whose type is an array of rank equal to the level of nesting is used, with element type determined by the dominant type of the elements in the initializer; if no dominant type can be determined, `Object` is used. For example:\n\n     ```vb\n     ' x Is GetType(Double(,,))\n     Dim x = { { { 1, 2.0 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }.GetType()\n        \n     ' y Is GetType(Integer())\n     Dim y = { 1, 2, 3 }.GetType()\n        \n     ' z Is GetType(Object())\n     Dim z = { 1, \"2\" }.GetType()\n        \n     ' Error: Inconsistent nesting\n     Dim a = { { 10 }, { 20, 30 } }.GetType()\n     ```\n\n  __Note.__ There is a slight change in behavior between version 9.0 and version 10.0 of the language. Prior to 10.0, array element initializers did not affect local variable type inference and now they do. So `Dim a() = { 1, 2, 3 }` would have inferred `Object()` as the type of `a` in version 9.0 of the language and `Integer()` in version 10.0.\n\n  The reclassification then reinterprets the array literal as an array-creation expression. So the examples:\n\n  ```vb\n  Dim x As Double = { 1, 2, 3, 4 }\n  Dim y = { \"a\", \"b\" }\n  ```\n\n  are equivalent to:\n\n  ```vb\n  Dim x As Double = New Double() { 1, 2, 3, 4 }\n  Dim y = New String() { \"a\", \"b\" }\n  ```\n\n  The reclassification is judged as narrowing if any conversion from an element expression to the array element type is narrowing; otherwise it is judged as widening.\n\n* The default value `Nothing` can be reclassified as a value. In a context where the target type is known, the result is the default value of the target type. In a context where the target type is not known, the result is a null value of type `Object`.\n\nA namespace expression, type expression, event access expression, or void expression cannot be reclassified. Multiple reclassifications can be done at the same time. For example:\n\n```vb\nModule Test\n    Sub F(i As Integer)\n    End Sub\n\n    ReadOnly Property P() As Integer\n        Get\n        End Get\n    End Sub\n\n    Sub Main()\n        F(P)\n    End Property\nEnd Module\n```\n\nIn this case, the property group expression `P` is first reclassified from a property group to a property access and then reclassified from a property access to a value. The fewest number of reclassifications are performed to reach a valid classification in the context.\n\n## Constant Expressions\n\nA *constant expression* is an expression whose value can be fully evaluated at compile time.\n\n```antlr\nConstantExpression\n    : Expression\n    ;\n```\n\nThe type of a constant expression can be `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, `Long`, `Char`, `Single`, `Double`, `Decimal`, `Date`, `Boolean`, `String`, `Object`, or any enumeration type. The following constructs are permitted in constant expressions:\n\n* Literals (including `Nothing`).\n\n* References to constant type members or constant locals.\n\n* References to members of enumeration types.\n\n* Parenthesized subexpressions.\n\n* Coercion expressions, provided the target type is one of the types listed above. Coercions to and from `String` are an exception to this rule and are only allowed on null values because `String` conversions are always done in the current culture of the execution environment at run time. Note that constant coercion expressions can only ever use intrinsic conversions.\n\n* The `+`, `-` and `Not` unary operators, provided the operand and result is of a type listed above.\n\n* The `+`, `-`, `*`, `^`, `Mod`, `/`, `\\`, `<<`, `>>`, `&`, `And`, `Or`, `Xor`, `AndAlso`, `OrElse`, `=`, `<`, `>`, `<>`, `<=`, and `=>` binary operators, provided each operand and result is of a type listed above.\n\n* The conditional operator If, provided each operand and result is of a type listed above.\n\n* The following run-time functions: `Microsoft.VisualBasic.Strings.ChrW`; `Microsoft.VisualBasic.Strings.Chr` if the constant value is between 0 and 128; `Microsoft.VisualBasic.Strings.AscW` if the constant string is not empty; `Microsoft.VisualBasic.Strings.Asc` if the constant string is not empty.\n\nThe following constructs are *not* permitted in constant expressions:\n\n* Implicit binding through a `With` context.\n\nConstant expressions of an integral type (`ULong`, `Long`, `UInteger`, `Integer`, `UShort`, `Short`, `SByte`, or `Byte`) can be implicitly converted to a narrower integral type, and constant expressions of type `Double` can be implicitly converted to `Single`, provided the value of the constant expression is within the range of the destination type. These narrowing conversions are allowed regardless of whether permissive or strict semantics are being used.\n\n\n## Late-Bound Expressions\n\nWhen the target of a member access expression or index expression is of type `Object`, the processing of the expression may be deferred until run time. Deferring processing this way is called *late binding*. Late binding allows `Object` variables to be used in a *typeless* way, where all resolution of members is based on the actual run-time type of the value in the variable. If strict semantics are specified by the compilation environment or by `Option Strict`, late binding causes a compile-time error. Non-public members are ignored when doing late-binding, including for the purposes of overload resolution. Note that, unlike the early-bound case, invoking or accessing a `Shared` member late-bound will cause the invocation target to be evaluated at run time. If the expression is an invocation expression for a member defined on `System.Object`, late binding will not take place.\n\nIn general, late-bound accesses are resolved at run time by looking up the identifier on the actual run-time type of the expression. If late-bound member lookup fails at run time, a `System.MissingMemberException` exception is thrown. Because late-bound member lookup is done solely off the run-time type of the associated target expression, an object's run-time type is never an interface. Therefore, it is impossible to access interface members in a late-bound member access expression.\n\nThe arguments to a late-bound member access are evaluated in the order they appear in the member access expression: not the order in which parameters are declared in the late-bound member. The following example illustrates this difference:\n\n```vb\nClass C\n    Public Sub f(ByVal x As Integer, ByVal y As Integer)\n    End Sub\nEnd Class\n\nModule Module1\n    Sub Main()\n        Console.Write(\"Early-bound: \")\n        Dim c As C = New C\n        c.f(y:=t(\"y\"), x:=t(\"x\"))\n\n        Console.Write(vbCrLf & \"Late-bound: \")\n        Dim o As Object = New C\n        o.f(y:=t(\"y\"), x:=t(\"x\"))\n    End Sub\n\n    Function t(ByVal s As String) As Integer\n        Console.Write(s)\n        Return 0\n    End Function\nEnd Module\n```\n\nThis code displays:\n\n```console\nEarly-bound: xy\nLate-bound: yx\n```\n\nBecause late-bound overload resolution is done on the run-time type of the arguments, it is possible that an expression might produce different results based on whether it is evaluated at compile time or run time. The following example illustrates this difference:\n\n```vb\nClass Base\nEnd Class\n\nClass Derived\n    Inherits Base\nEnd Class\n\nModule Test\n    Sub F(b As Base)\n        Console.WriteLine(\"F(Base)\")\n    End Sub\n\n    Sub F(d As Derived)\n        Console.WriteLine(\"F(Derived)\")\n    End Sub\n\n    Sub Main()\n        Dim b As Base = New Derived()\n        Dim o As Object = b\n\n        F(b)\n        F(o)\n    End Sub\nEnd Module\n```\n\nThis code displays:\n\n```console\nF(Base)\nF(Derived)\n```\n\n## Simple Expressions\n\nSimple expressions are literals, parenthesized expressions, instance expressions, or simple name expressions.\n\n```antlr\nSimpleExpression\n    : LiteralExpression\n    | ParenthesizedExpression\n    | InstanceExpression\n    | SimpleNameExpression\n    | AddressOfExpression\n    ;\n```\n\n### Literal Expressions\n\nLiteral expressions evaluate to the value represented by the literal. A literal expression is classified as a value, except for the literal `Nothing`, which is classified as a default value.\n\n```antlr\nLiteralExpression\n    : Literal\n    ;\n```\n\n### Parenthesized Expressions\n\nA parenthesized expression consists of an expression enclosed in parentheses. A parenthesized expression is classified as a value, and the enclosed expression must be classified as a value. A parenthesized expression evaluates to the value of the expression within the parentheses.\n\n```antlr\nParenthesizedExpression\n    : OpenParenthesis Expression CloseParenthesis\n    ;\n```\n\n### Instance Expressions\n\nAn *instance expression* is the keyword `Me`. It may only be used within the body of a non-shared method, constructor, or property accessor. It is classified as a value. The keyword `Me` represents the instance of the type containing the method or property accessor being executed. If a constructor explicitly invokes another constructor (Section [Constructors](type-members.md#constructors)), `Me` cannot be used until after that constructor call, because the instance has not yet been constructed.\n\n```antlr\nInstanceExpression\n    : 'Me'\n    ;\n```\n\n### Simple Name Expressions\n\nA *simple name expression* consists of a single identifier followed by an optional type argument list.\n\n```antlr\nSimpleNameExpression\n    : Identifier ( OpenParenthesis 'Of' TypeArgumentList CloseParenthesis )?\n    ;\n```\n\nThe name is resolved and classified by the following \"simple name resolution rules\":\n\n1.  Starting with the immediately enclosing block and continuing with each enclosing outer block (if any), if the identifier matches the name of a local variable, static variable, constant local, method type parameter, or parameter, then the identifier refers to the matching entity.\n\n    If the identifier matches a local variable, static variable, or constant local and a type argument list was provided, a compile-time error occurs. If the identifier matches a method type parameter and a type argument list was provided, no match occurs and resolution continues. If the identifier matches a local variable, the local variable matched is the implicit function or `Get` accessor return local variable, and the expression is part of an invocation expression, invocation statement, or an `AddressOf` expression, then no match occurs and resolution continues.\n\n    The expression is classified as a variable if it is a local variable, static variable, or parameter. The expression is classified as a type if it is a method type parameter. The expression is classified as a value if it is a constant local.\n\n2.  For each nested type containing the expression, starting from the innermost and going to the outermost, if a lookup of the identifier in the type produces a match with an accessible member:\n\n    21. If the matching type member is a type parameter, then the result is classified as a type and is the matching type parameter. If a type argument list was provided, no match occurs and resolution continues.\n    22. Otherwise, if the type is the immediately enclosing type and the lookup identifies a non-shared type member, then the result is the same as a member access of the form `Me.E(Of A)`, where `E` is the identifier and `A` is the type argument list, if any.\n    23. Otherwise, the result is exactly the same as a member access of the form `T.E(Of A)`, where `T` is the type containing the matching member, `E` is the identifier, and `A` is the type argument list, if any. In this case, it is an error for the identifier to refer to a non-shared member.\n\n3.  For each nested namespace, starting from the innermost and going to the outermost namespace, do the following:\n\n    31. If the namespace contains an accessible type with the given name and has the same number of type parameters as was supplied in the type argument list, if any, then the identifier refers to that type and is classified as a type.\n    32. Otherwise, if no type argument list was supplied and the namespace contains a namespace member with the given name, then the identifier refers to that namespace and is classified as a namespace.\n    33. Otherwise, if the namespace contains one or more accessible standard modules, and a member name lookup of the identifier produces an accessible match in exactly one standard module, then the result is exactly the same as a member access of the form `M.E(Of A)`, where `M` is the standard module containing the matching member, `E` is the identifier, and `A` is the type argument list, if any. If the identifier matches accessible type members in more than one standard module, a compile-time error occurs.\n\n4.  If the source file has one or more import aliases, and the identifier matches the name of one of them, then the identifier refers to that namespace or type. If a type argument list is supplied, a compile-time error occurs.\n\n5. If the source file containing the name reference has one or more imports:\n\n    51. If the identifier matches in exactly one import the name of an accessible type with the same number of type parameters as was supplied in the type argument list, if any, or a type member, then the identifier refers to that type or type member. If the identifier matches in more than one import the name of an accessible type with the same number of type parameters as was supplied in the type argument list, if any, or an accessible type member, a compile-time error occurs.\n    52. Otherwise, if no type argument list was supplied and the identifier matches in exactly one import the name of a namespace with accessible types, then the identifier refers to that namespace. If no type argument list was supplied and the identifier matches in more than one import the name of a namespace with accessible types, a compile-time error occurs.\n    53. Otherwise, if the imports contain one or more accessible standard modules, and a member name lookup of the identifier produces an accessible match in exactly one standard module, then the result is exactly the same as a member access of the form `M.E(Of A)`, where `M` is the standard module containing the matching member, `E` is the identifier, and `A` is the type argument list, if any. If the identifier matches accessible type members in more than one standard module, a compile-time error occurs.\n\n6.  If the compilation environment defines one or more import aliases, and the identifier matches the name of one of them, then the identifier refers to that namespace or type. If a type argument list is supplied, a compile-time error occurs.\n\n7. If the compilation environment defines one or more imports:\n\n    71. If the identifier matches in exactly one import the name of an accessible type with the same number of type parameters as was supplied in the type argument list, if any, or a type member, then the identifier refers to that type or type member. If the identifier matches in more than one import the name of an accessible type with the same number of type parameters as was supplied in the type argument list, if any, or a type member, a compile-time error occurs.\n    72. Otherwise, if no type argument list was supplied and the identifier matches in exactly one import the name of a namespace with accessible types, then the identifier refers to that namespace. If no type argument list was supplied and the identifier matches in more than one import the name of a namespace with accessible types, a compile-time error occurs.\n    73. Otherwise, if the imports contain one or more accessible standard modules, and a member name lookup of the identifier produces an accessible match in exactly one standard module, then the result is exactly the same as a member access of the form `M.E(Of A)`, where `M` is the standard module containing the matching member,  `E` is the identifier, and `A` is the type argument list, if any. If the identifier matches accessible type members in more than one standard module, a compile-time error occurs.\n\n8. Otherwise, the name given by the identifier is undefined.\n\nA simple name expression that is undefined is a compile-time error.\n\nNormally, a name can only occur once in a particular namespace. However, because namespaces can be declared across multiple .NET assemblies, it is possible to have a situation where two assemblies define a type with the same fully qualified name. In that case, a type declared in the current set of source files is preferred over a type declared in an external .NET assembly. Otherwise, the name is ambiguous and there is no way to disambiguate the name.\n\n\n### AddressOf Expressions\n\nAn `AddressOf` expression is used to produce a method pointer. The expression consists of the `AddressOf` keyword and an expression that must be classified as a method group or a late-bound access. The method group cannot refer to constructors.\n\nThe result is classified as a method pointer, with the same associated target expression and type argument list (if any) as the method group.\n\n```antlr\nAddressOfExpression\n    : 'AddressOf' Expression\n    ;\n```\n\n## Type Expressions\n\nA *type expression* is a `GetType` expression, a `TypeOf...Is` expression, an `Is` expression, or a `GetXmlNamespace` expression.\n\n```antlr\nTypeExpression\n    : GetTypeExpression\n    | TypeOfIsExpression\n    | IsExpression\n    | GetXmlNamespaceExpression\n    ;\n```\n\n### GetType Expressions\n\nA `GetType` expression consists of the keyword `GetType` and the name of a type.\n\n```antlr\nGetTypeExpression\n    : 'GetType' OpenParenthesis GetTypeTypeName CloseParenthesis\n    ;\n\nGetTypeTypeName\n    : TypeName\n    | QualifiedOpenTypeName\n    ;\n\nQualifiedOpenTypeName\n    : Identifier TypeArityList? (Period IdentifierOrKeyword TypeArityList?)*\n    | 'Global' Period IdentifierOrKeyword TypeArityList?\n      (Period IdentifierOrKeyword TypeArityList?)*\n    ;\n\nTypeArityList\n    : OpenParenthesis 'Of' CommaList? CloseParenthesis\n    ;\n\nCommaList\n    : Comma Comma*\n    ;\n```\n\nA `GetType` expression is classified as a value, and its value is the reflection (`System.Type`) class that represents its *GetTypeTypeName*. If the *GetTypeTypeName* is a type parameter, the expression will return the `System.Type` object that corresponds to the type argument supplied for the type parameter at run-time.\n\nThe *GetTypeTypeName* is special in two ways:\n\n* It is allowed to be `System.Void`, the only place in the language where this type name may be referenced.\n\n* It may be a constructed generic type with the type arguments omitted. This allows the `GetType` expression to return the `System.Type` object that corresponds to the generic type itself.\n\nThe following example demonstrates the `GetType` expression:\n\n```vb\nModule Test\n    Sub Main()\n        Dim t As Type() = { GetType(Integer), GetType(System.Int32), _\n            GetType(String), GetType(Double()) }\n        Dim i As Integer\n\n        For i = 0 To t.Length - 1\n            Console.WriteLine(t(i).Name)\n        Next i\n    End Sub\nEnd Module\n```\n\nThe resulting output is:\n\n```console\nInt32\nInt32\nString\nDouble[]\n```\n\n\n### TypeOf...Is Expressions\n\nA `TypeOf...Is` expression is used to check whether the run-time type of a value is compatible with a given type. The first operand must be classified as a value, cannot be a reclassified lambda method, and must be of a reference type or an unconstrained type parameter type. The second operand must be a type name. The result of the expression is classified as a value and is a `Boolean` value. The expression evaluates to `True` if the run-time type of the operand has an identity, default, reference, array, value type, or type parameter conversion to the type, `False` otherwise. A compile-time error occurs if no conversion exists between the type of the expression and the specific type.\n\n```antlr\nTypeOfIsExpression\n    : 'TypeOf' Expression 'Is' LineTerminator? TypeName\n    ;\n```\n\n### Is Expressions\n\nAn `Is` or `IsNot` expression is used to do a reference equality comparison.\n\n```antlr\nIsExpression\n    : Expression 'Is' LineTerminator? Expression\n    | Expression 'IsNot' LineTerminator? Expression\n    ;\n```\n\nEach expression must be classified as a value and the type of each expression must be a reference type, an unconstrained type parameter type, or a nullable value type. If the type of one expression is an unconstrained type parameter type or nullable value type, however, the other expression must be the literal `Nothing`.\n\nThe result is classified as a value and is typed as `Boolean`. An `Is` operation evaluates to `True` if both values refer to the same instance or both values are `Nothing`, or `False` otherwise. An `IsNot` operation evaluates to `False` if both values refer to the same instance or both values are `Nothing`, or `True` otherwise.\n\n\n### GetXmlNamespace Expressions\n\nA `GetXmlNamespace` expression consists of the keyword `GetXmlNamespace` and the name of an XML namespace declared by the source file or compilation environment.\n\n```antlr\nGetXmlNamespaceExpression\n    : 'GetXmlNamespace' OpenParenthesis XMLNamespaceName? CloseParenthesis\n    ;\n```\n\nAn `GetXmlNamespace` expression is classified as a value, and its value is an instance of `System.Xml.Linq.XNamespace` that represents the *XMLNamespaceName*. If that type is not available, then a compile-time error will occur.\n\nFor example:\n\n```vb\nImports <xmlns:db=\"http://example.org/database\">\n\nModule Test\n    Sub Main()\n        Dim db = GetXmlNamespace(db)\n\n        ' The following are equivalent\n        Dim customer1 = _\n            New System.Xml.Linq.XElement(db + \"customer\", \"Bob\")\n        Dim customer2 = <db:customer>Bob</>\n    End Sub\nEnd Module\n```\n\nEverything between the parentheses is considered part of the namespace name, so XML rules around things such as whitespace apply. For example:\n\n```vb\nImports <xmlns:db-ns=\"http://example.org/database\">\n\nModule Test\n    Sub Main()\n\n        ' Error, XML name expected\n        Dim db1 = GetXmlNamespace( db-ns )\n\n        ' Error, ')' expected\n        Dim db2 = GetXmlNamespace(db _\n            )\n\n        ' OK.\n        Dim db3 = GetXmlNamespace(db-ns)\n    End Sub\nEnd Module\n```\n\nThe XML namespace expression can also be omitted, in which case the expression returns the object that represents the default XML namespace.\n\n\n## Member Access Expressions\n\nA member access expression is used to access a member of an entity.\n\n```antlr\nMemberAccessExpression\n    : MemberAccessBase? Period IdentifierOrKeyword\n      ( OpenParenthesis 'Of' TypeArgumentList CloseParenthesis )?\n    ;\n\nMemberAccessBase\n    : Expression\n    | NonArrayTypeName\n    | 'Global'\n    | 'MyClass'\n    | 'MyBase'\n    ;\n```\n\nA member access of the form `E.I(Of A)`, where `E` is an expression, a non-array type name, the keyword `Global`, or omitted and `I` is an identifier with an optional type argument list `A`, is evaluated and classified as follows:\n\n1. If `E` is omitted, then the expression from the immediately containing `With` statement is substituted for `E` and the member access is performed. If there is no containing `With` statement, a compile-time error occurs.\n\n2. If `E` is classified as a namespace or `E` is the keyword `Global`, then the member lookup is done in the context of the specified namespace. If `I` is the name of an accessible member of that namespace with the same number of type parameters as was supplied in the type argument list, if any, then the result is that member. The result is classified as a namespace or a type depending on the member. Otherwise, a compile-time error occurs.\n\n3. If `E` is a type or an expression classified as a type, then the member lookup is done in the context of the specified type. If `I` is the name of an accessible member of `E`, then `E.I` is evaluated and classified as follows:\n\n    31. If `I` is the keyword `New` and `E` is not an enumeration then a compile-time error occurs.\n    32. If `I` identifies a type with the same number of type parameters as was supplied in the type argument list, if any, then the result is that type.\n    33. If `I` identifies one or more methods, then the result is a method group with the associated type argument list and no associated target expression.\n    34. If `I` identifies one or more properties and no type argument list was supplied, then the result is a property group with no associated target expression.\n    35. If `I` identifies a shared variable and no type argument list was supplied, then the result is either a variable or a value. If the variable is read-only, and the reference occurs outside the shared constructor of the type in which the variable is declared, then the result is the value of the shared variable `I` in `E`. Otherwise, the result is the shared variable `I` in `E`.\n    36. If `I` identifies a shared event and no type argument list was supplied, the result is an event access with no associated target expression.\n    37. If `I` identifies a constant and no type argument list was supplied, then the result is the value of that constant.\n    38. If `I` identifies an enumeration member and no type argument list was supplied, then the result is the value of that enumeration member.\n    39. Otherwise, `E.I` is an invalid member reference, and a compile-time error occurs.\n\n4. If `E` is classified as a variable or value, the type of which is `T`, then the member lookup is done in the context of `T`. If `I` is the name of an accessible member of `T`, then `E.I` is evaluated and classified as follows:\n\n    41. If `I` is the keyword `New`, `E` is  `Me`, `MyBase`, or `MyClass`, and no type arguments were supplied, then the result is a method group representing the instance constructors of the type of `E` with an associated target expression of `E` and no type argument list. Otherwise, a compile-time error occurs.\n    42. If `I` identifies one or more methods, including extension methods if `T` is not `Object`, then the result is a method group with the associated type argument list and an associated target expression of `E`.\n    43. If `I` identifies one or more properties and no type arguments were supplied, then the result is a property group with an associated target expression of `E`.\n    44. If `I` identifies a shared variable or an instance variable and no type arguments were supplied, then the result is either a variable or a value. If the variable is read-only, and the reference occurs outside a constructor of the class in which the variable is declared appropriate for the kind of variable (shared or instance), then the result is the value of the variable `I` in the object referenced by `E`. If `T` is a reference type, then the result is the variable `I` in the object referenced by `E`. Otherwise, if `T` is a value type and the expression `E` is classified as a variable, the result is a variable; otherwise the result is a value.\n    45. If `I` identifies an event and no type arguments were supplied, the result is an event access with an associated target expression of `E`.\n    46. If `I` identifies a constant and no type arguments were supplied, then the result is the value of that constant.\n    47. If `I` identifies an enumeration member and no type arguments were supplied, then the result is the value of that enumeration member.\n    48. If `T` is `Object`, then the result is a late-bound member lookup classified as a late-bound access with the associated type argument list and an associated target expression of `E`.\n\n5. Otherwise, `E.I` is an invalid member reference, and a compile-time error occurs.\n\nA member access of the form `MyClass.I(Of A)` is equivalent to `Me.I(Of A)`, but all members accessed on it are treated as if the members are non-overridable. Thus, the member accessed will not be affected by the run-time type of the value on which the member is being accessed.\n\nA member access of the form `MyBase.I(Of A)` is equivalent to `CType(Me, T).I(Of A)` where `T` is the direct base type of the type containing the member access expression. All method invocations on it are treated as if the method being invoked is non-overridable. This form of member access is also called a *base access*.\n\nThe following example demonstrates how `Me`, `MyBase` and `MyClass` relate:\n\n```vb\nClass Base\n    Public Overridable Sub F()\n        Console.WriteLine(\"Base.F\")\n    End Sub\nEnd Class\n\nClass Derived\n    Inherits Base\n\n    Public Overrides Sub F()\n        Console.WriteLine(\"Derived.F\")\n    End Sub\n\n    Public Sub G()\n        MyClass.F()\n    End Sub\nEnd Class\n\nClass MoreDerived\n    Inherits Derived\n\n    Public Overrides Sub F()\n        Console.WriteLine(\"MoreDerived.F\")\n    End Sub\n\n    Public Sub H()\n        MyBase.F()\n    End Sub\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim x As MoreDerived = new MoreDerived()\n\n        x.F()\n        x.G()\n        x.H()\n    End Sub\n\nEnd Module\n```\n\nThis code prints out:\n\n```console\nMoreDerived.F\nDerived.F\nDerived.F\n```\n\nWhen a member access expression begins with the keyword `Global`, the keyword represents the outermost unnamed namespace, which is useful in situations where a declaration shadows an enclosing namespace. The `Global` keyword allows \"escaping\" out to the outermost namespace in that situation. For example:\n\n```vb\nClass System\nEnd Class\n\nModule Test\n    Sub Main()\n        ' Error: Class System does not contain Console\n        System.Console.WriteLine(\"Hello, world!\") \n\n\n        ' Legal, binds to System in outermost namespace\n        Global.System.Console.WriteLine(\"Hello, world!\") \n    End Sub\nEnd Module\n```\n\nIn the above example, the first method call is invalid because the identifier `System` binds to the class `System`, not the namespace `System`. The only way to access the `System` namespace is to use `Global` to escape out to the outermost namespace.\n\nIf the member being accessed is shared, any expression on the left side of the period is superfluous and is not evaluated unless the member access is done late-bound. For example, consider the following code:\n\n```vb\nClass C\n    Public Shared F As Integer = 10\nEnd Class\n\nModule Test\n    Public Function ReturnC() As C\n        Console.WriteLine(\"Returning a new instance of C.\")\n        Return New C()\n    End Function\n\n    Public Sub Main()\n        Console.WriteLine(\"The value of F is: \" & ReturnC().F)\n    End Sub\nEnd Module\n```\n\nIt prints `The value of F is: 10` because the function `ReturnC` does not need to be called to provide an instance of `C` to access the shared member `F`.\n\n\n### Identical Type and Member Names\n\nIt is not uncommon to name members using the same name as their type. In that situation, however, inconvenient name hiding can occur:\n\n```vb\nEnum Color\n    Red\n    Green\n    Yellow\nEnd Enum\n\nClass Test\n    ReadOnly Property Color() As Color\n        Get\n            Return Color.Red\n        End Get\n    End Property\n\n    Shared Function DefaultColor() As Color\n        Return Color.Green    ' Binds to the instance property!\n    End Function\nEnd Class\n```\n\nIn the previous example, the simple name `Color` in `DefaultColor` binds to the instance property instead of the type. Because an instance member cannot be referenced in a shared member, this would normally be an error.\n\nHowever, a special rule allows access to the type in this case. If the base expression of a member access expression is a simple name and binds to a constant, field, property, local variable or parameter whose type has the same name, then the base expression can refer either to the member or the type. This can never result in ambiguity because the members that can be accessed off of either one are the same.\n\n### Default Instances\n\nIn some situations, classes derived from a common base class usually or always have only a single instance. For example, most windows shown in a user interface only ever have one instance showing on the screen at any time. To simplify working with these types of classes, Visual Basic can automatically generate *default instances* of the classes that provide a single, easily referenced instance for each class.\n\nDefault instances are always created for a *family* of types rather than for one particular type. So instead of creating a default instance for a class Form1 that derives from Form, default instances are created for all classes derived from Form. This means that each individual class that derives from the base class does not have to be specially marked to have a default instance.\n\nThe default instance of a class is represented by a compiler-generated property that returns the default instance of that class. The property generated as a member of a class called the *group class* that manages allocating and destroying default instances for all classes derived from the particular base class. For example, all of the default instance properties of classes derived from `Form` may be collected in the `MyForms` class. If an instance of the group class is returned by the expression `My.Forms`, then the following code accesses the default instances of derived classes `Form1` and `Form2`:\n\n```vb\nClass Form1\n    Inherits Form\n    Public x As Integer\nEnd Class\n\nClass Form2\n    Inherits Form\n    Public y As Integer\nEnd Class\n\nModule Main\n    Sub Main()\n        My.Forms.Form1.x = 10\n        Console.WriteLine(My.Forms.Form2.y)\n    End Sub\nEnd Module\n```\n\nDefault instances will not be created until the first reference to them; fetching the property representing the default instance causes the default instance to be created if it has not already been created or has been set to `Nothing`. To allow testing for the existence of a default instance, when a default instance is the target of an `Is` or `IsNot` operator, the default instance will not be created. Thus, it is possible to test whether a default instance is `Nothing` or some other reference without causing the default instance to be created.\n\nDefault instances are intended to make it easy to refer to the default instance from outside of the class that has the default instance. Using a default instance from within a class that defines it might cause confusion as to which instance is being referred to, i.e. the default instance or the current instance. For example, the following code modifies only the value `x` in the default instance, even though it is being called from another instance. Thus the code would print the value `5` instead of `10`:\n\n```vb\nClass Form1\n    Inherits Form\n\n    Public x As Integer = 5\n\n    Public Sub ChangeX()\n        Form1.x = 10\n    End Sub\nEnd Class\n\nModule Main\n    Sub Main()\n        Dim f As Form1 = New Form1()\n        f.ChangeX()\n        Console.WriteLine(f.x)\n    End Sub\nEnd Module\n```\n\nTo prevent this kind of confusion, it is not valid to refer to a default instance from within an instance method of the default instance's type.\n\n#### Default Instances and Type Names\n\nA default instance may also be accessible directly through its type's name. In this case, in any expression context where the type name is not allowed the expression `E`, where `E` represents the fully qualified name of the class with a default instance, is changed to `E'`, where `E'` represents an expression that fetches the default instance property. For example, if default instances for classes derived from `Form` allow accessing the default instance through the type name, then the following code is equivalent to the code in the previous example:\n\n```vb\nModule Main\n    Sub Main()\n        Form1.x = 10\n        Console.WriteLine(Form2.y)\n    End Sub\nEnd Module\n```\n\nThis also means that a default instance that is accessible through its type's name is also assignable through the type name. For example, the following code sets the default instance of `Form1` to `Nothing`:\n\n```vb\nModule Main\n    Sub Main()\n        Form1 = Nothing\n    End Sub\nEnd Module\n```\n\nNote that the meaning of `E.I` were `E` represents a class and `I` represents a shared member does not change. Such an expression still accesses the shared member directly off of the class instance and does not reference the default instance.\n\n#### Group Classes\n\nThe `Microsoft.VisualBasic.MyGroupCollectionAttribute` attribute indicates the group class for a family of default instances. The attribute has four parameters:\n\n* The parameter `TypeToCollect` specifies the base class for the group. All instantiable classes without open type parameters that derive from a type with this name (regardless of type parameters) will automatically have a default instance.\n\n* The parameter `CreateInstanceMethodName` specifies the method to call in the group class to create a new instance in a default instance property.\n\n* The parameter `DisposeInstanceMethodName` specifies the method to call in the group class to dispose of a default instance property if the default instance property is assigned the value `Nothing`.\n\n* The parameter `DefaultInstanceAlias` specifics the expression `E'` to substitute for the class name if the default instances are accessible directly through their type name. If this parameter is `Nothing` or an empty string, default instances on this group type are not accessible directly through their type's name. (__Note.__ In all current implementations of the Visual Basic language, the `DefaultInstanceAlias` parameter is ignored, except in compiler-provided code.)\n\nMultiple types can be collected into the same group by separating the names of the types and methods in the first three parameters using commas. There must be the same number of items in each parameter, and the list elements are matched in order. For example, the following attribute declaration collects types that derive from `C1`, `C2` or `C3` into a single group:\n\n```vb\n<Microsoft.VisualBasic.MyGroupCollection(\"C1, C2, C3\", _\n    \"CreateC1, CreateC2, CreateC3\", _\n    \"DisposeC1, DisposeC2, DisposeC3\", \"My.Cs\")>\nPublic NotInheritable Class MyCs\n    ...\nEnd Class\n```\n\nThe signature of the create method must be of the form `Shared Function <Name>(Of T As {New, <Type>})(Instance Of T) As T`. The dispose method must be of the form `Shared Sub <Name>(Of T As <Type>)(ByRef Instance Of T)`. Thus, the group class for the example in the preceding section could be declared as follows:\n\n```vb\n<Microsoft.VisualBasic.MyGroupCollection(\"Form\", \"Create\", _\n    \"Dispose\", \"My.Forms\")> _\nPublic NotInheritable Class MyForms\n    Private Shared Function Create(Of T As {New, Form}) _\n        (Instance As T) As T\n        If Instance Is Nothing Then\n            Return New T()\n        Else\n            Return Instance\n        End If\n    End Function\n\n    Private Shared Sub Dispose(Of T As Form)(ByRef Instance As T)\n        Instance.Close()\n        Instance = Nothing\n    End Sub\nEnd Class\n```\n\nIf a source file declared a derived class `Form1`, the generated group class would be equivalent to:\n\n```vb\n<Microsoft.VisualBasic.MyGroupCollection(\"Form\", \"Create\", _\n    \"Dispose\", \"My.Forms\")> _\nPublic NotInheritable Class MyForms\n    Private Shared Function Create(Of T As {New, Form}) _\n        (Instance As T) As T\n        If Instance Is Nothing Then\n            Return New T()\n        Else\n            Return Instance\n        End If\n    End Function\n\n    Private Shared Sub Dispose(Of T As Form)(ByRef Instance As T)\n        Instance.Close()\n        Instance = Nothing\n    End Sub\n\n    Private m_Form1 As Form1\n\n    Public Property Form1() As Form1\n        Get\n            Return Create(m_Form1)\n        End Get\n        Set (Value As Form1)\n            If Value IsNot Nothing AndAlso Value IsNot m_Form1 Then\n                Throw New ArgumentException( _\n                    \"Property can only be set to Nothing.\")\n            End If\n            Dispose(m_Form1)\n        End Set\n    End Property\nEnd Class\n```\n\n### Extension Method Collection\n\nExtension methods for the member access expression `E.I` are collected by gathering all of the extension methods with the name `I` that are available in the current context:\n\n1. First, each nested type containing the expression is checked, starting from the innermost and going to the outermost.\n2. Then, each nested namespace is checked, starting from the innermost and going to the outermost namespace.\n3. Then, the imports in the source file are checked.\n4. Then, the imports defined by the compilation environment are checked.\n\nAn extension method is collected only if there is a widening native conversion from the target expression type to the type of the first parameter of the extension method. And unlike regular simple name expression binding, the search collects *all* extension methods; the collection does not stop when an extension method is found. For example:\n\n```vb\nImports System.Runtime.CompilerServices\n\nClass C1\nEnd Class\n\n\nNamespace N1\n    Module N1C1Extensions\n        <Extension> _\n        Sub M1(c As C1, x As Integer)\n        End Sub\n    End Module\nEnd Namespace\n\nNamespace N1.N2\n    Module N2C1Extensions\n        <Extension> _\n        Sub M1(c As C1, y As Double)\n        End Sub\n    End Module\nEnd Namespace\n\nNamespace N1.N2.N3\n    Module Test\n        Sub Main()\n            Dim x As New C1()\n\n            ' Calls N1C1Extensions.M1\n            x.M1(10)\n        End Sub\n    End Module\nEnd Namespace\n```\n\nIn this example, even though `N2C1Extensions.M1` is found before `N1C1Extensions.M1`, they both are considered as extension methods. Once all of the extension methods have been collected, they are then *curried*. Currying takes the target of the extension method call and applies it to the extension method call, resulting in a new method signature with the first parameter removed (because it has been specified). For example:\n\n```vb\nImports System.Runtime.CompilerServices\n\nModule Ext1\n    <Extension> _\n    Sub M(x As Integer, y As Integer)\n    End Sub\nEnd Module\n\nModule Ext2\n    <Extension> _\n    Sub M(x As Integer, y As Double)\n    End Sub\nEnd Module\n\nModule Main\n    Sub Test()\n        Dim v As Integer = 10\n\n        ' The curried method signatures considered are:\n        '        Ext1.M(y As Integer)\n        '        Ext2.M(y As Double)\n        v.M(10)\n    End Sub\nEnd Module\n```\n\nIn the above example, the curried result of applying `v` to `Ext1.M` is the method signature `Sub M(y As Integer)`.\n\nIn addition to removing the first parameter of the extension method, currying also removes any method type parameters that are a part of the type of the first parameter. When currying an extension method with method type parameter, type inference is applied to the first parameter and the result is fixed for any type parameters that are inferred. If type inference fails, the method is ignored. For example:\n\n```vb\nImports System.Runtime.CompilerServices\n\nModule Ext1\n    <Extension> _\n    Sub M(Of T, U)(x As T, y As U)\n    End Sub\nEnd Module\n\nModule Ext2\n    <Extension> _\n    Sub M(Of T)(x As T, y As T)\n    End Sub\nEnd Module\n\nModule Main\n    Sub Test()\n        Dim v As Integer = 10\n\n        ' The curried method signatures considered are:\n        '        Ext1.M(Of U)(y As U)\n        '        Ext2.M(y As Integer)\n        v.M(10)\n    End Sub\nEnd Module\n```\n\nIn the above example, the curried result of applying `v` to `Ext1.M` is the method signature `Sub M(Of U)(y As U)`, because the type parameter `T` is inferred as a result of the currying and is now fixed. Because the type parameter `U` was not inferred as a part of the currying, it remains an open parameter. Similarly, because the type parameter `T` is inferred as a result of applying `v` to `Ext2.M`, the type of parameter `y` becomes fixed as `Integer`. It will not be inferred to be any other type. When currying the signature, all constraints except for `New` constraints are also applied. If the constraints are not satisfied, or depend on a type that was not inferred as a part of currying, the extension method is ignored. For example:\n\n```vb\nImports System.Runtime.CompilerServices\n\nModule Ext1\n    <Extension> _\n    Sub M1(Of T As Structure)(x As T, y As Integer)\n    End Sub\n\n    <Extension> _\n    Sub M2(Of T As U, U)(x As T, y As U)\n    End Sub\nEnd Module\n\nModule Main\n    Sub Test()\n        Dim s As String = \"abc\"\n\n        ' Error: String does not satisfy the Structure constraint\n        s.M1(10)\n\n        ' Error: T depends on U, which cannot be inferred\n        s.M2(10)\n    End Sub\nEnd Module\n```\n\n__Note.__ One of the main reasons for doing currying of extension methods is that it allows query expressions to infer the type of the iteration before evaluating the arguments to a query pattern method. Since most query pattern methods take lambda expressions, which require type inference themselves, this greatly simplifies the process of evaluating a query expression.\n\nUnlike normal interface inheritance, extension methods that extend two interfaces that do not relate to one another are available, as long as they do not have the same curried signature:\n\n```vb\nImports System.Runtime.CompilerServices\n\nInterface I1\nEnd Interface\n\nInterface I2\nEnd Interface\n\nClass C1\n    Implements I1, I2\nEnd Class\n\nModule I1Ext\n    <Extension> _\n    Sub M1(i As I1, x As Integer)\n    End Sub\n\n    <Extension> _\n    Sub M2(i As I1, x As Integer)\n    End Sub\nEnd Module\n\nModule I2Ext\n    <Extension> _\n    Sub M1(i As I2, x As Integer)\n    End Sub\n\n    <Extension> _\n    Sub M2(I As I2, x As Double)\n    End Sub\nEnd Module\n\nModule Main\n    Sub Test()\n        Dim c As New C1()\n\n        ' Error: M is ambiguous between I1Ext.M1 and I2Ext.M1.\n        c.M1(10)\n\n        ' Calls I1Ext.M2\n        c.M2(10)\n    End Sub\nEnd Module\n```\n\nFinally, it is important to remember that extension methods are not considered when doing late binding:\n\n```vb\nModule Test\n    Sub Main()\n        Dim o As Object = ...\n\n        ' Ignores extension methods\n        o.M1()\n    End Sub\nEnd Module\n```\n\n## Dictionary Member Access Expressions\n\nA *dictionary member access expression* is used to look up a member of a collection. A dictionary member access takes the form of `E!I`, where `E` is an expression that is classified as a value and `I` is an identifier.\n\n```antlr\nDictionaryAccessExpression\n    : Expression? '!' IdentifierOrKeyword\n    ;\n```\n\nThe type of the expression must have a default property indexed by a single `String` parameter. The dictionary member access expression `E!I` is transformed into the expression `E.D(\"I\")`, where `D` is the default property of `E`. For example:\n\n```vb\nClass Keys\n    Public ReadOnly Default Property Item(s As String) As Integer\n        Get\n            Return 10\n        End Get\n    End Property \nEnd Class\n\nModule Test\n    Sub Main()\n        Dim x As Keys = new Keys()\n        Dim y As Integer\n        ' The two statements are equivalent.\n        y = x!abc\n        y = x(\"abc\")\n    End Sub\nEnd Module\n```\n\nIf an exclamation point is specified with no expression, the expression from the immediately containing `With` statement is assumed. If there is no containing `With` statement, a compile-time error occurs.\n\n\n## Invocation Expressions\n\nAn invocation expression consists of an invocation target and an optional argument list.\n\n```antlr\nInvocationExpression\n    : Expression ( OpenParenthesis ArgumentList? CloseParenthesis )?\n    ;\n\nArgumentList\n    : PositionalArgumentList\n    | PositionalArgumentList Comma NamedArgumentList\n    | NamedArgumentList\n    ;\n\nPositionalArgumentList\n    : Expression? ( Comma Expression? )*\n    ;\n\nNamedArgumentList\n    : IdentifierOrKeyword ColonEquals Expression\n      ( Comma IdentifierOrKeyword ColonEquals Expression )*\n    ;\n```\n\nThe target expression must be classified as a method group or a value whose type is a delegate type. If the target expression is a value whose type is a delegate type, then the target of the invocation expression becomes the method group for the `Invoke` member of the delegate type and the target expression becomes the associated target expression of the method group.\n\nAn argument list has two sections: positional arguments and named arguments. *Positional arguments* are expressions and must precede any named arguments. *Named arguments* start with an identifier that can match keywords, followed by `:=` and an expression.\n\nIf the method group only contains one accessible method, including both instance and extension methods, and that method takes no arguments and is a function, then the method group is interpreted as an invocation expression with an empty argument list and the result is used as the target of an invocation expression with the provided argument list(s). For example:\n\n```vb\nClass C1\n    Function M1() As Integer()\n        Return New Integer() { 1, 2, 3 }\n    End Sub\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim c As New C1()\n\n        ' Prints 3\n        Console.WriteLine(c.M1(2))\n    End Sub\nEnd Module\n```\n\nOtherwise, overload resolution is applied to the methods to pick the most applicable method for the given argument list(s). If the most applicable method is a function, then the result of the invocation expression is classified as a value typed as the return type of the function. If the most applicable method is a subroutine, then the result is classified as void. If the most applicable method is a partial method that has no body, then the invocation expression is ignored and the result is classified as void.\n\nFor an early-bound invocation expression, the arguments are evaluated in the order in which the corresponding parameters are declared in the target method. For a late-bound member access expression, they are evaluated in the order in which they appear in the member access expression: see Section [Late-Bound Expressions](expressions.md#late-bound-expressions).\n\n## Overloaded Method Resolution:\nFor Overload Resolution, Specificity of members/types given an argument list, Genericity, Applicability to Argument List, Passing Arguments, and Picking Arguments for Optional Parameters, Conditional Methods, and Type Argument Inference: see Section [Overload Resolution](overload-resolution.md).\n\n## Index Expressions\n\nAn *index expression* results in an array element or reclassifies a property group into a property access. An index expression consists of, in order, an expression, an opening parenthesis, an index argument list, and a closing parenthesis.\n\n```antlr\nIndexExpression\n    : Expression OpenParenthesis ArgumentList? CloseParenthesis\n    ;\n```\n\nThe target of the index expression must be classified as either a property group or a value. An index expression is processed as follows:\n\n* If the target expression is classified as a value and if its type is not an array type, `Object`, or `System.Array`, the type must have a default property. The index is performed on a property group that represents all of the default properties of the type. Although it is not valid to declare a parameterless default property in Visual Basic, other languages may allow declaring such a property. Consequently, indexing a property with no arguments is allowed.\n\n* If the expression results in a value of an array type, the number of arguments in the argument list must be the same as the rank of the array type and may not include named arguments. If any of the indexes are invalid at run time, a `System.IndexOutOfRangeException` exception is thrown. Each expression must be implicitly convertible to type `Integer`. The result of the index expression is the variable at the specified index and is classified as a variable.\n\n* If the expression is classified as a property group, overload resolution is used to determine whether one of the properties is applicable to the index argument list. If the property group only contains one property that has a `Get` accessor and if that accessor takes no arguments, then the property group is interpreted as an index expression with an empty argument list. The result is used as the target of the current index expression. If no properties are applicable, then a compile-time error occurs. Otherwise, the expression results in a property access with the associated target expression (if any) of the property group.\n\n* If the expression is classified as a late-bound property group or as a value whose type is `Object` or `System.Array`, the processing of the index expression is deferred until run time and the indexing is late-bound. The expression results in a late-bound property access typed as `Object`. The associated target expression is either the target expression, if it is a value, or the associated target expression of the property group. At run time the expression is processed as follows:\n\n* If the expression is classified as a late-bound property group, the expression may result in a method group, a property group, or a value (if the member is an instance or shared variable). If the result is a method group or property group, overload resolution is applied to the group to determine the correct method for the argument list. If overload resolution fails, a `System.Reflection.AmbiguousMatchException` exception is thrown. Then the result is processed either as a property access or as an invocation and the result is returned. If the invocation is of a subroutine, the result is `Nothing`.\n\n* If the run-time type of the target expression is an array type or `System.Array`, the result of the index expression is the value of the variable at the specified index.\n\n* Otherwise, the run-time type of the expression must have a default property and the index is performed on the property group that represents all of the default properties on the type. If the type has no default property, then a `System.MissingMemberException` exception is thrown.\n\n\n## New Expressions\n\nThe `New` operator is used to create new instances of types. There are four forms of `New` expressions:\n\n* Object-creation expressions are used to create new instances of class types and value types.\n\n* Array-creation expressions are used to create new instances of array types.\n\n* Delegate-creation expressions (which do not have a distinct syntax from object-creation expressions) are used to create new instances of delegate types.\n\n* Anonymous object-creation expressions are used to create new instances of anonymous class types.\n\n```antlr\nNewExpression\n    : ObjectCreationExpression\n    | ArrayExpression\n    | AnonymousObjectCreationExpression\n    ;\n```\n\nA `New` expression is classified as a value and the result is the new instance of the type.\n\n\n### Object-Creation Expressions\n\nAn object-creation expression is used to create a new instance of a class type or a structure type.\n\n```antlr\nObjectCreationExpression\n    : 'New' NonArrayTypeName ( OpenParenthesis ArgumentList? CloseParenthesis )?\n      ObjectCreationExpressionInitializer?\n    ;\n\nObjectCreationExpressionInitializer\n    : ObjectMemberInitializer\n    | ObjectCollectionInitializer\n    ;\n\nObjectMemberInitializer\n    : 'With' OpenCurlyBrace FieldInitializerList CloseCurlyBrace\n    ;\n\nFieldInitializerList\n    : FieldInitializer ( Comma FieldInitializer )*\n    ;\n\nFieldInitializer\n    : 'Key'? ('.' IdentifierOrKeyword Equals )? Expression\n    ;\n\nObjectCollectionInitializer\n    : 'From' CollectionInitializer\n    ;\n\nCollectionInitializer\n    : OpenCurlyBrace CollectionElementList? CloseCurlyBrace\n    ;\n\nCollectionElementList\n    : CollectionElement ( Comma CollectionElement )*\n    ;\n\nCollectionElement\n    : Expression\n    | CollectionInitializer\n    ;\n```\n\nThe type of an object creation expression must be a class type, a structure type, or a type parameter with a `New` constraint and cannot be a `MustInherit` class. Given an object creation expression of the form `New T(A)`, where `T` is a class type or structure type and `A` is an optional argument list, overload resolution determines the correct constructor of `T` to call. A type parameter with a `New` constraint is considered to have a single, parameterless constructor. If no constructor is callable, a compile-time error occurs; otherwise the expression results in the creation of a new instance of `T` using the chosen constructor. If there are no arguments, the parentheses may be omitted.\n\nWhere an instance is allocated depends on whether the instance is a class type or a value type. `New` instances of class types are created on the system heap, while new instances of value types are created directly on the stack.\n\nAn object-creation expression can optionally specify a list of member initializers after the constructor arguments. These member initializers are prefixed with the keyword `With`, and the initializer list is interpreted as if it was in the context of a `With` statement. For example, given the class:\n\n```vb\nClass Customer\n    Dim Name As String\n    Dim Address As String\nEnd Class\n```\n\nThe code:\n\n```vb\nModule Test\n    Sub Main()\n        Dim x As New Customer() With { .Name = \"Bob Smith\", _\n            .Address = \"123 Main St.\" }\n    End Sub\nEnd Module\n```\n\nIs roughly equivalent to:\n\n```vb\nModule Test\n    Sub Main()\n        Dim x, _t1 As Customer\n\n        _t1 = New Customer()\n        With _t1\n            .Name = \"Bob Smith\"\n            .Address = \"123 Main St.\"\n        End With\n\n        x = _t1\n    End Sub\nEnd Module\n```\n\nEach initializer must specify a name to assign, and the name must be a non-`ReadOnly` instance variable or property of the type being constructed; the member access will not be late bound if the type being constructed is `Object`. Initializers may not use the `Key` keyword. Each member in a type can only be initialized once. The initializer expressions, however, may refer to each other. For example:\n\n```vb\nModule Test\n    Sub Main()\n        Dim x As New Customer() With { .Name = \"Bob Smith\", _\n            .Address = .Name & \" St.\" }\n    End Sub\nEnd Module\n```\n\nThe initializers are assigned left-to-right, so if an initializer refers to a member that has not been initialized yet, it will see whatever value the instance variable after the constructor ran:\n\n```vb\nModule Test\n    Sub Main()\n        ' The value of Address will be \" St.\" since Name has not been\n        ' assigned yet.\n        Dim x As New Customer() With { .Address = .Name & \" St.\" }\n    End Sub\nEnd Module\n```\n\nInitializers can be nested:\n\n```vb\nClass Customer\n    Dim Name As String\n    Dim Address As Address\n    Dim Age As Integer\nEnd Class\n\nClass Address\n    Dim Street As String\n    Dim City As String\n    Dim State As String\n    Dim ZIP As String\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim c As New Customer() With { _\n            .Name = \"John Smith\", _\n            .Address = New Address() With { _\n                .Street = \"23 Main St.\", _\n                .City = \"Peoria\", _\n                .State = \"IL\", _\n                .ZIP = \"13934\" }, _\n            .Age = 34 }\n    End Sub\nEnd Module\n```\n\nIf the type being created is a collection type and has an instance method named `Add` (including extension methods and shared methods), then the object-creation expression can specify a collection initializer prefixed by the keyword `From`. An object-creation expression cannot specify both a member initializer and a collection initializer. Each element in the collection initializer is passed as an argument to an invocation of the `Add` function. For example:\n\n```vb\nDim list = New List(Of Integer)() From { 1, 2, 3, 4 }\n```\n\nis equivalent to:\n\n```vb\nDim list = New List(Of Integer)()\nlist.Add(1)\nlist.Add(2)\nlist.Add(3)\n```\n\nIf an element is a collection initializer itself, each element of the sub-collection initializer will be passed as an individual argument to the `Add` function. For example, the following:\n\n```vb\nDim dict = Dictionary(Of Integer, String) From { { 1, \"One\" },{ 2, \"Two\" } }\n```\n\nis equivalent to:\n\n```vb\nDim dict = New Dictionary(Of Integer, String)\ndict.Add(1, \"One\")\ndict.Add(2, \"Two\")\n```\n\nThis expansion is always done and is only ever done one level deep; after that, sub-initializers are considered array literals. For example:\n\n```vb\n' Error: List(Of T) does not have an Add method that takes two parameters.\nDim list = New List(Of Integer())() From { { 1, 2 }, { 3, 4 } }\n\n' OK, this initializes the dictionary with (Integer, Integer()) pairs.\nDim dict = New Dictionary(Of Integer, Integer())() From _\n        { {  1, { 2, 3 } }, { 3, { 4, 5 } } }\n```\n\n\n### Array Expressions\n\nAn array expression is used to create a new instance of an array type. There are two types of array expressions: array creation expressions, and array literals.\n\n#### Array creation expressions\n\nIf an array size initialization modifier is supplied, the resulting array type is derived by deleting each of the individual arguments from the array size initialization argument list. The value of each argument determines the upper bound of the corresponding dimension in the newly allocated array instance. If the expression has a non-empty collection initializer, each argument in the argument list must be a constant, and the rank and dimension lengths specified by the expression list must match those of the collection initializer.\n\n```vb\nDim a() As Integer = New Integer(2) {}\nDim b() As Integer = New Integer(2) { 1, 2, 3 }\nDim c(,) As Integer = New Integer(1, 2) { { 1, 2, 3 } , { 4, 5, 6 } }\n\n' Error, length/initializer mismatch.\nDim d() As Integer = New Integer(2) { 0, 1, 2, 3 }\n```\n\nIf an array size initialization modifier is not supplied, then the type name must be an array type and the collection initializer must be empty or have the same number of levels of nesting as the rank of the specified array type. All of the elements in the innermost nesting level must be implicitly convertible to the element type of the array and must be classified as a value. The number of elements in each nested collection initializer must always be consistent with the size of the other collections at the same level. The individual dimension lengths are inferred from the number of elements in each of the corresponding nesting levels of the collection initializer. If the collection initializer is empty, the length of each dimension is zero.\n\n```vb\nDim e() As Integer = New Integer() { 1, 2, 3 }\nDim f(,) As Integer = New Integer(,) { { 1, 2, 3 } , { 4, 5, 6 } }\n\n' Error: Inconsistent numbers of elements!\nDim g(,) As Integer = New Integer(,) { { 1, 2 }, { 4, 5, 6 } }\n\n' Error: Inconsistent levels of nesting!\nDim h(,) As Integer = New Integer(,) { 1, 2, { 3, 4 } }\n```\n\nThe outermost nesting level of a collection initializer corresponds to the leftmost dimension of an array, and the innermost nesting level corresponds to the rightmost dimension. The example:\n\n```vb\nDim array As Integer(,) = _\n    { { 0, 1 }, { 2, 3 }, { 4, 5 }, { 6, 7 }, { 8, 9 } }\n```\n\nIs equivalent to the following:\n\n```vb\nDim array(4, 1) As Integer\n\narray(0, 0) = 0: array(0, 1) = 1\narray(1, 0) = 2: array(1, 1) = 3\narray(2, 0) = 4: array(2, 1) = 5\narray(3, 0) = 6: array(3, 1) = 7\narray(4, 0) = 8: array(4, 1) = 9\n```\n\nIf the collection initializer is empty (that is, one that contains curly braces but no initializer list) and the bounds of the dimensions of the array being initialized are known, the empty collection initializer represents an array instance of the specified size where all the elements have been initialized to the element type's default value. If the bounds of the dimensions of the array being initialized are not known, the empty collection initializer represents an array instance in which all dimensions are size zero.\n\nAn array instance's rank and length of each dimension are constant for the entire lifetime of the instance. In other words, it is not possible to change the rank of an existing array instance, nor is it possible to resize its dimensions.\n\n#### Array Literals\n\nAn array literal denotes an array whose element type, rank, and bounds are inferred from a combination of the expression context and a collection initializer. This is explained in Section [Expression Reclassification](expressions.md#expression-reclassification).\n\n```antlr\nArrayExpression\n    : ArrayCreationExpression\n    | ArrayLiteralExpression\n    ;\n\nArrayCreationExpression\n    : 'New' NonArrayTypeName ArrayNameModifier CollectionInitializer\n    ;\n\nArrayLiteralExpression\n    : CollectionInitializer\n    ;\n```\n\nFor example:\n\n```vb\n' array of integers\nDim a = {1, 2, 3}\n\n' array of shorts\nDim b = {1S, 2S, 3S}\n\n' array of shorts whose type is taken from the context\nDim c As Short() = {1, 2, 3}\n\n' array of type Integer(,)\nDim d = {{1, 0}, {0, 1}}\n\n' jagged array of rank ()()\nDim e = {({1, 0}), ({0, 1})}\n\n' error: inconsistent rank\nDim f = {{1}, {2, 3}}\n\n' error: inconsistent rank\nDim g = {1, {2}}\n```\n\nThe format and requirements for the collection initializer in an array literal is exactly the same as that for the collection initializer in an array creation expression.\n\n__Note.__ An array literal does not create the array in and of itself; instead, it is the reclassification of the expression into a value that causes the array to be created. For instance, the conversion `CType(new Integer() {1,2,3}, Short())` is not possible because there is no conversion from `Integer()` to `Short()`; but the expression `CType({1,2,3},Short())` is possible because it first reclassifies the array literal into the array creation expression `New Short() {1,2,3}`.\n\n\n### Delegate-Creation Expressions\n\nA delegate-creation expression is used to create a new instance of a delegate type. The argument of a delegate-creation expression must be an expression classified as a method pointer or a lambda method.\n\nIf the argument is a method pointer, one of the methods referenced by the method pointer must be applicable to the signature of the delegate type. A method `M` is applicable to a delegate type `D` if:\n\n* `M` is not `Partial` or has a body.\n\n* Both `M` and `D` are functions, or `D` is a subroutine.\n\n* `M` and `D` have the same number of parameters.\n\n* The parameter types of `M` each have a conversion from the type of the corresponding parameter type of `D`, and their modifiers (i.e. `ByRef`, `ByVal`) match.\n\n* The return type of `M`, if any, has a conversion to the return type of `D`.\n\nIf the method pointer references a late-bound access, then the late-bound access is assumed to be to a function that has the same number of parameters as the delegate type.\n\nIf strict semantics are not being used and there is only one method referenced by the method pointer, but it is not applicable due to the fact that it has no parameters and the delegate type does, then the method is considered applicable and the parameters or return value are simply ignored. For example:\n\n```vb\nDelegate Sub F(x As Integer)\n\nModule Test\n    Sub M()\n    End Sub\n\n    Sub Main()\n        ' Valid\n        Dim x As F = AddressOf M\n    End Sub\nEnd Module\n```\n\n__Note.__ This relaxation is only allowed when strict semantics are not being used because of extension methods. Because extension methods are only considered if a regular method was not applicable, it is possible for an instance method with no parameters to hide an extension method with parameters for the purpose of delegate construction.\n\nIf more than one method referenced by the method pointer is applicable to the delegate type, then overload resolution is used to pick between the candidate methods. The types of the parameters to the delegate are used as the types of the arguments for the purposes of overload resolution. If no one method candidate is most applicable, a compile-time error occurs. In the following example, the local variable is initialized with a delegate that refers to the second `Square` method because that method is more applicable to the signature and return type of `DoubleFunc`.\n\n```vb\nDelegate Function DoubleFunc(x As Double) As Double\n\nModule Test\n    Function Square(x As Single) As Single\n        Return x * x\n    End Function \n\n    Function Square(x As Double) As Double\n        Return x * x\n    End Function\n\n    Sub Main()\n        Dim a As New DoubleFunc(AddressOf Square)\n    End Sub\nEnd Module\n```\n\nHad the second `Square` method not been present, the first `Square` method would have been chosen. If strict semantics are specified by the compilation environment or by `Option Strict`, then a compile-time error occurs if the most specific method referenced by the method pointer is narrower than the delegate signature. A method `M` is considered narrower than a delegate type `D` if:\n\n* A parameter type of `M` has a widening conversion to the corresponding parameter type of `D`.\n\n* Or, the return type, if any, of `M` has a narrowing conversion to the return type of `D`.\n\nIf type arguments are associated with the method pointer, only methods with the same number of type arguments are considered. If no type arguments are associated with the method pointer, type inference is used when matching signatures against a generic method. Unlike other normal type inference, the return type of the delegate is used when inferring type arguments, but return types are still not considered when determining the least generic overload. The following example shows both ways of supplying a type argument to a delegate-creation expression:\n\n```vb\nDelegate Function D(s As String, i As Integer) As Integer\nDelegate Function E() As Integer\n\nModule Test\n    Public Function F(Of T)(s As String, t1 As T) As T\n    End Function\n\n    Public Function G(Of T)() As T\n    End Function\n\n    Sub Main()\n        Dim d1 As D = AddressOf f(Of Integer)    ' OK, type arg explicit\n        Dim d2 As D = AddressOf f                ' OK, type arg inferred\n\n        Dim e1 As E = AddressOf g(Of Integer)    ' OK, type arg explicit\n        Dim e2 As E = AddressOf g                ' OK, infer from return\n  End Sub\nEnd Module\n```\n\nIn the above example, a non-generic delegate type was instantiated using a generic method. It is also possible to create an instance of a constructed delegate type using a generic method. For example:\n\n```vb\nDelegate Function Predicate(Of U)(u1 As U, u2 As U) As Boolean\n\nModule Test\n    Function Compare(Of T)(t1 As List(of T), t2 As List(of T)) As Boolean\n        ...\n    End Function\n\n    Sub Main()\n        Dim p As Predicate(Of List(Of Integer))\n        p = AddressOf Compare(Of Integer)\n    End Sub\nEnd Module\n```\n\nIf the argument to the delegate-creation expression is a lambda method, the lambda method must be applicable to the signature of the delegate type. A lambda method `L` is applicable to a delegate type `D` if:\n\n* If `L` has parameters, `D` has the same number of parameters. (If `L` has no parameters, the parameters of `D` are ignored.)\n\n* The parameter types of `L` each have a conversion to the type of the corresponding parameter type of `D`, and their modifiers (i.e. `ByRef`, `ByVal`) match.\n\n* If `D` is a function, the return type of `L` has a conversion to the return type of `D`. (If `D` is a subroutine, the return value of `L` is ignored.)\n\nIf the parameter type of a parameter of `L` is omitted, then the type of the corresponding parameter in `D` is inferred; if the parameter of `L` has array or nullable name modifiers, a compile-time error results. Once all of the parameter types of `L` are available, then the type of the expression in the lambda method is inferred. For example:\n\n```vb\nDelegate Function F(x As Integer, y As Long) As Long\n\nModule Test\n    Sub Main()\n        ' b inferred to Integer, c and return type inferred to Long\n        Dim a As F = Function(b, c) b + c\n\n        ' e and return type inferred to Integer, f inferred to Long\n        Dim d As F = Function(e, f) e + CInt(f)\n    End Sub\nEnd Module\n```\n\nIn some situations where delegate signature does not exactly match the lambda method or method signature, the .NET Framework may not support the delegate creation natively. In that situation, a lambda method expression is used to match the two methods. For example:\n\n```vb\nDelegate Function IntFunc(x As Integer) As Integer\n\nModule Test\n    Function SquareString(x As String) As String\n        Return CInt(x) * CInt(x)\n    End Function \n\n    Sub Main()\n        ' The following two lines are equivalent\n        Dim a As New IntFunc(AddressOf SquareString)\n        Dim b As New IntFunc( _\n            Function(x As Integer) CInt(SquareString(CStr(x))))\n    End Sub\nEnd Module\n```\n\nThe result of a delegate-creation expression is a delegate instance that refers to the matching method with the associated target expression (if any) from the method pointer expression. If the target expression is typed as a value type, then the value type is copied onto the system heap because a delegate can only point to a method of an object on the heap. The method and object to which a delegate refers remain constant for the entire lifetime of the delegate. In other words, it is not possible to change the target or object of a delegate after it has been created.\n\n### Anonymous Object-Creation Expressions\n\nAn object-creation expression with member initializers can also omit the type name entirely.\n\n```antlr\nAnonymousObjectCreationExpression\n    : 'New' ObjectMemberInitializer\n    ;\n```\n\nIn that case, an anonymous type is constructed based on the types and names of the members initialized as a part of the expression. For example:\n\n```vb\nModule Test\n    Sub Main()\n        Dim Customer = New With { .Name = \"John Smith\", .Age = 34 }\n\n        Console.WriteLine(Customer.Name)\n    End Sub\nEnd Module\n```\n\nThe type created by an anonymous object-creation expression is a class that has no name, inherits directly from `Object`, and has a set of properties with the same name as the members assigned to in the member initializer list. The type of each property is inferred using the same rules as local variable type inference. Generated anonymous types also override `ToString`, returning a string representation of all members and their values. (The exact format of this string is beyond the scope of this specification).\n\nBy default, the properties generated by the anonymous type are read-write. It is possible to mark an anonymous type property as read-only by using the `Key` modifier. The `Key` modifier specifies that the field can be used to uniquely identify the value the anonymous type represents. In addition to making the property read-only, it also causes the anonymous type to override `Equals` and  `GetHashCode` and to implement the interface `System.IEquatable(Of T)` (filling in the anonymous type for `T`). The members are defined as follows:\n\n`Function Equals(obj As Object) As Boolean` and `Function Equals(val As T) As Boolean` are implemented by validating that the two instances are of the same type and then comparing each `Key` member using `Object.Equals`. If all `Key` members are equal, then `Equals` returns `True`, otherwise `Equals` returns `False`.\n\n`Function GetHashCode() As Integer` is implemented such that if `Equals` is true for two instances of the anonymous type, then `GetHashCode` will return the same value. The hash starts with a seed value and then, for each `Key` member, in order multiplies the hash by 31 and adds the `Key` member's hash value (provided by `GetHashCode`) if the member is not a reference type or nullable value type with the value of `Nothing`.\n\nFor example, the type created in the statement:\n\n```vb\nDim zipState = New With { Key .ZipCode = 98112, .State = \"WA\" }\n```\n\ncreates a class that looks approximately like this (although exact implementation may vary):\n\n```vb\nFriend NotInheritable Class $Anonymous1\n    Implements IEquatable(Of $Anonymous1)\n\n    Private ReadOnly _zipCode As Integer\n    Private _state As String\n\n    Public Sub New(zipCode As Integer, state As String)\n        _zipCode = zipcode\n        _state = state\n    End Sub\n\n    Public ReadOnly Property ZipCode As Integer\n        Get\n            Return _zipCode\n        End Get\n    End Property\n\n    Public Property State As String\n        Get\n            Return _state\n        End Get\n        Set (value As Integer)\n            _state = value\n        End Set\n    End Property\n\n    Public Overrides Function Equals(obj As Object) As Boolean\n        Dim val As $Anonymous1 = TryCast(obj, $Anonymous1)\n        Return Equals(val)\n    End Function\n\n    Public Overloads Function Equals(val As $Anonymous1) As Boolean _\n        Implements IEquatable(Of $Anonymous1).Equals\n\n        If val Is Nothing Then \n            Return False\n        End If\n\n        If Not Object.Equals(_zipCode, val._zipCode) Then \n            Return False\n        End If\n\n        Return True\n    End Function\n\n    Public Overrides Function GetHashCode() As Integer\n        Dim hash As Integer = 0\n\n        hash = hash Xor _zipCode.GetHashCode()\n\n        Return hash\n    End Function\n\n    Public Overrides Function ToString() As String\n        Return \"{ Key .ZipCode = \" & _zipCode & \", .State = \" & _state & \" }\"\n    End Function\nEnd Class\n```\n\nTo simplify the situation where an anonymous type is created from the fields of another type, field names can be inferred directly from expressions in the following cases:\n\n* A simple name expression `x` infers the name `x`.\n\n* A member access expression `x.y` infers the name `y`.\n\n* A dictionary lookup expression `x!y` infers the name `y`.\n\n* An invocation or index expression with no arguments `x()` infers the name `x`.\n\n* An XML member access expression `x.<y>`, `x...<y>`, `x.@y` infers the name `y`.\n\n* An XML member access expression that is the target of a member access expression `x.<y>.z` infers the name `z`.\n\n* An XML member access expression that is the target of an invocation or index expression with no arguments `x.<y>.z()` infers the name `z`.\n\n* An XML member access expression that is the target of an invocation or index expression `x.<y>(0)` infers the name `y`.\n\nThe initializer is interpreted as an assignment of the expression to the inferred name. For example, the following initializers are equivalent:\n\n```vb\nClass Address\n    Public Street As String\n    Public City As String\n    Public State As String\n    Public ZIP As String\nEnd Class\n\nClass C1\n    Sub Test(a As Address)\n        Dim cityState1 = New With { .City = a.City, .State = a.State }\n        Dim cityState2 = New With { a.City, a.State }\n    End Sub\nEnd Class\n```\n\nIf a member name is inferred that conflicts with an existing member of the type, such as `GetHashCode`, then a compile time error occurs. Unlike regular member initializers, anonymous object-creation expressions do not allow member initializers to have circular references, or to refer to a member before it has been initialized. For example:\n\n```vb\nModule Test\n    Sub Main()\n        ' Error: Circular references\n        Dim x = New With { .a = .b, .b = .a }\n\n        ' Error: Referring to .b before it has been assigned to\n        Dim y = New With { .a = .b, .b = 10 }\n\n        ' Error: Referring to .a before it has been assigned to\n        Dim z = New With { .a = .a }\n    End Sub\nEnd Module\n```\n\nIf two anonymous class creation expressions occur within the same method and yield the same resulting shape -- if the property order, property names, and property types all match -- they will both refer to the same anonymous class. The method scope of an instance or shared member variable with an initializer is the constructor in which the variable is initialized.\n\n__Note.__ It is possible that a compiler may choose to unify anonymous types further, such as at the assembly level, but this cannot be relied upon at this time.\n\n\n## Cast Expressions\n\nA cast expression coerces an expression to a given type. Specific cast keywords coerce expressions into the primitive types. Three general cast keywords, `CType`, `TryCast` and `DirectCast`, coerce an expression into a type.\n\n```antlr\nCastExpression\n    : 'DirectCast' OpenParenthesis Expression Comma TypeName CloseParenthesis\n    | 'TryCast' OpenParenthesis Expression Comma TypeName CloseParenthesis\n    | 'CType' OpenParenthesis Expression Comma TypeName CloseParenthesis\n    | CastTarget OpenParenthesis Expression CloseParenthesis\n    ;\n\nCastTarget\n    : 'CBool' | 'CByte' | 'CChar'  | 'CDate'  | 'CDec' | 'CDbl' | 'CInt'\n    | 'CLng'  | 'CObj'  | 'CSByte' | 'CShort' | 'CSng' | 'CStr' | 'CUInt'\n    | 'CULng' | 'CUShort'\n    ;\n```\n\n`DirectCast` and `TryCast` have special behaviors. Because of this, they only support native conversions. Additionally, the target type in a `TryCast` expression cannot be a value type. User-defined conversion operators are not considered when `DirectCast` or `TryCast` is used. (__Note.__ The conversion set that `DirectCast` and `TryCast` support are restricted because they implement \"native CLR\" conversions. The purpose of `DirectCast` is to provide the functionality of the \"unbox\" instruction, while the purpose of `TryCast` is to provide the functionality of the \"isinst\" instruction. Since they map onto CLR instructions, supporting conversions not directly supported by the CLR would defeat the intended purpose.)\n\n`DirectCast` converts expressions that are typed as `Object` differently than `CType`. When converting an expression of type `Object` whose run-time type is a primitive value type, `DirectCast` throws a `System.InvalidCastException` exception if the specified type is not the same as the run-time type of the expression or a `System.NullReferenceException` if the expression evaluates to `Nothing`. (__Note.__ As noted above, `DirectCast` maps directly onto the CLR instruction \"unbox\" when the type of the expression is `Object`. In contrast, `CType` turns into a call to a runtime helper to do the conversion so that conversions between primitive types can be supported. In the case when an `Object` expression is being converted to a primitive value type and the type of the actual instance match the target type, `DirectCast` will be significantly faster than `CType`.)\n\n`TryCast` converts expressions but does not throw an exception if the expression cannot be converted to the target type. Instead, `TryCast` will result in `Nothing` if the expression cannot be converted at runtime. (__Note.__ As noted above, `TryCast` maps directly onto the CLR instruction \"isinst\". By combining the type check and the conversion into a single operation, `TryCast` can be cheaper than doing a `TypeOf ... Is` and then a `CType`.)\n\nFor example:\n\n```vb\nInterface ITest\n    Sub Test()\nEnd Interface\n\nModule Test\n    Sub Convert(o As Object)\n        Dim i As ITest = TryCast(o, ITest)\n\n        If i IsNot Nothing Then\n            i.Test()\n        End If\n    End Sub\nEnd Module\n```\n\nIf no conversion exists from the type of the expression to the specified type, a compile-time error occurs. Otherwise, the expression is classified as a value and the result is the value produced by the conversion.\n\n\n## Operator Expressions\n\nThere are two kinds of operators. *Unary operators* take one operand and use prefix notation (for example, `-x`). *Binary operators* take two operands and use infix notation (for example, `x + y`). With the exception of the relational operators, which always result in `Boolean`, an operator defined for a particular type results in that type. The operands to an operator must always be classified as a value; the result of an operator expression is classified as a value.\n\n```antlr\nOperatorExpression\n    : ArithmeticOperatorExpression\n    | RelationalOperatorExpression\n    | LikeOperatorExpression\n    | ConcatenationOperatorExpression\n    | ShortCircuitLogicalOperatorExpression\n    | LogicalOperatorExpression\n    | ShiftOperatorExpression\n    | AwaitOperatorExpression\n    ;\n```\n\n### Operator Precedence and Associativity\n\nWhen an expression contains multiple binary operators, the *precedence* of the operators controls the order in which the individual binary operators are evaluated. For example, the expression `x + y * z` is evaluated as `x + (y * z)` because the `*` operator has higher precedence than the `+` operator. The following table lists the binary operators in descending order of precedence:\n\n\n| __Category__     | __Operators__                                          | \n|------------------|--------------------------------------------------------|\n| Primary          | All non-operator expressions                           |\n| Await            | `Await`                                                |\n| Exponentiation   | `^`                                                    |\n| Unary negation   | `+`, `-`                                               |\n| Multiplicative   | `*`, `/`                                               |\n| Integer division | `\\`                                                    |\n| Modulus          | `Mod`                                                  |\n| Additive         | `+`, `-`                                               |\n| Concatenation    | `&`                                                    |\n| Shift            | `<<`, `>>`                                             |\n| Relational       | `=`, `<>`, `<`, `>`, `<=`, `>=`, `Like`, `Is`, `IsNot` |\n| Logical NOT      | `Not`                                                  |\n| Logical AND      | `And`, `AndAlso`                                       |\n| Logical OR       | `Or`, `OrElse`                                         |\n| Logical XOR      | `Xor`                                                  |\n\nWhen an expression contains two operators with the same precedence, the *associativity* of the operators controls the order in which the operations are performed. All binary operators are left-associative, meaning that operations are performed from left to right. Precedence and associativity can be controlled using parenthetical expressions.\n\n### Object Operands\n\nIn addition to the regular types supported by each operator, all operators support operands of type `Object`. Operators applied to `Object` operands are handled similarly to method calls made on `Object` values: a late-bound method call might be chosen, in which case the run-time type of the operands, rather than the compile-time type, determines the validity and type of the operation. If strict semantics are specified by the compilation environment or by `Option Strict`, any operators with operands of type `Object` cause a compile-time error, except for the `TypeOf...Is`, `Is` and `IsNot` operators.\n\nWhen operator resolution determines that an operation should be performed late-bound, the outcome of the operation is the result of applying the operator to the operand types if the run-time types of the operands are types that are supported by the operator. The value `Nothing` is treated as the default value of the type of the other operand in a binary operator expression. In a unary operator expression, or if both operands are `Nothing` in a binary operator expression, the type of the operation is `Integer` or the only result type of the operator, if the operator does not result in `Integer`. The result of the operation is always then cast back to `Object`. If the operand types have no valid operator, a `System.InvalidCastException` exception is thrown. Conversions at run time are done without regard to whether they are implicit or explicit.\n\nIf the result of a numeric binary operation would produce an overflow exception (regardless of whether integer overflow checking is on or off), then the result type is promoted to the next wider numeric type, if possible. For example, consider the following code:\n\n```vb\nModule Test\n    Sub Main()\n        Dim o As Object = CObj(CByte(2)) * CObj(CByte(255))\n\n        Console.WriteLine(o.GetType().ToString() & \" = \" & o)\n    End Sub\nEnd Module\n```\n\nIt prints the following result:\n\n```console\nSystem.Int16 = 512\n```\n\nIf no wider numeric type is available to hold the number, a `System.OverflowException` exception is thrown.\n\n### Operator Resolution\n\nGiven an operator type and a set of operands, operator resolution determines which operator to use for the operands. When resolving operators, user-defined operators will be considered first, using the following steps:\n\n1. First, all of the candidate operators are collected. The candidate operators are all of the user-defined operators of the particular operator type in the source type and all of the user-defined operators of the particular type in the target type. If the source type and destination type are related, common operators are only considered once.\n\n2. Then, overload resolution is applied to the operators and operands to select the most specific operator. In the case of binary operators, this may result in a late-bound call.\n\nWhen collecting the candidate operators for a type `T?`, the operators of type `T` are used instead. Any of `T`'s user-defined operators that involve only non-nullable value types are also lifted. A lifted operator uses the nullable version of any value types, with the exception the return types of `IsTrue` and `IsFalse` (which must be `Boolean`). Lifted operators are evaluated by converting the operands to their non-nullable version, then evaluating the user-defined operator and then converting the result type to its nullable version. If ether operand is `Nothing`, the result of the expression is a value of `Nothing` typed as the nullable version of the result type. For example:\n\n```vb\nStructure T\n    ...\nEnd Structure\n\nStructure S\n    Public Shared Operator +(ByVal op1 As S, ByVal op2 As T) As T\n        ...\n    End Operator\nEnd Structure\n\nModule Test\n    Sub Main()\n        Dim x As S?\n        Dim y, z As T?\n\n        ' Valid, as S + T = T is lifted to S? + T? = T?\n        z = x + y \n    End Sub\nEnd Module\n```\n\nIf the operator is a binary operator and one of the operands is reference type, the operator is also lifted, but any binding to the operator produces an error. For example:\n\n```vb\nStructure S1\n    Public F1 As Integer\n\n    Public Shared Operator +(left As S1, right As String) As S1\n       ...\n    End Operator\nEnd Structure\n\nModule Test\n    Sub Main()\n        Dim a? As S1\n        Dim s As String\n        \n        ' Error: '+' is not defined for S1? and String\n        a = a + s\n    End Sub\nEnd Module\n```\n\n__Note.__ This rule exists because there has been consideration whether we wish to add null-propagating reference types in a future version, in which case the behavior in the case of binary operators between the two types would change.\n\nAs with conversions, user-defined operators are always preferred over lifted operators.\n\nWhen resolving overloaded operators, there may be differences between classes defined in Visual Basic and those defined in other languages:\n\n* In other languages, `Not`, `And`, and `Or` may be overloaded both as logical operators and bitwise operators. Upon import from an external assembly, either form is accepted as a valid overload for these operators. However, for a type which defines both logical and bitwise operators, only the bitwise implementation will be considered.\n\n* In other languages, `>>` and `<<` may be overloaded both as signed operators and unsigned operators. Upon import from an external assembly, either form is accepted as a valid overload. However, for a type which defines both signed and unsigned operators, only the signed implementation will be considered.\n\n* If no user-defined operator is most specific to the operands, then intrinsic operators will be considered. If no intrinsic operator is defined for the operands and either operand has type Object then the operator will be resolved late-bound; otherwise,  a compile-time error results.\n\nIn prior versions of Visual Basic, if there was exactly one operand of type Object, and no applicable user-defined operators, and no applicable intrinsic operators, then it was an error. As of Visual Basic 11, it is now resolved late-bound. For example:\n\n```vb\nModule Module1\n  Sub Main()\n      Dim p As Object = Nothing\n      Dim U As New Uri(\"http://www.microsoft.com\")\n      Dim j = U * p  ' is now resolved late-bound\n   End Sub\nEnd Module\n```\n\nA type `T` that has an intrinsic operator also defines that same operator for `T?`. The result of the operator on `T?` will be the same as for `T`, except that if either operand is `Nothing`, the result of the operator will be `Nothing` (i.e. the null value is propagated). For the purposes of resolving the type of an operation, the `?` is removed from any operands that have them, the type of the operation is determined, and a `?` is added to the type of the operation if any of the operands were nullable value types. For example:\n\n```vb\nDim v1? As Integer = 10\nDim v2 As Long = 20\n\n' Type of operation will be Long?\nConsole.WriteLine(v1 + v2)\n```\n\nEach operator lists the intrinsic types it is defined for and the type of the operation performed given the operand types. The result of type of a intrinsic operation follows these general rules:\n\n* If all operands are of the same type, and the operator is defined for the type, then no conversion occurs and the operator for that type is used.\n\n* Any operand whose type is not defined for the operator is converted using the following steps and the operator is resolved against the new types:\n\n  * The operand is converted to the next widest type that is defined for both the operator and the operand and to which it is implicitly convertible.\n\n  * If there is no such type, then the operand is converted to the next narrowest type that is defined for both the operator and the operand and to which it is implicitly convertible.\n\n  * If there is no such type or the conversion cannot occur, a compile-time error occurs.\n\n* Otherwise, the operands are converted to the wider of the operand types and the operator for that type is used. If the narrower operand type cannot be implicitly converted to the wider operator type, a compile-time error occurs.\n\nDespite these general rules, however, there are a number of special cases called out in the operator results tables.\n\n__Note.__ For formatting reasons, the operator type tables abbreviate the predefined names to their first two characters. So \"By\" is `Byte`, \"UI\" is `UInteger`, \"St\" is `String`, etc. \"Err\" means that there is no operation defined for the given operand types.\n\n## Arithmetic Operators\n\nThe `*`, `/`, `\\`, `^`, `Mod`, `+`, and `-` operators are the *arithmetic operators*.\n\n```antlr\nArithmeticOperatorExpression\n    : UnaryPlusExpression\n    | UnaryMinusExpression\n    | AdditionOperatorExpression\n    | SubtractionOperatorExpression\n    | MultiplicationOperatorExpression\n    | DivisionOperatorExpression\n    | ModuloOperatorExpression\n    | ExponentOperatorExpression\n    ;\n```\n\nFloating-point arithmetic operations may be performed with higher precision than the result type of the operation. For example, some hardware architectures support an \"extended\" or \"long double\" floating-point type with greater range and precision than the `Double` type, and implicitly perform all floating-point operations using this higher-precision type. Hardware architectures can be made to perform floating-point operations with less precision only at excessive cost in performance; rather than require an implementation to forfeit both performance and precision, Visual Basic allows the higher-precision type to be used for all floating-point operations. Other than delivering more precise results, this rarely has any measurable effects. However, in expressions of the form `x * y / z`, where the multiplication produces a result that is outside the `Double` range, but the subsequent division brings the temporary result back into the `Double` range, the fact that the expression is evaluated in a higher-range format may cause a finite result to be produced instead of infinity.\n\n\n### Unary Plus Operator\n\n```antlr\nUnaryPlusExpression\n    : '+' Expression\n    ;\n```\n\nThe unary plus operator is defined for the `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, `Long`, `Single`, `Double`, and `Decimal` types.\n\n__Operation Type:__\n\n\n| __Bo__ | __SB__ | __By__ | __Sh__ | __US__ | __In__ | __UI__ | __Lo__ | __UL__ | __De__ | __Si__ | __Do__ | __Da__  | __Ch__  | __St__ | __Ob__ | \n|----|----|----|----|----|----|----|----|----|----|----|----|-----|-----|----|----|\n| Sh | SB | By | Sh | US | In | UI | Lo | UL | De | Si | Do | Err | Err | Do | Ob | \n\n\n### Unary Minus Operator\n\n```antlr\nUnaryMinusExpression\n    : '-' Expression\n    ;\n```\n\nThe unary minus operator is defined for the following types:\n\n`SByte`, `Short`, `Integer`, and `Long`. The result is computed by subtracting the operand from zero. If integer overflow checking is on and the value of the operand is the maximum negative `SByte`, `Short`, `Integer`, or `Long`, a `System.OverflowException` exception is thrown. Otherwise, if the value of the operand is the maximum negative `SByte`, `Short`, `Integer`, or `Long`, the result is that same value, and the overflow is not reported.\n\n`Single` and `Double`. The result is the value of the operand with its sign inverted, including the values 0 and Infinity. If the operand is NaN, the result is also NaN.\n\n`Decimal`. The result is computed by subtracting the operand from zero.\n\n__Operation Type:__\n\n| __Bo__ | __SB__ | __By__ | __Sh__ | __US__ | __In__ | __UI__ | __Lo__ | __UL__ | __De__ | __Si__ | __Do__ | __Da__  | __Ch__  | __St__ | __Ob__ | \n|----|----|----|----|----|----|----|----|----|----|----|----|-----|-----|----|----|\n| Sh | SB | Sh | Sh | In | In | Lo | Lo | De | De | Si | Do | Err | Err | Do | Ob | \n\n\n### Addition Operator\n\nThe addition operator computes the sum of the two operands.\n\n```antlr\nAdditionOperatorExpression\n    : Expression '+' LineTerminator? Expression\n    ;\n```\n\nThe addition operator is defined for the following types:\n\n* `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, and `Long`. If integer overflow checking is on and the sum is outside the range of the result type, a `System.OverflowException` exception is thrown. Otherwise, overflows are not reported, and any significant high-order bits of the result are discarded.\n\n* `Single` and `Double`. The sum is computed according to the rules of IEEE 754 arithmetic.\n\n* `Decimal`. If the resulting value is too large to represent in the decimal format, a `System.OverflowException` exception is thrown. If the result value is too small to represent in the decimal format, the result is 0.\n\n* `String`. The two `String` operands are concatenated together.\n\n* `Date`. The `System.DateTime` type defines overloaded addition operators. Because `System.DateTime` is equivalent to the intrinsic `Date` type, these operators is also available on the `Date` type.\n\n__Operation Type:__\n\n|        | __Bo__ | __SB__ | __By__ | __Sh__ | __US__ | __In__ | __UI__ | __Lo__ | __UL__ | __De__ | __Si__ | __Do__ | __Da__  | __Ch__  | __St__ | __Ob__ | \n|--------|----|----|----|----|----|----|----|----|----|----|----|----|-----|-----|----|----|\n| __Bo__ | Sh | SB | Sh | Sh | In | In | Lo | Lo | De | De | Si | Do | Err | Err | Do | Ob | \n| __SB__ |    | SB | Sh | Sh | In | In | Lo | Lo | De | De | Si | Do | Err | Err | Do | Ob | \n| __By__ |    |    | By | Sh | US | In | UI | Lo | UL | De | Si | Do | Err | Err | Do | Ob | \n| __Sh__ |    |    |    | Sh | In | In | Lo | Lo | De | De | Si | Do | Err | Err | Do | Ob | \n| __US__ |    |    |    |    | US | In | UI | Lo | UL | De | Si | Do | Err | Err | Do | Ob | \n| __In__ |    |    |    |    |    | In | Lo | Lo | De | De | Si | Do | Err | Err | Do | Ob | \n| __UI__ |    |    |    |    |    |    | UI | Lo | UL | De | Si | Do | Err | Err | Do | Ob | \n| __Lo__ |    |    |    |    |    |    |    | Lo | De | De | Si | Do | Err | Err | Do | Ob | \n| __UL__ |    |    |    |    |    |    |    |    | UL | De | Si | Do | Err | Err | Do | Ob | \n| __De__ |    |    |    |    |    |    |    |    |    | De | Si | Do | Err | Err | Do | Ob | \n| __Si__ |    |    |    |    |    |    |    |    |    |    | Si | Do | Err | Err | Do | Ob | \n| __Do__ |    |    |    |    |    |    |    |    |    |    |    | Do | Err | Err | Do | Ob | \n| __Da__ |    |    |    |    |    |    |    |    |    |    |    |    | St  | Err | St | Ob | \n| __Ch__ |    |    |    |    |    |    |    |    |    |    |    |    |     | St  | St | Ob | \n| __St__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     | St | Ob | \n| __Ob__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     |    | Ob | \n\n\n### Subtraction Operator\n\nThe subtraction operator subtracts the second operand from the first operand.\n\n```antlr\nSubtractionOperatorExpression\n    : Expression '-' LineTerminator? Expression\n    ;\n```\n\nThe subtraction operator is defined for the following types:\n\n* `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, and `Long`. If integer overflow checking is on and the difference is outside the range of the result type, a `System.OverflowException` exception is thrown. Otherwise, overflows are not reported, and any significant high-order bits of the result are discarded.\n\n* `Single` and `Double`. The difference is computed according to the rules of IEEE 754 arithmetic.\n\n* `Decimal`. If the resulting value is too large to represent in the decimal format, a `System.OverflowException` exception is thrown. If the result value is too small to represent in the decimal format, the result is 0.\n\n* `Date`. The `System.DateTime` type defines overloaded subtraction operators. Because `System.DateTime` is equivalent to the intrinsic `Date` type, these operators is also available on the `Date` type.\n\n__Operation Type:__\n\n|        | __Bo__ | __SB__ | __By__ | __Sh__ | __US__ | __In__ | __UI__ | __Lo__ | __UL__ | __De__ | __Si__ | __Do__ | __Da__  | __Ch__  | __St__ | __Ob__ |\n|--------|----|----|----|----|----|----|----|----|----|----|----|----|-----|-----|-----|-----|\n| __Bo__ | Sh | SB | Sh | Sh | In | In | Lo | Lo | De | De | Si | Do | Err | Err | Do  | Ob  | \n| __SB__ |    | SB | Sh | Sh | In | In | Lo | Lo | De | De | Si | Do | Err | Err | Do  | Ob  | \n| __By__ |    |    | By | Sh | US | In | UI | Lo | UL | De | Si | Do | Err | Err | Do  | Ob  | \n| __Sh__ |    |    |    | Sh | In | In | Lo | Lo | De | De | Si | Do | Err | Err | Do  | Ob  | \n| __US__ |    |    |    |    | US | In | UI | Lo | UL | De | Si | Do | Err | Err | Do  | Ob  | \n| __In__ |    |    |    |    |    | In | Lo | Lo | De | De | Si | Do | Err | Err | Do  | Ob  | \n| __UI__ |    |    |    |    |    |    | UI | Lo | UL | De | Si | Do | Err | Err | Do  | Ob  | \n| __Lo__ |    |    |    |    |    |    |    | Lo | De | De | Si | Do | Err | Err | Do  | Ob  | \n| __UL__ |    |    |    |    |    |    |    |    | UL | De | Si | Do | Err | Err | Do  | Ob  | \n| __De__ |    |    |    |    |    |    |    |    |    | De | Si | Do | Err | Err | Do  | Ob  | \n| __Si__ |    |    |    |    |    |    |    |    |    |    | Si | Do | Err | Err | Do  | Ob  | \n| __Do__ |    |    |    |    |    |    |    |    |    |    |    | Do | Err | Err | Do  | Ob  | \n| __Da__ |    |    |    |    |    |    |    |    |    |    |    |    | Err | Err | Err | Err | \n| __Ch__ |    |    |    |    |    |    |    |    |    |    |    |    |     | Err | Err | Err | \n| __St__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     | Do  | Ob  | \n| __Ob__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     |     | Ob  | \n\n\n### Multiplication Operator\n\nThe multiplication operator computes the product of two operands.\n\n```antlr\nMultiplicationOperatorExpression\n    : Expression '*' LineTerminator? Expression\n    ;\n```\n\nThe multiplication operator is defined for the following types:\n\n* `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, and `Long`. If integer overflow checking is on and the product is outside the range of the result type, a `System.OverflowException` exception is thrown. Otherwise, overflows are not reported, and any significant high-order bits of the result are discarded.\n\n* `Single` and `Double`. The product is computed according to the rules of IEEE 754 arithmetic.\n\n* `Decimal`. If the resulting value is too large to represent in the decimal format, a `System.OverflowException` exception is thrown. If the result value is too small to represent in the decimal format, the result is 0.\n\n__Operation Type:__\n\n|        | __Bo__ | __SB__ | __By__ | __Sh__ | __US__ | __In__ | __UI__ | __Lo__ | __UL__ | __De__ | __Si__ | __Do__ | __Da__  | __Ch__  | __St__ | __Ob__ |\n|--------|----|----|----|----|----|----|----|----|----|----|----|----|-----|-----|-----|-----|\n| __Bo__ | Sh | SB | Sh | Sh | In | In | Lo | Lo | De | De | Si | Do | Err | Err | Do  | Ob  | \n| __SB__ |    | SB | Sh | Sh | In | In | Lo | Lo | De | De | Si | Do | Err | Err | Do  | Ob  | \n| __By__ |    |    | By | Sh | US | In | UI | Lo | UL | De | Si | Do | Err | Err | Do  | Ob  | \n| __Sh__ |    |    |    | Sh | In | In | Lo | Lo | De | De | Si | Do | Err | Err | Do  | Ob  | \n| __US__ |    |    |    |    | US | In | UI | Lo | UL | De | Si | Do | Err | Err | Do  | Ob  | \n| __In__ |    |    |    |    |    | In | Lo | Lo | De | De | Si | Do | Err | Err | Do  | Ob  | \n| __UI__ |    |    |    |    |    |    | UI | Lo | UL | De | Si | Do | Err | Err | Do  | Ob  | \n| __Lo__ |    |    |    |    |    |    |    | Lo | De | De | Si | Do | Err | Err | Do  | Ob  | \n| __UL__ |    |    |    |    |    |    |    |    | UL | De | Si | Do | Err | Err | Do  | Ob  | \n| __De__ |    |    |    |    |    |    |    |    |    | De | Si | Do | Err | Err | Do  | Ob  | \n| __Si__ |    |    |    |    |    |    |    |    |    |    | Si | Do | Err | Err | Do  | Ob  | \n| __Do__ |    |    |    |    |    |    |    |    |    |    |    | Do | Err | Err | Do  | Ob  | \n| __Da__ |    |    |    |    |    |    |    |    |    |    |    |    | Err | Err | Err | Err | \n| __Ch__ |    |    |    |    |    |    |    |    |    |    |    |    |     | Err | Err | Err | \n| __St__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     | Do  | Ob  | \n| __Ob__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     |     | Ob  | \n\n\n### Division Operators\n\nDivision operators compute the quotient of two operands. There are two division operators: the regular (floating-point) division operator and the integer division operator.\n\n```antlr\nDivisionOperatorExpression\n    : FPDivisionOperatorExpression\n    | IntegerDivisionOperatorExpression\n    ;\n\nFPDivisionOperatorExpression\n    : Expression '/' LineTerminator? Expression\n    ;\n\nIntegerDivisionOperatorExpression\n    : Expression '\\\\' LineTerminator? Expression\n    ;\n```\n\nThe regular division operator is defined for the following types:\n\n* `Single` and `Double`. The quotient is computed according to the rules of IEEE 754 arithmetic.\n\n* `Decimal`. If the value of the right operand is zero, a `System.DivideByZeroException` exception is thrown. If the resulting value is too large to represent in the decimal format, a `System.OverflowException` exception is thrown. If the result value is too small to represent in the decimal format, the result is zero. The scale of the result, before any rounding, is the closest scale to the preferred scale which will preserve a result equal to the exact result.  The preferred scale is the scale of the first operand less the scale of the second operand.\n\nAccording to normal operator resolution rules, regular division purely between operands of types such as `Byte`, `Short`, `Integer`, and `Long` would cause both operands to be converted to type `Decimal`. However, when doing operator resolution on the division operator when neither type is `Decimal`, `Double` is considered narrower than `Decimal`. This convention is followed because `Double` division is more efficient than `Decimal` division.\n\n__Operation Type:__\n\n|        | __Bo__ | __SB__ | __By__ | __Sh__ | __US__ | __In__ | __UI__ | __Lo__ | __UL__ | __De__ | __Si__ | __Do__ | __Da__  | __Ch__  | __St__ | __Ob__ |\n|--------|----|----|----|----|----|----|----|----|----|----|----|----|-----|-----|-----|-----|\n| __Bo__ | Do | Do | Do | Do | Do | Do | Do | Do | Do | De | Si | Do | Err | Err | Do  | Ob  | \n| __SB__ |    | Do | Do | Do | Do | Do | Do | Do | Do | De | Si | Do | Err | Err | Do  | Ob  | \n| __By__ |    |    | Do | Do | Do | Do | Do | Do | Do | De | Si | Do | Err | Err | Do  | Ob  | \n| __Sh__ |    |    |    | Do | Do | Do | Do | Do | Do | De | Si | Do | Err | Err | Do  | Ob  | \n| __US__ |    |    |    |    | Do | Do | Do | Do | Do | De | Si | Do | Err | Err | Do  | Ob  | \n| __In__ |    |    |    |    |    | Do | Do | Do | Do | De | Si | Do | Err | Err | Do  | Ob  | \n| __UI__ |    |    |    |    |    |    | Do | Do | Do | De | Si | Do | Err | Err | Do  | Ob  | \n| __Lo__ |    |    |    |    |    |    |    | Do | Do | De | Si | Do | Err | Err | Do  | Ob  | \n| __UL__ |    |    |    |    |    |    |    |    | Do | De | Si | Do | Err | Err | Do  | Ob  | \n| __De__ |    |    |    |    |    |    |    |    |    | De | Si | Do | Err | Err | Do  | Ob  | \n| __Si__ |    |    |    |    |    |    |    |    |    |    | Si | Do | Err | Err | Do  | Ob  | \n| __Do__ |    |    |    |    |    |    |    |    |    |    |    | Do | Err | Err | Do  | Ob  | \n| __Da__ |    |    |    |    |    |    |    |    |    |    |    |    | Err | Err | Err | Err | \n| __Ch__ |    |    |    |    |    |    |    |    |    |    |    |    |     | Err | Err | Err | \n| __St__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     | Do  | Ob  | \n| __Ob__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     |     | Ob  | \n\nThe integer division operator is defined for `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, and `Long`. If the value of the right operand is zero, a `System.DivideByZeroException` exception is thrown. The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign, and zero or negative when the two operands have opposite signs. If the left operand is the maximum negative `SByte`, `Short`, `Integer`, or `Long`, and the right operand is `-1`, an overflow occurs; if integer overflow checking is on, a `System.OverflowException` exception is thrown. Otherwise, the overflow is not reported and the result is instead the value of the left operand.\n\n__Note.__ As the two operands for unsigned types will always be zero or positive, the result is always zero or positive.  As the result of the expression will always be less than or equal to the largest of the two operands, it is not possible for an overflow to occur.  As such integer overflow checking is not performed for integer divide with two unsigned integers. The result is the type as that of the left operand.\n\n\n__Operation Type:__\n\n|        | __Bo__ | __SB__ | __By__ | __Sh__ | __US__ | __In__ | __UI__ | __Lo__ | __UL__ | __De__ | __Si__ | __Do__ | __Da__  | __Ch__  | __St__ | __Ob__ |\n|--------|----|----|----|----|----|----|----|----|----|----|----|----|-----|-----|-----|-----|\n| __Bo__ | Sh | SB | Sh | Sh | In | In | Lo | Lo | Lo | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __SB__ |    | SB | Sh | Sh | In | In | Lo | Lo | Lo | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __By__ |    |    | By | Sh | US | In | UI | Lo | UL | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __Sh__ |    |    |    | Sh | In | In | Lo | Lo | Lo | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __US__ |    |    |    |    | US | In | UI | Lo | UL | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __In__ |    |    |    |    |    | In | Lo | Lo | Lo | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __UI__ |    |    |    |    |    |    | UI | Lo | UL | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __Lo__ |    |    |    |    |    |    |    | Lo | Lo | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __UL__ |    |    |    |    |    |    |    |    | UL | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __De__ |    |    |    |    |    |    |    |    |    | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __Si__ |    |    |    |    |    |    |    |    |    |    | Lo | Lo | Err | Err | Lo  | Ob  | \n| __Do__ |    |    |    |    |    |    |    |    |    |    |    | Lo | Err | Err | Lo  | Ob  | \n| __Da__ |    |    |    |    |    |    |    |    |    |    |    |    | Err | Err | Err | Err | \n| __Ch__ |    |    |    |    |    |    |    |    |    |    |    |    |     | Err | Err | Err | \n| __St__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     | Lo  | Ob  | \n| __Ob__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     |     | Ob  | \n\n\n### Mod Operator\n\nThe `Mod` (modulo) operator computes the remainder of the division between two operands.\n\n```antlr\nModuloOperatorExpression\n    : Expression 'Mod' LineTerminator? Expression\n    ;\n```\n\nThe `Mod` operator is defined for the following types:\n\n* `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong` and `Long`. The result of `x Mod y` is the value produced by `x - (x \\ y) * y`. If `y` is zero, a `System.DivideByZeroException` exception is thrown. The modulo operator never causes an overflow.\n\n* `Single` and `Double`. The remainder is computed according to the rules of IEEE 754 arithmetic.\n\n* `Decimal`. If the value of the right operand is zero, a `System.DivideByZeroException` exception is thrown. If the resulting value is too large to represent in the decimal format, a `System.OverflowException` exception is thrown. If the result value is too small to represent in the decimal format, the result is zero.\n\n__Operation Type:__\n\n|        | __Bo__ | __SB__ | __By__ | __Sh__ | __US__ | __In__ | __UI__ | __Lo__ | __UL__ | __De__ | __Si__ | __Do__ | __Da__  | __Ch__  | __St__ | __Ob__ |\n|--------|----|----|----|----|----|----|----|----|----|----|----|----|-----|-----|-----|-----|\n| __Bo__ | Sh | SB | Sh | Sh | In | In | Lo | Lo | De | De | Si | Do | Err | Err | Do  | Ob  | \n| __SB__ |    | SB | Sh | Sh | In | In | Lo | Lo | De | De | Si | Do | Err | Err | Do  | Ob  | \n| __By__ |    |    | By | Sh | US | In | UI | Lo | UL | De | Si | Do | Err | Err | Do  | Ob  | \n| __Sh__ |    |    |    | Sh | In | In | Lo | Lo | De | De | Si | Do | Err | Err | Do  | Ob  | \n| __US__ |    |    |    |    | US | In | UI | Lo | UL | De | Si | Do | Err | Err | Do  | Ob  | \n| __In__ |    |    |    |    |    | In | Lo | Lo | De | De | Si | Do | Err | Err | Do  | Ob  | \n| __UI__ |    |    |    |    |    |    | UI | Lo | UL | De | Si | Do | Err | Err | Do  | Ob  | \n| __Lo__ |    |    |    |    |    |    |    | Lo | De | De | Si | Do | Err | Err | Do  | Ob  | \n| __UL__ |    |    |    |    |    |    |    |    | UL | De | Si | Do | Err | Err | Do  | Ob  | \n| __De__ |    |    |    |    |    |    |    |    |    | De | Si | Do | Err | Err | Do  | Ob  | \n| __Si__ |    |    |    |    |    |    |    |    |    |    | Si | Do | Err | Err | Do  | Ob  | \n| __Do__ |    |    |    |    |    |    |    |    |    |    |    | Do | Err | Err | Do  | Ob  | \n| __Da__ |    |    |    |    |    |    |    |    |    |    |    |    | Err | Err | Err | Err | \n| __Ch__ |    |    |    |    |    |    |    |    |    |    |    |    |     | Err | Err | Err | \n| __St__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     | Do  | Ob  | \n| __Ob__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     |     | Ob  | \n\n\n### Exponentiation Operator\n\nThe exponentiation operator computes the first operand raised to the power of the second operand.\n\n```antlr\nExponentOperatorExpression\n    : Expression '^' LineTerminator? Expression\n    ;\n```\n\nThe exponentiation operator is defined for type `Double`. The value is computed according to the rules of IEEE 754 arithmetic.\n\n__Operation Type:__\n\n|        | __Bo__ | __SB__ | __By__ | __Sh__ | __US__ | __In__ | __UI__ | __Lo__ | __UL__ | __De__ | __Si__ | __Do__ | __Da__  | __Ch__  | __St__ | __Ob__ |\n|--------|----|----|----|----|----|----|----|----|----|----|----|----|-----|-----|-----|-----|\n| __Bo__ | Do | Do | Do | Do | Do | Do | Do | Do | Do | Do | Do | Do | Err | Err | Do  | Ob  | \n| __SB__ |    | Do | Do | Do | Do | Do | Do | Do | Do | Do | Do | Do | Err | Err | Do  | Ob  | \n| __By__ |    |    | Do | Do | Do | Do | Do | Do | Do | Do | Do | Do | Err | Err | Do  | Ob  | \n| __Sh__ |    |    |    | Do | Do | Do | Do | Do | Do | Do | Do | Do | Err | Err | Do  | Ob  | \n| __US__ |    |    |    |    | Do | Do | Do | Do | Do | Do | Do | Do | Err | Err | Do  | Ob  | \n| __In__ |    |    |    |    |    | Do | Do | Do | Do | Do | Do | Do | Err | Err | Do  | Ob  | \n| __UI__ |    |    |    |    |    |    | Do | Do | Do | Do | Do | Do | Err | Err | Do  | Ob  | \n| __Lo__ |    |    |    |    |    |    |    | Do | Do | Do | Do | Do | Err | Err | Do  | Ob  | \n| __UL__ |    |    |    |    |    |    |    |    | Do | Do | Do | Do | Err | Err | Do  | Ob  | \n| __De__ |    |    |    |    |    |    |    |    |    | Do | Do | Do | Err | Err | Do  | Ob  | \n| __Si__ |    |    |    |    |    |    |    |    |    |    | Do | Do | Err | Err | Do  | Ob  | \n| __Do__ |    |    |    |    |    |    |    |    |    |    |    | Do | Err | Err | Do  | Ob  | \n| __Da__ |    |    |    |    |    |    |    |    |    |    |    |    | Err | Err | Err | Err | \n| __Ch__ |    |    |    |    |    |    |    |    |    |    |    |    |     | Err | Err | Err | \n| __St__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     | Do  | Ob  | \n| __Ob__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     |     | Ob  | \n\n\n## Relational Operators\n\nThe *relational operators* compare values to one other. The comparison operators are `=`, `<>`, `<`, `>`, `<=`, and `>=`.\n\n```antlr\nRelationalOperatorExpression\n    : Expression '=' LineTerminator? Expression\n    | Expression '<' '>' LineTerminator? Expression\n    | Expression '<' LineTerminator? Expression\n    | Expression '>' LineTerminator? Expression\n    | Expression '<' '=' LineTerminator? Expression\n    | Expression '>' '=' LineTerminator? Expression\n    ;\n```\n\nAll of the relational operators result in a `Boolean` value.\n\nThe relational operators have the following general meaning:\n\n* The `=` operator tests whether the two operands are equal.\n\n* The `<>` operator tests whether the two operands are not equal.\n\n* The `<` operator tests whether the first operand is less than the second operand.\n\n* The `>` operator tests whether the first operand is greater than the second operand.\n\n* The `<=` operator tests whether the first operand is less than or equal to the second operand.\n\n* The `>=` operator tests whether the first operand is greater than or equal to the second operand.\n\nThe relational operators are defined for the following types:\n\n* `Boolean`. The operators compare the truth values of the two operands. `True` is considered to be less than `False`, which matches with their numeric values.\n\n* `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, and `Long`. The operators compare the numeric values of the two integral operands.\n\n* `Single` and `Double`. The operators compare the operands according to the rules of the IEEE 754 standard.\n\n* `Decimal`. The operators compare the numeric values of the two decimal operands.\n\n* `Date`. The operators return the result of comparing the two date/time values.\n\n* `Char`. The operators return the result of comparing the two Unicode values.\n\n* `String`. The operators return the result of comparing the two values using either a binary comparison or a text comparison. The comparison used is determined by the compilation environment and the `Option Compare` statement. A binary comparison determines whether the numeric Unicode value of each character in each string is the same. A text comparison does a Unicode text comparison based on the current culture in use on the .NET Framework. When doing a string comparison, a null value is equivalent to the string literal `\"\"`.\n\n__Operation Type:__\n        \n|        | __Bo__ | __SB__ | __By__ | __Sh__ | __US__ | __In__ | __UI__ | __Lo__ | __UL__ | __De__ | __Si__ | __Do__ | __Da__  | __Ch__  | __St__ | __Ob__ | \n|--------|----|----|----|----|----|----|----|----|----|----|----|----|-----|-----|----|----|\n| __Bo__ | Bo | SB | Sh | Sh | In | In | Lo | Lo | De | De | Si | Do | Err | Err | Bo | Ob | \n| __SB__ |    | SB | Sh | Sh | In | In | Lo | Lo | De | De | Si | Do | Err | Err | Do | Ob | \n| __By__ |    |    | By | Sh | US | In | UI | Lo | UL | De | Si | Do | Err | Err | Do | Ob | \n| __Sh__ |    |    |    | Sh | In | In | Lo | Lo | De | De | Si | Do | Err | Err | Do | Ob | \n| __US__ |    |    |    |    | US | In | UI | Lo | UL | De | Si | Do | Err | Err | Do | Ob | \n| __In__ |    |    |    |    |    | In | Lo | Lo | De | De | Si | Do | Err | Err | Do | Ob | \n| __UI__ |    |    |    |    |    |    | UI | Lo | UL | De | Si | Do | Err | Err | Do | Ob | \n| __Lo__ |    |    |    |    |    |    |    | Lo | De | De | Si | Do | Err | Err | Do | Ob | \n| __UL__ |    |    |    |    |    |    |    |    | UL | De | Si | Do | Err | Err | Do | Ob | \n| __De__ |    |    |    |    |    |    |    |    |    | De | Si | Do | Err | Err | Do | Ob | \n| __Si__ |    |    |    |    |    |    |    |    |    |    | Si | Do | Err | Err | Do | Ob | \n| __Do__ |    |    |    |    |    |    |    |    |    |    |    | Do | Err | Err | Do | Ob | \n| __Da__ |    |    |    |    |    |    |    |    |    |    |    |    | Da  | Err | Da | Ob | \n| __Ch__ |    |    |    |    |    |    |    |    |    |    |    |    |     | Ch  | St | Ob | \n| __St__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     | St | Ob | \n| __Ob__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     |    | Ob | \n\n\n## Like Operator\n\nThe `Like` operator determines whether a string matches a given pattern.\n\n```antlr\nLikeOperatorExpression\n    : Expression 'Like' LineTerminator? Expression\n    ;\n```\n\nThe `Like` operator is defined for the `String` type. The first operand is the string being matched, and the second operand is the pattern to match against. The pattern is made up of Unicode characters. The following character sequences have special meanings:\n\n* The character `?` matches any single character.\n\n* The character `*` matches zero or more characters.\n\n* The character `#` matches any single digit (0-9).\n\n* A list of characters surrounded by brackets (`[ab...]`) matches any single character in the list.\n\n* A list of characters surrounded by brackets and prefixed by an exclamation point (`[!ab...]`) matches any single character not in the character list.\n\n* Two characters in a character list separated by a hyphen (`-`) specify a range of Unicode characters starting with the first character and ending with the second character. If the second character is not later in the sort order than the first character, a run-time exception occurs. A hyphen that appears at the beginning or end of a character list specifies itself.\n\nTo match the special characters left bracket (`[`), question mark (`?`), number sign (`#`), and asterisk (`*`), brackets must enclose them. The right bracket (`]`) cannot be used within a group to match itself, but it can be used outside a group as an individual character. The character sequence `[]` is considered to be the string literal `\"\"`. \n\nNote that character comparisons and ordering for character lists are dependent on the type of comparisons being used. If binary comparisons are being used, character comparisons and ordering are based on the numeric Unicode values. If text comparisons are being used, character comparisons and ordering are based on the current locale being used on the .NET Framework.\n\nIn some languages, special characters in the alphabet represent two separate characters and vice versa. For example, several languages use the character `æ` to represent the characters `a` and `e` when they appear together, while the characters `^` and `O` can be used to represent the character `Ô`. When using text comparisons, the `Like` operator recognizes such cultural equivalences. In that case, an occurrence of the single special character in either pattern or string matches the equivalent two-character sequence in the other string. Similarly, a single special character in pattern enclosed in brackets (by itself, in a list, or in a range) matches the equivalent two-character sequence in the string and vice versa.\n\nIn a `Like` expression where both operands are `Nothing` or one operand has an intrinsic conversion to `String` and the other operand is `Nothing`, `Nothing` is treated as if it were the empty string literal `\"\"`.\n\n__Operation Type:__\n\n|        | __Bo__ | __SB__ | __By__ | __Sh__ | __US__ | __In__ | __UI__ | __Lo__ | __UL__ | __De__ | __Si__ | __Do__ | __Da__  | __Ch__  | __St__ | __Ob__ | \n|--------|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|\n| __Bo__ | St | St | St | St | St | St | St | St | St | St | St | St | St | St | St | Ob | \n| __SB__ |    | St | St | St | St | St | St | St | St | St | St | St | St | St | St | Ob | \n| __By__ |    |    | St | St | St | St | St | St | St | St | St | St | St | St | St | Ob | \n| __Sh__ |    |    |    | St | St | St | St | St | St | St | St | St | St | St | St | Ob | \n| __US__ |    |    |    |    | St | St | St | St | St | St | St | St | St | St | St | Ob | \n| __In__ |    |    |    |    |    | St | St | St | St | St | St | St | St | St | St | Ob | \n| __UI__ |    |    |    |    |    |    | St | St | St | St | St | St | St | St | St | Ob | \n| __Lo__ |    |    |    |    |    |    |    | St | St | St | St | St | St | St | St | Ob | \n| __UL__ |    |    |    |    |    |    |    |    | St | St | St | St | St | St | St | Ob | \n| __De__ |    |    |    |    |    |    |    |    |    | St | St | St | St | St | St | Ob | \n| __Si__ |    |    |    |    |    |    |    |    |    |    | St | St | St | St | St | Ob | \n| __Do__ |    |    |    |    |    |    |    |    |    |    |    | St | St | St | St | Ob | \n| __Da__ |    |    |    |    |    |    |    |    |    |    |    |    | St | St | St | Ob | \n| __Ch__ |    |    |    |    |    |    |    |    |    |    |    |    |    | St | St | Ob | \n| __St__ |    |    |    |    |    |    |    |    |    |    |    |    |    |    | St | Ob | \n| __Ob__ |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | Ob | \n\n\n## Concatenation Operator\n\n```antlr\nConcatenationOperatorExpression\n    : Expression '&' LineTerminator? Expression\n    ;\n```\n\nThe *concatenation operator* is defined for all of the intrinsic types, including the nullable versions of the intrinsic value types. It is also defined for concatenation between the types mentioned above and `System.DBNull`, which is treated as a `Nothing` string. The concatenation operator converts all of its operands to `String`; in the expression, all conversions to `String` are considered to be widening, regardless of whether strict semantics are used. A `System.DBNull` value is converted to the literal `Nothing` typed as `String`. A nullable value type whose value is `Nothing` is also converted to the literal `Nothing` typed as `String`, rather than throwing a run-time error.\n\nA concatenation operation results in a string that is the concatenation of the two operands in order from left to right. The value `Nothing` is treated as if it were the empty string literal `\"\"`.\n\n__Operation Type:__\n\n|        | __Bo__ | __SB__ | __By__ | __Sh__ | __US__ | __In__ | __UI__ | __Lo__ | __UL__ | __De__ | __Si__ | __Do__ | __Da__  | __Ch__  | __St__ | __Ob__ | \n|--------|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|----|\n| __Bo__ | St | St | St | St | St | St | St | St | St | St | St | St | St | St | St | Ob | \n| __SB__ |    | St | St | St | St | St | St | St | St | St | St | St | St | St | St | Ob | \n| __By__ |    |    | St | St | St | St | St | St | St | St | St | St | St | St | St | Ob | \n| __Sh__ |    |    |    | St | St | St | St | St | St | St | St | St | St | St | St | Ob | \n| __US__ |    |    |    |    | St | St | St | St | St | St | St | St | St | St | St | Ob | \n| __In__ |    |    |    |    |    | St | St | St | St | St | St | St | St | St | St | Ob | \n| __UI__ |    |    |    |    |    |    | St | St | St | St | St | St | St | St | St | Ob | \n| __Lo__ |    |    |    |    |    |    |    | St | St | St | St | St | St | St | St | Ob | \n| __UL__ |    |    |    |    |    |    |    |    | St | St | St | St | St | St | St | Ob | \n| __De__ |    |    |    |    |    |    |    |    |    | St | St | St | St | St | St | Ob | \n| __Si__ |    |    |    |    |    |    |    |    |    |    | St | St | St | St | St | Ob | \n| __Do__ |    |    |    |    |    |    |    |    |    |    |    | St | St | St | St | Ob | \n| __Da__ |    |    |    |    |    |    |    |    |    |    |    |    | St | St | St | Ob | \n| __Ch__ |    |    |    |    |    |    |    |    |    |    |    |    |    | St | St | Ob | \n| __St__ |    |    |    |    |    |    |    |    |    |    |    |    |    |    | St | Ob | \n| __Ob__ |    |    |    |    |    |    |    |    |    |    |    |    |    |    |    | Ob | \n\n\n## Logical Operators\n\nThe `And`, `Not`, `Or`, and `Xor` operators are called the logical operators.\n\n```antlr\nLogicalOperatorExpression\n    : 'Not' Expression\n    | Expression 'And' LineTerminator? Expression\n    | Expression 'Or' LineTerminator? Expression\n    | Expression 'Xor' LineTerminator? Expression\n    ;\n```\n\nThe logical operators are evaluated as follows:\n\n* For the `Boolean` type:\n\n  * A logical `And` operation is performed on its two operands.\n\n  * A logical `Not` operation is performed on its operand.\n\n  * A logical `Or` operation is performed on its two operands.\n\n  * A logical exclusive-`Or` operation is performed on its two operands.\n\n* For `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, `Long`, and all enumerated types, the specified operation is performed on each bit of the binary representation of the two operand(s):\n\n  * `And`: The result bit is 1 if both bits are 1; otherwise the result bit is 0.\n\n  * `Not`: The result bit is 1 if the bit is 0; otherwise the result bit is 1.\n\n  * `Or`: The result bit is 1 if either bit is 1; otherwise the result bit is 0.\n\n  * `Xor`: The result bit is 1 if either bit is 1 but not both bits; otherwise the result bit is 0 (that is, 1 `Xor` 0 = 1, 1 `Xor` 1 = 0).\n\n* When the logical operators `And` and `Or` are lifted for the type `Boolean?`, they are extended to encompass three-valued Boolean logic as such:\n\n  * `And` evaluates to true if both operands are true; false if one of the operands is false; `Nothing` otherwise.\n\n  * `Or` evaluates to true if either operand is true; false is both operands are false; `Nothing` otherwise.\n\nFor example:\n\n```vb\nModule Test\n    Sub Main()\n        Dim x?, y? As Boolean\n\n        x = Nothing\n        y = True \n\n        If x Or y Then\n            ' Will execute\n        End If\n    End Sub\nEnd Module\n```\n\n__Note.__ Ideally, the logical operators `And` and `Or` would be lifted using three-valued logic for any type that can be used in a Boolean expression (i.e. a type that implements `IsTrue` and `IsFalse`), in the same way that `AndAlso` and `OrElse` short circuit across any type that can be used in a Boolean expression. Unfortunately, three-valued lifting is only applied to `Boolean?`, so user-defined types that desire three-valued logic must do so manually by defining `And` and `Or` operators for their nullable version.\n\nNo overflows are possible from these operations. The enumerated type operators do the bitwise operation on the underlying type of the enumerated type, but the return value is the enumerated type.\n\n__Not Operation Type:__\n\n| __Bo__ | __SB__ | __By__ | __Sh__ | __US__ | __In__ | __UI__ | __Lo__ | __UL__ | __De__ | __Si__ | __Do__ | __Da__  | __Ch__  | __St__ | __Ob__ | \n|----|----|----|----|----|----|----|----|----|----|----|----|-----|-----|----|----|\n| Bo | SB | By | Sh | US | In | UI | Lo | UL | Lo | Lo | Lo | Err | Err | Lo | Ob | \n\n__And, Or, Xor Operation Type:__\n\n|        | __Bo__ | __SB__ | __By__ | __Sh__ | __US__ | __In__ | __UI__ | __Lo__ | __UL__ | __De__ | __Si__ | __Do__ | __Da__  | __Ch__  | __St__ | __Ob__ |\n|--------|----|----|----|----|----|----|----|----|----|----|----|----|-----|-----|-----|-----|\n| __Bo__ | Bo | SB | Sh | Sh | In | In | Lo | Lo | Lo | Lo | Lo | Lo | Err | Err | Bo  | Ob  | \n| __SB__ |    | SB | Sh | Sh | In | In | Lo | Lo | Lo | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __By__ |    |    | By | Sh | US | In | UI | Lo | UL | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __Sh__ |    |    |    | Sh | In | In | Lo | Lo | Lo | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __US__ |    |    |    |    | US | In | UI | Lo | UL | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __In__ |    |    |    |    |    | In | Lo | Lo | Lo | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __UI__ |    |    |    |    |    |    | UI | Lo | UL | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __Lo__ |    |    |    |    |    |    |    | Lo | Lo | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __UL__ |    |    |    |    |    |    |    |    | UL | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __De__ |    |    |    |    |    |    |    |    |    | Lo | Lo | Lo | Err | Err | Lo  | Ob  | \n| __Si__ |    |    |    |    |    |    |    |    |    |    | Lo | Lo | Err | Err | Lo  | Ob  | \n| __Do__ |    |    |    |    |    |    |    |    |    |    |    | Lo | Err | Err | Lo  | Ob  | \n| __Da__ |    |    |    |    |    |    |    |    |    |    |    |    | Err | Err | Err | Err | \n| __Ch__ |    |    |    |    |    |    |    |    |    |    |    |    |     | Err | Err | Err | \n| __St__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     | Lo  | Ob  | \n| __Ob__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     |     | Ob  | \n\n\n### Short-circuiting Logical Operators\n\nThe `AndAlso` and `OrElse` operators are the short-circuiting versions of the `And` and `Or` logical operators.\n\n```antlr\nShortCircuitLogicalOperatorExpression\n    : Expression 'AndAlso' LineTerminator? Expression\n    | Expression 'OrElse' LineTerminator? Expression\n    ;\n```\n\nBecause of their short circuiting behavior, the second operand is not evaluated at run time if the operator result is known after evaluating the first operand.\n\nThe short-circuiting logical operators are evaluated as follows:\n\n* If the first operand in an `AndAlso` operation evaluates to `False` or returns True from its `IsFalse` operator, the expression returns its first operand. Otherwise, the second operand is evaluated and a logical `And` operation is performed on the two results.\n\n* If the first operand in an `OrElse` operation evaluates to `True` or returns True from its `IsTrue` operator, the expression returns its first operand. Otherwise, the second operand is evaluated and a logical `Or` operation is performed on its two results.\n\nThe `AndAlso` and `OrElse` operators are defined for the type `Boolean`, or for any type `T` that overloads the following operators:\n\n```vb\nPublic Shared Operator IsTrue(op As T) As Boolean\nPublic Shared Operator IsFalse(op As T) As Boolean\n```\n\nas well as overloading the corresponding `And` or `Or` operator:\n\n```vb\nPublic Shared Operator And(op1 As T, op2 As T) As T\nPublic Shared Operator Or(op1 As T, op2 As T) As T\n```\n\nWhen evaluating the `AndAlso` or `OrElse` operators, the first operand is evaluated only once, and the second operand is either not evaluated or evaluated exactly once. For example, consider the following code:\n\n```vb\nModule Test\n    Function TrueValue() As Boolean\n        Console.Write(\" True\")\n        Return True\n    End Function\n\n    Function FalseValue() As Boolean\n        Console.Write(\" False\")\n        Return False\n    End Function\n\n    Sub Main()\n        Console.Write(\"And:\")\n        If FalseValue() And TrueValue() Then\n        End If\n        Console.WriteLine()\n\n        Console.Write(\"Or:\")\n        If TrueValue() Or FalseValue() Then\n        End If\n        Console.WriteLine()\n\n        Console.Write(\"AndAlso:\")\n        If FalseValue() AndAlso TrueValue() Then\n        End If\n        Console.WriteLine()\n\n        Console.Write(\"OrElse:\")\n        If TrueValue() OrElse FalseValue() Then\n        End If\n        Console.WriteLine()\n    End Sub\nEnd Module\n```\n\nIt prints the following result:\n\n```console\nAnd: False True\nOr: True False\nAndAlso: False\nOrElse: True\n```\n\nIn the lifted form of the `AndAlso` and `OrElse` operators, if the first operand was a null `Boolean?`, then the second operand is evaluated but the result is always a null `Boolean?`.\n\n__Operation Type:__\n\n|        | __Bo__ | __SB__ | __By__ | __Sh__ | __US__ | __In__ | __UI__ | __Lo__ | __UL__ | __De__ | __Si__ | __Do__ | __Da__  | __Ch__  | __St__ | __Ob__ |\n|--------|----|----|----|----|----|----|----|----|----|----|----|----|-----|-----|-----|-----|\n| __Bo__ | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Err | Err | Bo  | Ob  | \n| __SB__ |    | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Err | Err | Bo  | Ob  | \n| __By__ |    |    | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Err | Err | Bo  | Ob  | \n| __Sh__ |    |    |    | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Err | Err | Bo  | Ob  | \n| __US__ |    |    |    |    | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Err | Err | Bo  | Ob  | \n| __In__ |    |    |    |    |    | Bo | Bo | Bo | Bo | Bo | Bo | Bo | Err | Err | Bo  | Ob  | \n| __UI__ |    |    |    |    |    |    | Bo | Bo | Bo | Bo | Bo | Bo | Err | Err | Bo  | Ob  | \n| __Lo__ |    |    |    |    |    |    |    | Bo | Bo | Bo | Bo | Bo | Err | Err | Bo  | Ob  | \n| __UL__ |    |    |    |    |    |    |    |    | Bo | Bo | Bo | Bo | Err | Err | Bo  | Ob  | \n| __De__ |    |    |    |    |    |    |    |    |    | Bo | Bo | Bo | Err | Err | Bo  | Ob  | \n| __Si__ |    |    |    |    |    |    |    |    |    |    | Bo | Bo | Err | Err | Bo  | Ob  | \n| __Do__ |    |    |    |    |    |    |    |    |    |    |    | Bo | Err | Err | Bo  | Ob  | \n| __Da__ |    |    |    |    |    |    |    |    |    |    |    |    | Err | Err | Err | Err | \n| __Ch__ |    |    |    |    |    |    |    |    |    |    |    |    |     | Err | Err | Err | \n| __St__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     | Bo  | Ob  | \n| __Ob__ |    |    |    |    |    |    |    |    |    |    |    |    |     |     |     | Ob  | \n\n\n## Shift Operators\n\nThe binary operators `<<` and `>>` perform bit shifting operations.\n\n```antlr\nShiftOperatorExpression\n    : Expression '<' '<' LineTerminator? Expression\n    | Expression '>' '>' LineTerminator? Expression\n    ;\n```\n\nThe operators are defined for the `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong` and `Long` types. Unlike the other binary operators, the result type of a shift operation is determined as if the operator was a unary operator with just the left operand. The type of the right operand must be implicitly convertible to `Integer` and is not used in determining the result type of the operation.\n\nThe `<<` operator causes the bits in the first operand to be shifted left the number of places specified by the shift amount. The high-order bits outside the range of the result type are discarded and the low-order vacated bit positions are zero-filled.\n\nThe `>>` operator causes the bits in the first operand to be shifted right the number of places specified by the shift amount. The low-order bits are discarded and the high-order vacated bit positions are set to zero if the left operand is positive or to one if negative. If the left operand is of type `Byte`, `UShort`, `UInteger`, or `ULong` the vacant high-order bits are zero-filled.\n\nThe shift operators shift the bits of the underlying representation of the first operand by the amount of the second operand. If the value of the second operand is greater than the number of bits in the first operand, or is negative, then the shift amount is computed as `RightOperand And SizeMask` where `SizeMask` is:\n\n| __LeftOperand Type__  | __SizeMask__ | \n|-----------------------|--------------|\n| `Byte`, `SByte`       | 7 (`&H7`)    | \n| `UShort`, `Short`     | 15 (`&HF`)   | \n| `UInteger`, `Integer` | 31 (`&H1F`)  | \n| `ULong`, `Long`       | 63 (`&H3F`)  | \n\nIf the shift amount is zero, the result of the operation is identical to the value of the first operand. No overflows are possible from these operations.\n\n__Operation Type:__\n\n\n| __Bo__ | __SB__ | __By__ | __Sh__ | __US__ | __In__ | __UI__ | __Lo__ | __UL__ | __De__ | __Si__ | __Do__ | __Da__  | __Ch__  | __St__ | __Ob__ | \n|----|----|----|----|----|----|----|----|----|----|----|----|-----|-----|----|----|\n| Sh | SB | By | Sh | US | In | UI | Lo | UL | Lo | Lo | Lo | Err | Err | Lo | Ob | \n\n\n## Boolean Expressions\n\nA Boolean expression is an expression that can be tested to see if it is true or if it is false.\n\n```antlr\nBooleanExpression\n    : Expression\n    ;\n```\n\nA type `T` can be used in a Boolean expression if, in order of preference:\n\n* `T` is `Boolean` or `Boolean?`\n\n* `T` has a widening conversion to `Boolean`\n\n* `T` has a widening conversion to `Boolean?`\n\n* `T` defines two pseudo operators, `IsTrue` and `IsFalse`.\n\n* `T` has a narrowing conversion to `Boolean?` that does not involve a conversion from `Boolean` to `Boolean?`.\n\n* `T` has a narrowing conversion to `Boolean`.\n\n__Note.__ It is interesting to note that if `Option Strict` is off, an expression that has a narrowing conversion to `Boolean` will be accepted without a compile-time error but the language will still prefer an `IsTrue` operator if it exists. This is because `Option Strict` only changes what is and isn't accepted by the language, and never changes the actual meaning of an expression. Thus, `IsTrue` has to always be preferred over a narrowing conversion, regardless of `Option Strict`.\n\nFor example, the following class does not define a widening conversion to `Boolean`. As a result, its use in the `If` statement causes a call to the `IsTrue` operator.\n\n```vb\nClass MyBool\n    Public Shared Widening Operator CType(b As Boolean) As MyBool\n        ...\n    End Operator\n\n    Public Shared Narrowing Operator CType(b As MyBool) As Boolean\n        ...\n    End Operator\n\n    Public Shared Operator IsTrue(b As MyBool) As Boolean\n        ...\n    End Operator\n\n    Public Shared Operator IsFalse(b As MyBool) As Boolean\n        ...\n    End Operator\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim b As New MyBool\n\n        If b Then Console.WriteLine(\"True\")\n    End Sub\nEnd Module\n```\n\nIf a Boolean expression is typed as or converted to `Boolean` or `Boolean?`, then it is true if the value is `True` and false otherwise.\n\nOtherwise, a Boolean expression calls the `IsTrue` operator and returns `True` if the operator returned `True`; otherwise it is false (but never calls the `IsFalse` operator).\n\nIn the following example, `Integer` has a narrowing conversion to `Boolean`, so a null `Integer?` has a narrowing conversion to both `Boolean?` (yielding a null `Boolean`) and to `Boolean` (which throws an exception). The narrowing conversion to `Boolean?` is preferred, and so the value of \"`i`\" as a Boolean expression is therefore `False`.\n\n```vb\nDim i As Integer? = Nothing\nIf i Then Console.WriteLine()\n```\n\n\n## Lambda Expressions\n\nA *lambda expression* defines an anonymous method called a *lambda method*. Lambda methods make it easy to pass \"in-line\" methods to other methods that take delegate types.\n\n```antlr\nLambdaExpression\n    : SingleLineLambda\n    | MultiLineLambda\n    ;\n\nSingleLineLambda\n    : LambdaModifier* 'Function' ( OpenParenthesis ParameterList? CloseParenthesis )? Expression\n    | 'Sub' ( OpenParenthesis ParameterList? CloseParenthesis )? Statement\n    ;\n\nMultiLineLambda\n    : MultiLineFunctionLambda\n    | MultiLineSubLambda\n    ;\n\nMultiLineFunctionLambda\n    : LambdaModifier? 'Function' ( OpenParenthesis ParameterList? CloseParenthesis )? ( 'As' TypeName )? LineTerminator\n      Block\n      'End' 'Function'\n    ;\n\nMultiLineSubLambda\n    : LambdaModifier? 'Sub' ( OpenParenthesis ParameterList? CloseParenthesis )? LineTerminator\n      Block\n      'End' 'Sub'\n    ;\n\nLambdaModifier\n    : 'Async' | 'Iterator'\n    ;\n```\n\nThe example:\n\n```vb\nModule Test\n    Delegate Function IntFunc(x As Integer) As Integer\n\n    Sub Apply(a() As Integer, func As IntFunc)\n        For index As Integer = 0 To a.Length - 1\n            a(index) = func(a(index))\n        Next index\n    End Sub\n\n    Sub Main()\n        Dim a() As Integer = { 1, 2, 3, 4 }\n\n        Apply(a, Function(x As Integer) x * 2)\n\n        For Each value In a\n            Console.Write(value & \" \")\n        Next value\n    End Sub\nEnd Module\n```\n\nwill print out:\n\n```console\n2 4 6 8\n```\n\nA lambda expression begins with the optional modifiers `Async` or `Iterator`, followed by the keyword `Function` or `Sub` and a parameter list. Parameters in a lambda expression cannot be declared `Optional` or `ParamArray` and cannot have attributes. Unlike regular methods, omitting a parameter type for a lambda method does not automatically infer `Object`. Instead, when a lambda method is reclassified, the omitted parameter types and `ByRef` modifiers are inferred from the target type. In the previous example, the lambda expression could have been written as `Function(x) x * 2`, and it would have inferred the type of `x` to be `Integer` when the lambda method was used to create an instance of the `IntFunc` delegate type. Unlike local variable inference, if a lambda method parameter omits a type but has an array or nullable name modifier, a compile-time error occurs.\n\nA __regular lambda expression__ is one with neither `Async` nor `Iterator` modifiers.\n\nAn __iterator lambda expression__ is one with the `Iterator` modifier and no `Async` modifier. It must be a function. When it is reclassified to a value, it can only be reclassified to a value of delegate type whose return type is `IEnumerator`, or `IEnumerable`, or `IEnumerator(Of T)` or `IEnumerable(Of T)` for some `T`, and which has no ByRef parameters.\n\nAn __async lambda expression__ is one with the `Async` modifier and no `Iterator` modifier. An async sub lambda may only be reclassified to a value of sub delegate type with no ByRef parameters. An async function lambda may only be reclassified to a value of function delegate type whose return type is `Task` or `Task(Of T)` for some `T`, and which has no ByRef parameters.\n\nLambda expressions can either be single-line or multi-line. Single-line `Function` lambda expressions contain a single expression that represents the value returned from the lambda method. Single-line `Sub` lambda expressions contain a single statement without its closing `StatementTerminator`. For example:\n\n```vb\nModule Test\n    Sub Do(a() As Integer, action As Action(Of Integer))\n        For index As Integer = 0 To a.Length - 1\n            action(a(index))\n        Next index\n    End Sub\n\n    Sub Main()\n        Dim a() As Integer = { 1, 2, 3, 4 }\n\n        Do(a, Sub(x As Integer) Console.WriteLine(x))\n    End Sub\nEnd Module\n```\n\nSingle-line lambda constructs bind less tightly than all other expressions and statements. Thus, for example, \"`Function() x + 5`\" is equivalent to \"`Function() (x+5)\"` rather than \"`(Function() x) + 5`\". To avoid ambiguity, a single-line `Sub` lambda expression may not contain a Dim statement or a label declaration statement. Also, unless it is enclosed in parentheses, a single-line `Sub` lambda expression may not be immediately followed by a colon \":\", a member access operator \".\", a dictionary member access operator \"!\" or an open parenthesis \"(\". It may not contain any block statement (`With`, `SyncLock, If...EndIf`, `While`, `For`, `Do`, `Using`) nor `OnError` nor `Resume`.\n\n__Note.__ In the lambda expression `Function(i) x=i`, the body is interpreted as an *expression* (which tests whether `x` and `i` are equal). But in the lambda expression `Sub(i) x=i`, the body is interpreted as a statement (which assigns `i` to `x`).\n\nA multi-line lambda expression contains a statement block and must end with an appropriate `End` statement (i.e. `End Function` or `End Sub`). As with regular methods, a multi-line lambda method's `Function` or `Sub` statement and `End` statements must be on their own lines. For example:\n\n```vb\n' Error: Function statement must be on its own line!\nDim x = Sub(x As Integer) : Console.WriteLine(x) : End Sub\n\n' OK\nDim y = Sub(x As Integer)\n               Console.WriteLine(x)\n          End Sub\n```\n\nMulti-line `Function` lambda expressions can declare a return type but cannot put attributes on it. If a multi-line `Function` lambda expression does not declare a return type but the return type can be inferred from the context in which the lambda expression is used , then that return type is used. Otherwise the return type of the function is calculated as follows:\n\n* In a regular lambda expression, the return type is the dominant type of the expressions in all the `Return` statements in the statement block.\n\n* In an async lambda expression, the return type is `Task(Of T)` where `T` is the dominant type of the expressions in all the `Return` statements in the statement block.\n\n* In an iterator lambda expression, the return type is `IEnumerable(Of T)` where `T` is the dominant type of the expressions in all the `Yield` statements in the statement block.\n\nFor example:\n\n```vb\nFunction f(min As Integer, max As Integer) As IEnumerable(Of Integer)\n    If min > max Then Throw New ArgumentException()\n    Dim x = Iterator Function()\n                  For i = min To max\n                    Yield i\n                Next\n               End Function\n\n    ' infers x to be a delegate with return type IEnumerable(Of Integer)\n    Return x()\nEnd Function\n```\n\nIn all cases, if there are no `Return` (respectively `Yield`) statements, or if there is no dominant type among them, and strict semantics are being used, a compile-time error occurs; otherwise the dominant type is implicitly `Object`.\n\nNote that the return type is calculated from all `Return` statements, even if they are not reachable. For example:\n\n```vb\n' Return type is Double\nDim x = Function()\n              Return 10\n               Return 10.50\n          End Function\n```\n\nThere is no implicit return variable, as there is no name for the variable.\n\nThe statement blocks inside multi-line lambda expressions have the following restrictions:\n\n* `On Error` and `Resume` statements are not allowed, although `Try` statements are allowed.\n\n* Static locals cannot be declared in multi-line lambda expressions.\n\n* It is not possible to branch into or out of the statement block of a multi-line lambda expression, although the normal branching rules apply within it. For example:\n\n  ```vb\n  Label1:\n  Dim x = Sub()\n                 ' Error: Cannot branch out\n                 GoTo Label1\n\n                 ' OK: Wholly within the lamba.\n                 GoTo Label2:\n            Label2:\n            End Sub\n\n  ' Error: Cannot branch in\n  GoTo Label2\n  ```\n\nA lambda expression is roughly equivalent to an anonymous method declared on the containing type. The initial example is roughly equivalent to:\n\n```vb\nModule Test\n    Delegate Function IntFunc(x As Integer) As Integer\n\n    Sub Apply(a() As Integer, func As IntFunc)\n        For index As Integer = 0 To a.Length - 1\n            a(index) = func(a(index))\n        Next index\n    End Sub\n\n    Function $Lambda1(x As Integer) As Integer\n        Return x * 2\n    End Function\n\n    Sub Main()\n        Dim a() As Integer = { 1, 2, 3, 4 }\n\n        Apply(a, AddressOf $Lambda1)\n\n        For Each value In a\n            Console.Write(value & \" \")\n        Next value\n    End Sub\nEnd Module\n```\n\n\n### Closures\n\nLambda expressions have access to all of the variables in scope, including local variables or parameters defined in the containing method and lambda expressions. When a lambda expression refers to a local variable or parameter, the lambda expression captures the variable being referred to into a closure. A closure is an object that lives on the heap instead of on the stack, and when a variable is captured, all references to the variable are redirected to the closure. This enables lambda expressions to continue to refer to local variables and parameters even after the containing method is complete. For example:\n\n```vb\nModule Test\n    Delegate Function D() As Integer\n\n    Function M() As D\n        Dim x As Integer = 10\n        Return Function() x\n    End Function\n\n    Sub Main()\n        Dim y As D = M()\n\n        ' Prints 10\n        Console.WriteLine(y())\n    End Sub\nEnd Module\n```\n\nis roughly equivalent to:\n\n```vb\nModule Test\n    Delegate Function D() As Integer\n\n    Class $Closure1\n        Public x As Integer\n\n        Function $Lambda1() As Integer\n            Return x\n        End Function\n    End Class\n\n    Function M() As D\n        Dim c As New $Closure1()\n        c.x = 10\n        Return AddressOf c.$Lambda1\n    End Function\n\n    Sub Main()\n        Dim y As D = M()\n\n        ' Prints 10\n        Console.WriteLine(y())\n    End Sub\nEnd Module\n```\n\nA closure captures a new copy of a local variable each time it enters the block in which the local variable is declared, but the new copy is initialized with the value of the previous copy, if any. For example:\n\n```vb\nModule Test\n    Delegate Function D() As Integer\n\n    Function M() As D()\n        Dim a(9) As D\n\n        For i As Integer = 0 To 9\n            Dim x\n            a(i) = Function() x\n            x += 1\n        Next i\n\n        Return a\n    End Function\n\n    Sub Main()\n        Dim y() As D = M()\n\n        For i As Integer = 0 To 9\n            Console.Write(y(i)() & \" \")\n        Next i\n    End Sub\nEnd Module\n```\n\nprints\n\n```console\n1 2 3 4 5 6 7 8 9 10\n```\n\ninstead of\n\n```console\n9 9 9 9 9 9 9 9 9 9\n```\n\nBecause closures have to be initialized when entering a block, it is not allowed to `GoTo` into a block with a closure from outside of that block, although it is allowed to `Resume` into a block with a closure. For example:\n\n```vb\nModule Test\n    Sub Main()\n        Dim a = 10\n\n        If a = 10 Then\nL1:\n            Dim x = Function() a\n\n            ' Valid, source is within block\n            GoTo L2\nL2:\n        End If\n\n        ' ERROR: target is inside block with closure\n        GoTo L1\n    End Sub\nEnd Module\n```\n\nBecause they cannot be captured into a closure, the following cannot appear inside of a lambda expression:\n\n* Reference parameters.\n\n* Instance expressions (`Me`, `MyClass`, `MyBase`), if the type of `Me` is not a class.\n\nThe members of an anonymous type-creation expression, if the lambda expression is part of the expression. For example:\n\n```vb\n' Error: Lambda cannot refer to anonymous type field\nDim x = New With { .a = 12, .b = Function() .a }\n```\n\n`ReadOnly` instance variables in instance constructors or `ReadOnly` shared variables in shared constructors where the variables are used in a non-value context. For example:\n\n```vb\nClass C1\n    ReadOnly F1 As Integer\n\n    Sub New()\n        ' Valid, doesn't modify F1\n        Dim x = Function() F1\n\n        ' Error, tries to modify F1\n        Dim f = Function() ModifyValue(F1)\n    End Sub\n\n    Sub ModifyValue(ByRef x As Integer)\n    End Sub\nEnd Class\n```\n\n## Query Expressions\n\nA *query expression* is an expression that applies a series of *query operators* to the elements of a *queryable* collection. For example, the following expression takes a collection of `Customer` objects and returns the names of all the customers in the state of Washington:\n\n```vb\nDim names = _\n    From cust In Customers _\n    Where cust.State = \"WA\" _\n    Select cust.Name\n```\n\nA query expression must start with a `From` or an `Aggregate` operator and can end with any query operator. The result of a query expression is classified as a value; the result type of the expression depends on the result type of the last query operator in the expression.\n\n```antlr\nQueryExpression\n    : FromOrAggregateQueryOperator QueryOperator*\n    ;\n\nFromOrAggregateQueryOperator\n    : FromQueryOperator\n    | AggregateQueryOperator\n    ;\n\nQueryOperator\n    : FromQueryOperator\n    | AggregateQueryOperator\n    | SelectQueryOperator\n    | DistinctQueryOperator\n    | WhereQueryOperator\n    | OrderByQueryOperator\n    | PartitionQueryOperator\n    | LetQueryOperator\n    | GroupByQueryOperator\n    | JoinOrGroupJoinQueryOperator\n    ;\n\nJoinOrGroupJoinQueryOperator\n    : JoinQueryOperator\n    | GroupJoinQueryOperator\n    ;\n```\n\n### Range Variables\n\nSome query operators introduce a special kind of variable called a *range variable*. Range variables are not real variables; instead, they represent the individual values during the evaluation of the query over the input collections.\n\n```antlr\nCollectionRangeVariableDeclarationList\n    : CollectionRangeVariableDeclaration ( Comma CollectionRangeVariableDeclaration )*\n    ;\n\nCollectionRangeVariableDeclaration\n    : Identifier ( 'As' TypeName )? 'In' LineTerminator? Expression\n    ;\n\nExpressionRangeVariableDeclarationList\n    : ExpressionRangeVariableDeclaration ( Comma ExpressionRangeVariableDeclaration )*\n    ;\n\nExpressionRangeVariableDeclaration\n    : Identifier ( 'As' TypeName )? Equals Expression\n    ;\n```\n\nRange variables are scoped from the introducing query operator to the end of a query expression, or to a query operator such as `Select` that hides them. For example, in the following query\n\n```vb\nDim waCusts = _\n    From cust As Customer In Customers _\n    Where cust.State = \"WA\"\n```\n\nthe `From` query operator introduces a range variable `cust` typed as `Customer` that represents each customer in the `Customers` collection. The following `Where` query operator then refers to the range variable `cust` in the filter expression to determine whether to filter an individual customer out of the resulting collection.\n\nThere are two types of range variables: *collection range variables* and *expression range variables*. Collection range variables take their values from the elements of the collections being queried. The collection expression in a collection range variable declaration must be classified as a value whose type is queryable. If the type of a collection range variable is omitted, it is inferred to be the element type of the collection expression, or `Object` if the collection expression does not have an element type (i.e. only defines a `Cast` method). If the collection expression is not queryable (i.e. the element type of the collection cannot be inferred), a compile-time error results.\n\nAn expression range variable is a range variable whose value is calculated by an expression rather than a collection. In the following example, the `Select` query operator introduces an expression range variable named `cityState` calculated from two fields:\n\n```vb\nDim cityStates = _\n    From cust As Customer In Customers _\n    Select cityState = cust.City & \",\" & cust.State _\n    Where cityState.Length() < 10\n```\n\nAn expression range variable is not required to reference another range variable, although such a variable may be of dubious value. The expression assigned to an expression range variable must be classified as a value and must be implicitly convertible to the type of the range variable, if given.\n\nOnly in a Let operator may an expression range variable have its type specified. In other operators, or if its type is not specified, then local variable type inference is used to determine the type of the range variable.\n\nA range variable must follow the rules for declaring local variables in respect to shadowing. Thus, a range variable cannot hide the name of a local variable or parameter in the enclosing method or another range variable (unless the query operator specifically hides all current range variables in scope).\n\n\n### Queryable Types\n\nQuery expressions are implemented by translating the expression into calls to well-known methods on a collection type. These well-defined methods define the element type of the queryable collection as well as the result types of query operators executed on the collection. Each query operator specifies the method or methods that the query operator is generally translated into, although the specific translation is implementation dependent. The methods are given in the specification using a general format that looks like:\n\n```vb\nFunction Select(selector As Func(Of T, R)) As CR\n```\n\nThe following applies to the methods:\n\n* The method must be an instance or extension member of the collection type and must be accessible.\n\n* The method may be generic, provided that is possible to infer all type arguments.\n\n* The method may be overloaded, in which case overload resolution is used to determine the exactly method to use.\n\n* Another delegate type may be used in place of the delegate `Func` type, provided that it has the same signature, including return type, as the matching `Func` type.\n\n* The type `System.Linq.Expressions.Expression(Of D)` may be used in place of the delegate `Func` type, provided that `D` is a delegate type that has the same signature, including return type, as the matching `Func` type.\n\n* The type `T` represents the element type of the input collection. All of the methods defined by a collection type must have the same input element type for the collection type to be queryable.\n\n* The type `S` represents the element type of the second input collection in the case of query operators that perform joins.\n\n* The type `K` represents a key type in the case of query operators that have a set of range variables that act as keys.\n\n* The type `N` represents a type that is used as a numeric type (although it could still be a user-defined type and not an intrinsic numeric type).\n\n* The type `B` represents a type that can be used in a Boolean expression.\n\n* The type `R` represents the element type of the result collection, if the query operator produces a result collection. `R` depends on the number of range variables in scope at the conclusion of the query operator. If a single range variable is in scope, then `R` is the type of that range variable. In the example\n\n  ```vb\n  Dim custNames = From c In Customers\n                  Select c.Name\n  ```\n\n  the result of the query will be a collection type with an element type of `String`. If multiple range variables are in scope, then `R` is an anonymous type that contains all of the range variables in scope as `Key` fields. In the example:\n\n  ```vb\n  Dim custNames = From c In Customers, o In c.Orders \n                  Select Name = c.Name, ProductName = o.ProductName\n  ```\n\n  the result of the query will be a collection type with an element type of an anonymous type with a read-only property named `Name` of type `String` and a read-only property named `ProductName` of type `String`.\n\n  Within a query expression, anonymous types generated to contain range variables are *transparent*, which means that range variables are always available without qualification. For example, in the previous example the range variables `c` and `o` could be accessed without qualification in the `Select` query operator, even though the input collection's element type was an anonymous type.\n\n* The type `CX` represents a collection type, not necessarily the input collection type, whose element type is some type `X`.\n\nA queryable collection type must satisfy one of the following conditions, in order of preference:\n\n* It must define a conforming `Select` method.\n\n* It must have one of the following methods\n\n  ```vb\n  Function AsEnumerable() As CT\n  Function AsQueryable() As CT\n  ```\n\n  which can be called to obtain a queryable collection. If both methods are provided, `AsQueryable` is preferred over `AsEnumerable`.\n\n* It must have a method\n\n  ```vb\n  Function Cast(Of T)() As CT\n  ```\n\n  which can be called with the type of the range variable to produce a queryable collection.\n\nBecause determining the element type of a collection occurs independently of an actual method invocation, the applicability of specific methods cannot be determined. Thus, when determining the element type of a collection if there are instance methods that match well-known methods, then any extension methods that match well-known methods are ignored.\n\nQuery operator translation occurs in the order in which the query operators occur in the expression. It is not necessary for a collection object to implement all of the methods needed by all the query operators, although every collection object must at least support the `Select` query operator. If a needed method is not present, a compile-time error occurs. When binding well-known method names, non-methods are ignored for the purpose of multiple inheritance in interfaces and extension method binding, although shadowing semantics still apply. For example:\n\n```vb\nClass Q1\n    Public Function [Select](selector As Func(Of Integer, Integer)) As Q1\n    End Function\nEnd Class\n\nClass Q2\n    Inherits Q1\n\n    Public [Select] As Integer\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim qs As New Q2()\n\n        ' Error: Q2.Select still hides Q1.Select\n        Dim zs = From q In qs Select q\n    End Sub\nEnd Module\n```\n\n### Default Query Indexer\n\nEvery queryable collection type whose element type is `T` and does not already have a default property is considered to have a default property of the following general form:\n\n```vb\nPublic ReadOnly Default Property Item(index As Integer) As T\n    Get\n        Return Me.ElementAtOrDefault(index)\n    End Get\nEnd Property\n```\n\nThe default property can only be referred to using the default property access syntax; the default property cannot be referred to by name. For example:\n\n```vb\nDim customers As IEnumerable(Of Customer) = ...\nDim customerThree = customers(2)\n\n' Error, no such property\nDim customerFour = customers.Item(4)\n```\n\nIf the collection type does not have an `ElementAtOrDefault` member, a compile-time error will occur.\n\n### From Query Operator\n\nThe `From` query operator introduces a collection range variable that represents the individual members of a collection to be queried.\n\n```antlr\nFromQueryOperator\n    : LineTerminator? 'From' LineTerminator? CollectionRangeVariableDeclarationList\n    ;\n```\n\nFor example, the query expression:\n\n```vb\nFrom c As Customer In Customers ...\n```\n\ncan be thought of as equivalent to\n\n```vb\nFor Each c As Customer In Customers\n        ...\nNext c\n```\n\nWhen a `From` query operator declares multiple collection range variables or is not the first `From` query operator in the query expression, each new collection range variable is *cross joined* to the existing set of range variables. The result is that the query is evaluated over the cross-product of all the elements in the joined collections. For example, the expression:\n\n```vb\nFrom c In Customers _\nFrom e In Employees _\n...\n```\n\ncan be thought of as equivalent to:\n\n```vb\nFor Each c In Customers\n    For Each e In Employees\n            ...\n    Next e\nNext c\n```\n\nand is exactly equivalent to:\n\n```vb\nFrom c In Customers, e In Employees ...\n```\n\nThe range variables introduced in previous query operators can be used in a later `From` query operator. For example, in the following query expression the second `From` query operator refers to the value of the first range variable:\n\n```vb\nFrom c As Customer In Customers _\nFrom o As Order In c.Orders _\nSelect c.Name, o\n```\n\nMultiple range variables in a `From` query operator or multiple `From` query operators are only supported if the collection type contains one or both of the following methods:\n\n```vb\nFunction SelectMany(selector As Func(Of T, CR)) As CR\nFunction SelectMany(selector As Func(Of T, CS), _\n                          resultsSelector As Func(Of T, S, R)) As CR\n```\n\nThe code\n\n```vb\nDim xs() As Integer = ...\nDim ys() As Integer = ...\nDim zs = From x In xs, y In ys ...\n```\n\nis generally translated to\n\n```vb\nDim xs() As Integer = ...\nDim ys() As Integer = ...\nDim zs = _\n    xs.SelectMany( _\n        Function(x As Integer) ys, _\n        Function(x As Integer, y As Integer) New With {x, y})...\n```\n\n__Note.__ `From` is not a reserved word.\n\n\n### Join Query Operator\n\nThe `Join` query operator joins existing range variables with a new collection range variable, producing a single collection whose elements have been joined together based on an equality expression.\n\n```antlr\nJoinQueryOperator\n    : LineTerminator? 'Join' LineTerminator? CollectionRangeVariableDeclaration\n      JoinOrGroupJoinQueryOperator? LineTerminator? 'On' LineTerminator? JoinConditionList\n    ;\n\nJoinConditionList\n    : JoinCondition ( 'And' LineTerminator? JoinCondition )*\n    ;\n\nJoinCondition\n    : Expression 'Equals' LineTerminator? Expression\n    ;\n```\n\nFor example:\n\n```vb\nDim customersAndOrders = _\n    From cust In Customers _\n    Join ord In Orders On cust.ID Equals ord.CustomerID\n```\n\nThe equality expression is more restricted than a regular equality expression:\n\n* Both expressions must be classified as a value.\n\n* Both expressions must reference at least one range variable.\n\n* The range variable declared in the join query operator must be referenced by one of the expressions, and that expression must not reference any other range variables.\n\nIf the types of the two expressions are not the exact same type, then\n\n* If the equality operator is defined for the two types, both expressions are implicitly convertible to it, and it is not `Object`, then convert both expressions to that type.\n\n* Otherwise, if there is a dominant type that both expressions can be implicitly converted to, then convert both expressions to that type.\n\n* Otherwise, a compile-time error occurs.\n\nThe expressions are compared using hash values (i.e. by calling `GetHashCode()`) rather than by using equality operators for efficiency. A `Join` query operator may do multiple joins or equality conditions in the same operator. A `Join` query operator is only supported if the collection type contains a method:\n\n```vb\nFunction Join(inner As CS, _\n                  outerSelector As Func(Of T, K), _\n                  innerSelector As Func(Of S, K), _\n                  resultSelector As Func(Of T, S, R)) As CR\n```\n\nThe code\n\n```vb\nDim xs() As Integer = ...\nDim ys() As Integer = ...\nDim zs = From x In xs _\n            Join y In ys On x Equals y _\n            ...\n```\n\nis generally translated to\n\n```vb\nDim xs() As Integer = ...\nDim ys() As Integer = ...\nDim zs = _\n    xs.Join( _\n        ys, _\n        Function(x As Integer) x, _\n        Function(y As Integer) y, _\n        Function(x As Integer, y As Integer) New With {x, y})...\n```\n\n__Note.__ `Join`, `On` and `Equals` are not reserved words.\n\n\n### Let Query Operator\n\nThe `Let` query operator introduces an expression range variable. This allows calculating an intermediate value once that will be used multiple times in later query operators.\n\n```antlr\nLetQueryOperator\n    : LineTerminator? 'Let' LineTerminator? ExpressionRangeVariableDeclarationList\n    ;\n```\n\nFor example:\n\n```vb\nDim taxedPrices = _\n    From o In Orders _\n    Let tax = o.Price * 0.088 _\n    Where tax > 3.50 _\n    Select o.Price, tax, total = o.Price + tax\n```\n\ncan be thought of as equivalent to:\n\n```vb\nFor Each o In Orders\n    Dim tax = o.Price * 0.088\n    ...\nNext o\n```\n\nA `Let` query operator is only supported if the collection type contains a method:\n\n```vb\nFunction Select(selector As Func(Of T, R)) As CR\n```\n\nThe code\n\n```vb\nDim xs() As Integer = ...\nDim zs = From x In xs _\n            Let y = x * 10 _\n            ...\n```\n\nis generally translated to\n\n```vb\nDim xs() As Integer = ...\nDim zs = _\n    xs.Select(Function(x As Integer) New With {x, .y = x * 10})...\n```\n\n\n### Select Query Operator\n\nThe `Select` query operator is like the `Let` query operator in that it introduces expression range variables; however, a `Select` query operator hides the currently available range variables instead of adding to them. Also, the type of an expression range variable introduced by a `Select` query operator is always inferred using local variable type inference rules; an explicit type cannot be specified, and if no type can be inferred, a compile-time error occurs.\n\n```antlr\nSelectQueryOperator\n    : LineTerminator? 'Select' LineTerminator? ExpressionRangeVariableDeclarationList\n    ;\n```\n\nFor example, in the query:\n\n```vb\nDim smiths = _\n    From cust In Customers _\n    Select name = cust.name _\n    Where name.EndsWith(\"Smith\")\n```\n\nthe `Where` query operator only has access to the `name` range variable introduced by the `Select` operator; if the `Where` operator had tried to reference `cust`, a compile-time error would have occurred.\n\nInstead of explicitly specifying the names of the range variables, a `Select` query operator can infer the names of the range variables, using the same rules as anonymous type object creation expressions. For example:\n\n```vb\nDim custAndOrderNames = _\n      From cust In Customers, ord In cust.Orders _\n      Select cust.name, ord.ProductName _\n        Where name.EndsWith(\"Smith\")\n```\n\nIf the name of the range variable is not supplied and a name cannot be inferred, a compile-time error occurs. If the `Select` query operator contains only a single expression, no error occurs if a name for that range variable cannot be inferred but the range variable is nameless.  For example:\n\n```vb\nDim custAndOrderNames = _\n      From cust In Customers, ord In cust.Orders _\n      Select cust.Name & \" bought \" & ord.ProductName _\n        Take 10\n```\n\nIf there is an ambiguity in a `Select` query operator between assigning a name to a range variable and an equality expression, the name assignment is preferred. For example:\n\n```vb\nDim badCustNames = _\n      From c In Customers _\n        Let name = \"John Smith\" _\n      Select name = c.Name ' Creates a range variable named \"name\"\n\n\nDim goodCustNames = _\n      From c In Customers _\n        Let name = \"John Smith\" _\n      Select match = (name = c.Name)\n```\n\nEach expression in the `Select` query operator must be classified as a value. A `Select` query operator is supported only if the collection type contains a method:\n\n```vb\nFunction Select(selector As Func(Of T, R)) As CR\n```\n\nThe code\n\n```vb\nDim xs() As Integer = ...\nDim zs = From x In xs _\n            Select x, y = x * 10 _\n            ...\n```\n\nis generally translated to\n\n```vb\nDim xs() As Integer = ...\nDim zs = _\n    xs.Select(Function(x As Integer) New With {x, .y = x * 10})...\n```\n\n\n### Distinct Query Operator\n\nThe `Distinct` query operator restricts the values in a collection only to those with distinct values, as determined by comparing the element type for equality.\n\n```antlr\nDistinctQueryOperator\n    : LineTerminator? 'Distinct' LineTerminator?\n    ;\n```\n\nFor example, the query:\n\n```vb\nDim distinctCustomerPrice = _\n    From cust In Customers, ord In cust.Orders _\n    Select cust.Name, ord.Price _\n    Distinct\n```\n\nwill only return one row for each distinct pairing of customer name and order price, even if the customer has multiple orders with the same price. A `Distinct` query operator is supported only if the collection type contains a method:\n\n```vb\nFunction Distinct() As CT\n```\n\nThe code\n\n```vb\nDim xs() As Integer = ...\nDim zs = From x In xs _\n            Distinct _\n            ...\n```\n\nis generally translated to\n\n```vb\nDim xs() As Integer = ...\nDim zs = xs.Distinct()...\n```\n\n__Note.__ `Distinct` is not a reserved word.\n\n\n### Where Query Operator\n\nThe `Where` query operator restricts the values in a collection to those that satisfy a given condition.\n\n```antlr\nWhereQueryOperator\n    : LineTerminator? 'Where' LineTerminator? BooleanExpression\n    ;\n```\n\nA `Where` query operator takes a Boolean expression that is evaluated for each set of range variable values; if the value of the expression is true, then the values appear in the output collection, otherwise the values are skipped. For example, the query expression:\n\n```vb\nFrom cust In Customers, ord In Orders _\nWhere cust.ID = ord.CustomerID _\n...\n```\n\ncan be thought of as equivalent to the nested loop\n\n```vb\nFor Each cust In Customers\n    For Each ord In Orders\n            If cust.ID = ord.CustomerID Then\n                ...\n            End If\n    Next ord\nNext cust\n```\n\nA `Where` query operator is supported only if the collection type contains a method:\n\n```vb\nFunction Where(predicate As Func(Of T, B)) As CT\n```\n\nThe code\n\n```vb\nDim xs() As Integer = ...\nDim zs = From x In xs _\n            Where x < 10 _\n            ...\n```\n\nis generally translated to\n\n```vb\nDim xs() As Integer = ...\nDim zs = _\n    xs.Where(Function(x As Integer) x < 10)...\n```\n\n__Note.__ `Where` is not a reserved word.\n\n\n### Partition Query Operators\n\n```antlr\nPartitionQueryOperator\n    : LineTerminator? 'Take' LineTerminator? Expression\n    | LineTerminator? 'Take' 'While' LineTerminator? BooleanExpression\n    | LineTerminator? 'Skip' LineTerminator? Expression\n    | LineTerminator? 'Skip' 'While' LineTerminator? BooleanExpression\n    ;\n```\n\nThe `Take` query operator results in the first `n` elements of a collection. When used with the `While` modifier, the `Take` operator results in the first `n` elements of a collection that satisfy a Boolean expression. The `Skip` operator skips the first `n` elements of a collection and then returns the remainder of the collection.  When used in conjunction with the `While` modifier, the `Skip` operator skips the first `n` elements of a collection that satisfy a Boolean expression and then returns the rest of the collection. The expressions in a `Take` or `Skip` query operator must be classified as a value.\n\nA `Take` query operator is supported only if the collection type contains a method:\n\n```vb\nFunction Take(count As N) As CT\n```\n\nA `Skip` query operator is supported only if the collection type contains a method:\n\n```vb\nFunction Skip(count As N) As CT\n```\n\nA `Take While` query operator is supported only if the collection type contains a method:\n\n```vb\nFunction TakeWhile(predicate As Func(Of T, B)) As CT\n```\n\nA `Skip While` query operator is supported only if the collection type contains a method:\n\n```vb\nFunction SkipWhile(predicate As Func(Of T, B)) As CT\n```\n\nThe code\n\n```vb\nDim xs() As Integer = ...\nDim zs = From x In xs _\n            Skip 10 _\n            Take 5 _\n            Skip While x < 10 _\n            Take While x > 5 _\n            ...\n```\n\nis generally translated to\n\n```vb\nDim xs() As Integer = ...\nDim zs = _\n    xs.Skip(10). _\n        Take(5). _\n        SkipWhile(Function(x) x < 10). _\n        TakeWhile(Function(x) x > 5)...\n```\n\n__Note.__ `Take` and `Skip` are not reserved words.\n\n\n### Order By Query Operator\n\nThe `Order By` query operator orders the values that appear in the range variables. \n\n```antlr\nOrderByQueryOperator\n    : LineTerminator? 'Order' 'By' LineTerminator? OrderExpressionList\n    ;\n\nOrderExpressionList\n    : OrderExpression ( Comma OrderExpression )*\n    ;\n\nOrderExpression\n    : Expression Ordering?\n    ;\n\nOrdering\n    : 'Ascending' | 'Descending'\n    ;\n```\n\nAn `Order By` query operator takes expressions that specify the key values that should be used to order the iteration variables. For example, the following query returns products sorted by price:\n\n```vb\nDim productsByPrice = _\n    From p In Products _\n    Order By p.Price _\n    Select p.Name\n```\n\nAn ordering can be marked as `Ascending`, in which case smaller values come before larger values, or `Descending`, in which case larger values come before smaller values. The default for an ordering if none is specified is `Ascending`. For example, the following query returns products sorted by price with the most expensive product first:\n\n```vb\nDim productsByPriceDesc = _\n    From p In Products _\n    Order By p.Price Descending _\n    Select p.Name\n```\n\nThe `Order By` query operator may specify multiple expressions for ordering, in which case the collection is ordered in a nested manner. For example, the following query orders customers by state, then by city within each state and then by ZIP code within each city:\n\n```vb\nDim customersByLocation = _\n    From c In Customers _\n    Order By c.State, c.City, c.ZIP _\n    Select c.Name, c.State, c.City, c.ZIP\n```\n\nThe expressions in an `Order By` query operator must be classified as a value. An `Order By` query operator is supported only if the collection type contains one or both of the following methods:\n\n```vb\nFunction OrderBy(keySelector As Func(Of T, K)) As CT\nFunction OrderByDescending(keySelector As Func(Of T, K)) As CT\n```\n\nThe return type `CT` must be an *ordered collection*. An ordered collection is a collection type that contains one or both of the methods:\n\n```vb\nFunction ThenBy(keySelector As Func(Of T, K)) As CT\nFunction ThenByDescending(keySelector As Func(Of T, K)) As CT\n```\n\nThe code\n\n```vb\nDim xs() As Integer = ...\nDim zs = From x In xs _\n            Order By x Ascending, x Mod 2 Descending _\n            ...\n```\n\nis generally translated to\n\n```vb\nDim xs() As Integer = ...\nDim zs = _\n    xs.OrderBy(Function(x) x).ThenByDescending(Function(x) x Mod 2)...\n```\n\n__Note.__ Because query operators simply map syntax to methods that implement a particular query operation, order preservation is not dictated by the language and is determined by the implementation of the operator itself. This is very similar to user-defined operators in that the implementation to overload the addition operator for a user-defined numeric type may not perform anything resembling an addition. Of course, to preserve predictability, implementing something that does not match user expectations is not recommended.\n\n__Note.__ `Order` and `By` are not reserved words.\n\n\n### Group By Query Operator\n\nThe `Group By` query operator groups the range variables in scope based on one or more expressions, and then produces new range variables based on those groupings.\n\n```antlr\nGroupByQueryOperator\n    : LineTerminator? 'Group' ( LineTerminator? ExpressionRangeVariableDeclarationList )?\n      LineTerminator? 'By' LineTerminator? ExpressionRangeVariableDeclarationList\n      LineTerminator? 'Into' LineTerminator? ExpressionRangeVariableDeclarationList\n    ;\n```\n\nFor example, the following query groups all customers by `State`, and then computes the count and average age of each group:\n\n```vb\nDim averageAges = _\n    From cust In Customers _\n    Group By cust.State _\n    Into Count(), Average(cust.Age)\n```\n\nThe `Group By` query operator has three clauses: the optional `Group` clause, the `By` clause, and the `Into` clause. The `Group` clause has the same syntax and effect as a `Select` query operator, except that it only affects the range variables available in the `Into` clause and not the `By` clause. For example:\n\n```vb\nDim averageAges = _\n    From cust In Customers _\n    Group cust.Age By cust.State _\n    Into Count(), Average(Age)\n```\n\nThe `By` clause declares expression range variables that are used as key values in the grouping operation. The `Into` clause allows the declaration of expression range variables that calculate aggregations over each of the groups formed by the `By` clause. Within the `Into` clause, the expression range variable can only be assigned an expression which is a method invocation of an *aggregate function*. An aggregate function is a function on the collection type of the group (which may not necessarily be the same collection type of the original collection) which looks like either of the following methods:\n\n```vb\nFunction _name_() As _type_\nFunction _name_(selector As Func(Of T, R)) As R\n```\n\nIf an aggregate function takes a delegate argument, then the invocation expression can have an argument expression that must be classified as a value.  The argument expression can use the range variables that are in scope; within the call to an aggregate function, those range variables represent the values in the group being formed, not all of the values in the collection. For example, in the original example in this section the `Average` function calculates the average of the customers' ages per state rather than for all of the customers together.\n\nAll collection types are considered to have the aggregate function `Group` defined on it, which takes no parameters and simply returns the group. Other standard aggregate functions that a collection type may provide are:\n\n`Count` and `LongCount`, which return the count of the elements in the group or the count of the elements in the group that satisfy a Boolean expression. `Count` and `LongCount` are supported only if the collection type contains one of the methods:\n\n```vb\nFunction Count() As N\nFunction Count(selector As Func(Of T, B)) As N\nFunction LongCount() As N\nFunction LongCount(selector As Func(Of T, B)) As N\n```\n\n`Sum`, which returns the sum of an expression across all the elements in the group. `Sum` is supported only if the collection type contains one of the methods:\n\n```vb\nFunction Sum() As N\nFunction Sum(selector As Func(Of T, N)) As N\n```\n\n`Min` which returns the minimum value of an expression across all the elements in the group. `Min` is supported only if the collection type contains one of the methods:\n\n```vb\nFunction Min() As N\nFunction Min(selector As Func(Of T, N)) As N\n```\n\n`Max`, which returns the maximum value of an expression across all the elements in the group. `Max` is supported only if the collection type contains one of the methods:\n\n```vb\nFunction Max() As N\nFunction Max(selector As Func(Of T, N)) As N\n```\n\n`Average`, which returns the average of an expression across all the elements in the group. `Average` is supported only if the collection type contains one of the methods:\n\n```vb\nFunction Average() As N\nFunction Average(selector As Func(Of T, N)) As N\n```\n\n`Any`, which determines whether a group contains members or if a Boolean expression is true for any element in the group. `Any` returns a value that can be used in a Boolean expression and is supported only if the collection type contains one of the methods:\n\n```vb\nFunction Any() As B\nFunction Any(predicate As Func(Of T, B)) As B\n```\n\n`All`, which determines whether a Boolean expression is true for all elements in the group. `All` returns a value that can be used in a Boolean expression and is supported only if the collection type contains a method:\n\n```vb\nFunction All(predicate As Func(Of T, B)) As B\n```\n\nAfter a `Group By` query operator, the range variables previously in scope are hidden, and the range variables introduced by the `By` and `Into` clauses are available. A `Group By` query operator is supported only if the collection type contains the method:\n\n```vb\nFunction GroupBy(keySelector As Func(Of T, K), _\n                      resultSelector As Func(Of K, CT, R)) As CR\n```\n\nRange variable declarations in the `Group` clause are supported only if the collection type contains the method:\n\n```vb\nFunction GroupBy(keySelector As Func(Of T, K), _\n                      elementSelector As Func(Of T, S), _\n                      resultSelector As Func(Of K, CS, R)) As CR\n```\n\nThe code\n\n```vb\nDim xs() As Integer = ...\nDim zs = From x In xs _\n            Group y = x * 10, z = x / 10 By evenOdd = x Mod 2 _\n            Into Sum(y), Average(z) _\n            ...\n```\n\nis generally translated to\n\n```vb\nDim xs() As Integer = ...\nDim zs = _\n    xs.GroupBy( _\n        Function(x As Integer) x Mod 2, _\n        Function(x As Integer) New With {.y = x * 10, .z = x / 10}, _\n        Function(evenOdd, group) New With { _\n            evenOdd, _\n            .Sum = group.Sum(Function(e) e.y), _\n            .Average = group.Average(Function(e) e.z)})...\n```\n\n__Note.__ `Group`, `By`, and `Into` are not reserved words.\n\n\n### Aggregate Query Operator\n\nThe `Aggregate` query operator performs a similar function as the `Group By` operator, except it allows aggregating over groups that have already been formed. Because the group has already been formed, the `Into` clause of an `Aggregate` query operator does not hide the range variables in scope (in this way, `Aggregate` is more like a `Let`, and `Group By` is more like a `Select`).\n\n```antlr\nAggregateQueryOperator\n    : LineTerminator? 'Aggregate' LineTerminator? CollectionRangeVariableDeclaration QueryOperator*\n      LineTerminator? 'Into' LineTerminator? ExpressionRangeVariableDeclarationList\n    ;\n```\n\nFor example, the following query aggregates the total of all the orders placed by customers in Washington:\n\n```vb\nDim orderTotals = _\n    From cust In Customers _\n    Where cust.State = \"WA\" _\n    Aggregate order In cust.Orders _\n    Into Sum(order.Total)\n```\n\nThe result of this query is a collection whose element type is an anonymous type with a property named `cust` typed as `Customer` and a property named `Sum` typed as `Integer`.\n\nUnlike `Group By`, additional query operators can be placed between the `Aggregate` and `Into` clauses. Between an `Aggregate` clause and the end of the `Into` clause, all range variables in scope, including those declared by the `Aggregate` clause can be used. For example, the following query aggregates the sum total of all the orders placed by customers in Washington before 2006:\n\n```vb\nDim orderTotals = _\n    From cust In Customers _\n    Where cust.State = \"WA\" _\n    Aggregate order In cust.Orders _\n    Where order.Date <= #01/01/2006# _\n    Into Sum = Sum(order.Total)\n```\n\nThe `Aggregate` operator can also be used to start a query expression. In this case, the result of the query expression will be the single value computed by the `Into` clause. For example, the following query calculates the sum of all the order totals before January 1st, 2006:\n\n```vb\nDim ordersTotal = _\n    Aggregate order In Orders _\n    Where order.Date <= #01/01/2006# _\n    Into Sum(order.Total)\n```\n\nThe result of the query is a single `Integer` value. An `Aggregate` query operator is always available (although the aggregate function must be also be available for the expression to be valid). The code\n\n```vb\nDim xs() As Integer = ...\nDim zs = _\n    Aggregate x In xs _\n    Where x < 5 _\n    Into Sum()\n```\n\nis generally translated to\n\n```vb\nDim xs() As Integer = ...\nDim zs = _\n    xs.Where(Function(x) x < 5).Sum()\n```\n\n__Note.__ `Aggregate` and `Into` are not reserved words.\n\n\n### Group Join Query Operator\n\nThe `Group Join` query operator combines the functions of the `Join` and `Group By` query operators into a single operator. `Group Join` joins two collections based on matching keys extracted from the elements, grouping together all of the elements on the right side of the join that match a particular element on the left side of the join. Thus, the operator produces a set of hierarchical results.\n\n```antlr\nGroupJoinQueryOperator\n    : LineTerminator? 'Group' 'Join' LineTerminator? CollectionRangeVariableDeclaration\n      JoinOrGroupJoinQueryOperator? LineTerminator? 'On' LineTerminator? JoinConditionList\n      LineTerminator? 'Into' LineTerminator? ExpressionRangeVariableDeclarationList\n    ;\n```\n\nFor example, the following query produces elements that contain a single customer's name, a group of all of their orders, and the total amount of all of those orders:\n\n```vb\nDim custsWithOrders = _\n    From cust In Customers _\n    Group Join order In Orders On cust.ID Equals order.CustomerID _ \n    Into Orders = Group, OrdersTotal = Sum(order.Total) _\n    Select cust.Name, Orders, OrdersTotal\n```\n\nThe result of the query is a collection whose element type is an anonymous type with three properties: `Name`, typed as `String`, `Orders` typed as a collection whose element type is `Order`, and `OrdersTotal`, typed as `Integer`. A `Group Join` query operator is supported only if the collection type contains the method:\n\n```vb\nFunction GroupJoin(inner As CS, _\n                         outerSelector As Func(Of T, K), _\n                         innerSelector As Func(Of S, K), _\n                         resultSelector As Func(Of T, CS, R)) As CR\n```\n\nThe code\n\n```vb\nDim xs() As Integer = ...\nDim ys() As Integer = ...\nDim zs = From x In xs _\n            Group Join y in ys On x Equals y _\n            Into g = Group _\n            ...\n```\n\nis generally translated to\n\n```vb\nDim xs() As Integer = ...\nDim ys() As Integer = ...\nDim zs = _\n    xs.GroupJoin( _\n        ys, _\n        Function(x As Integer) x, _\n        Function(y As Integer) y, _\n        Function(x, group) New With {x, .g = group})...\n```\n\n__Note.__ `Group`, `Join`, and `Into` are not reserved words.\n\n\n## Conditional Expressions\n\nA conditional `If` expression tests an expression and returns a value.\n\n```antlr\nConditionalExpression\n    : 'If' OpenParenthesis BooleanExpression Comma Expression Comma Expression CloseParenthesis\n    | 'If' OpenParenthesis Expression Comma Expression CloseParenthesis\n    ;\n```\n\nUnlike the `IIF` runtime function, however, a conditional expression only evaluates its operands if necessary. Thus, for example, the expression `If(c Is Nothing, c.Name, \"Unknown\")` will not throw an exception if the value of `c` is `Nothing`. The conditional expression has two forms: one that takes two operands and one that takes three operands.\n\nIf three operands are provided, all three expressions must be classified as values, and the first operand must be a Boolean expression. If the result is of the expression is true, then the second expression will be the result of the operator, otherwise the third expression will be the result of the operator. The result type of the expression is the dominant type between the types of the second and third expression. If there is no dominant type, then a compile-time error occurs.\n\nIf two operands are provided, both of the operands must be classified as values, and the first operand must be either a reference type or a nullable value type. The expression `If(x, y)` is then evaluated as if was the expression `If(x IsNot Nothing, x, y)`, with two exceptions. First, the first expression is only ever evaluated once, and second, if the second operand's type is a non-nullable value type and the first operand's type is, the `?` is removed from the type of the first operand when determining the dominant type for the result type of the expression. For example:\n\n```vb\nModule Test\n    Sub Main()\n        Dim x?, y As Integer\n        Dim a?, b As Long\n\n        a = If(x, a)        ' Result type: Long?\n        y = If(x, 0)        ' Result type: Integer\n    End Sub\nEnd Module\n```\n\nIn both forms of the expression, if an operand is `Nothing`, its type is not used to determine the dominant type. In the case of the expression `If(<expression>, Nothing, Nothing)`, the dominant type is considered to be `Object`.\n\n\n## XML Literal Expressions\n\nAn XML literal expression represents an XML (eXtensible Markup Language) 1.0 value.\n\n```antlr\nXMLLiteralExpression\n    : XMLDocument\n    | XMLElement\n    | XMLProcessingInstruction\n    | XMLComment\n    | XMLCDATASection\n    ;\n```\n\nThe result of an XML literal expression is a value typed as one of the types from the `System.Xml.Linq` namespace. If the types in that namespace are not available, then an XML literal expression will cause a compile-time error. The values are generated through constructor calls translated from the XML literal expression. For example, the code:\n\n```vb\nDim book As System.Xml.Linq.XElement = _\n    <book title=\"My book\"></book>\n```\n\nis roughly equivalent to the code:\n\n```vb\nDim book As System.Xml.Linq.XElement = _\n    New System.Xml.Linq.XElement( _\n        \"book\", _\n        New System.Xml.Linq.XAttribute(\"title\", \"My book\"))\n```\n\nAn XML literal expression can take the form of an XML document, an XML element, an XML processing instruction, an XML comment, or a CDATA section.\n\n__Note.__ This specification contains only enough of a description of XML to describe the behavior of the Visual Basic language. More information on XML can be found at http://www.w3.org/TR/REC-xml/.\n\n\n### Lexical rules\n\n```antlr\nXMLCharacter\n    : '<Unicode tab character (0x0009)>'\n    | '<Unicode linefeed character (0x000A)>'\n    | '<Unicode carriage return character (0x000D)>'\n    | '<Unicode characters 0x0020 - 0xD7FF>'\n    | '<Unicode characters 0xE000 - 0xFFFD>'\n    | '<Unicode characters 0x10000 - 0x10FFFF>'\n    ;\n\nXMLString\n    : XMLCharacter+\n    ;\n\nXMLWhitespace\n    : XMLWhitespaceCharacter+\n    ;\n\nXMLWhitespaceCharacter\n    : '<Unicode carriage return character (0x000D)>'\n    | '<Unicode linefeed character (0x000A)>'\n    | '<Unicode space character (0x0020)>'\n    | '<Unicode tab character (0x0009)>'\n    ;\n\nXMLNameCharacter\n    : XMLLetter\n    | XMLDigit\n    | '.'\n    | '-'\n    | '_'\n    | ':'\n    | XMLCombiningCharacter\n    | XMLExtender\n    ;\n\nXMLNameStartCharacter\n    : XMLLetter\n    | '_'\n    | ':'\n    ;\n\nXMLName\n    : XMLNameStartCharacter XMLNameCharacter*\n    ;\n\nXMLLetter\n    : '<Unicode character as defined in the Letter production of the XML 1.0 specification>'\n    ;\n\nXMLDigit\n    : '<Unicode character as defined in the Digit production of the XML 1.0 specification>'\n    ;\n\nXMLCombiningCharacter\n    : '<Unicode character as defined in the CombiningChar production of the XML 1.0 specification>'\n    ;\n\nXMLExtender\n    : '<Unicode character as defined in the Extender production of the XML 1.0 specification>'\n    ;\n```\n\nXML literal expressions are interpreted using the lexical rules of XML instead of the lexical rules of regular Visual Basic code. The two sets of rules generally differ in the following ways:\n\n* White space is significant in XML. As a result, the grammar for XML literal expressions explicitly states where white space is allowed. Whitespace is not preserved, except when it occurs in the context of character data within an element. For example:\n\n  ```vb\n  ' The following element preserves no whitespace\n  Dim e1 = _\n      <customer>\n          <name>Bob</>\n      </>\n\n  ' The following element preserves all of the whitespace\n  Dim e2 = _\n      <customer>\n          Bob\n      </>\n  ```\n\n* XML end-of-line whitespace is normalized according to the XML specification.\n\n* XML is case-sensitive. Keywords must match casing exactly, or else a compile-time error will occur.\n\n* Line terminators are considered white space in XML. As a result, no line-continuation characters are needed in XML literal expressions.\n\n* XML does not accept full-width characters. If full-width characters are used, a compile-time error will occur.\n\n\n### Embedded expressions\n\nXML literal expressions can contain *embedded expressions*. An embedded expression is a Visual Basic expression that is evaluated and used to fill in one or more values at the location of embedded expression.\n\n```antlr\nXMLEmbeddedExpression\n    : '<' '%' '=' LineTerminator? Expression LineTerminator? '%' '>'\n    ;\n```\n\nFor example, the following code places the string `John Smith` as the value of the XML element:\n\n```vb\nDim name as String = \"John Smith\"\nDim element As System.Xml.Linq.XElement = <customer><%= name %></customer>\n```\n\nExpressions can be embedded in a number of contexts. For example, the following code produces an element named `customer`:\n\n```vb\nDim name As String = \"customer\"\nDim element As System.Xml.Linq.XElement = <<%= name %>>John Smith</>\n```\n\nEach context where an embedded expression can be used specifies the types that will be accepted. When within the context of the expression part of an embedded expression, the normal lexical rules for Visual Basic code still apply so, for example, line continuations must be used:\n\n```vb\n' Visual Basic expression uses line continuation, XML does not\nDim element As System.Xml.Linq.XElement = _\n    <<%= name & _\n          name %>>John \n                     Smith</>\n```\n\n\n### XML Documents\n\n```antlr\nXMLDocument\n    : XMLDocumentPrologue XMLMisc* XMLDocumentBody XMLMisc*\n    ;\n\nXMLDocumentPrologue\n    : '<' '?' 'xml' XMLVersion XMLEncoding? XMLStandalone? XMLWhitespace? '?' '>'\n    ;\n\nXMLVersion\n    : XMLWhitespace 'version' XMLWhitespace? '=' XMLWhitespace? XMLVersionNumberValue\n    ;\n\nXMLVersionNumberValue\n    : SingleQuoteCharacter '1' '.' '0' SingleQuoteCharacter\n    | DoubleQuoteCharacter '1' '.' '0' DoubleQuoteCharacter\n    ;\n\nXMLEncoding\n    : XMLWhitespace 'encoding' XMLWhitespace? '=' XMLWhitespace? XMLEncodingNameValue\n    ;\n\nXMLEncodingNameValue\n    : SingleQuoteCharacter XMLEncodingName SingleQuoteCharacter\n    | DoubleQuoteCharacter XMLEncodingName DoubleQuoteCharacter\n    ;\n\nXMLEncodingName\n    : XMLLatinAlphaCharacter XMLEncodingNameCharacter*\n    ;\n\nXMLEncodingNameCharacter\n    : XMLUnderscoreCharacter\n    | XMLLatinAlphaCharacter\n    | XMLNumericCharacter\n    | XMLPeriodCharacter\n    | XMLDashCharacter\n    ;\n\nXMLLatinAlphaCharacter\n    : '<Unicode Latin alphabetic character (0x0041-0x005a, 0x0061-0x007a)>'\n    ;\n\nXMLNumericCharacter\n    : '<Unicode digit character (0x0030-0x0039)>'\n    ;\n\nXMLHexNumericCharacter\n    : XMLNumericCharacter\n    | '<Unicode Latin hex alphabetic character (0x0041-0x0046, 0x0061-0x0066)>'\n    ;\n\nXMLPeriodCharacter\n    : '<Unicode period character (0x002e)>'\n    ;\n\nXMLUnderscoreCharacter\n    : '<Unicode underscore character (0x005f)>'\n    ;\n\nXMLDashCharacter\n    : '<Unicode dash character (0x002d)>'\n    ;\n\nXMLStandalone\n    : XMLWhitespace 'standalone' XMLWhitespace? '=' XMLWhitespace? XMLYesNoValue\n    ;\n\nXMLYesNoValue\n    : SingleQuoteCharacter XMLYesNo SingleQuoteCharacter\n    | DoubleQuoteCharacter XMLYesNo DoubleQuoteCharacter\n    ;\n\nXMLYesNo\n    : 'yes'\n    | 'no'\n    ;\n\nXMLMisc\n    : XMLComment\n    | XMLProcessingInstruction\n    | XMLWhitespace\n    ;\n\nXMLDocumentBody\n    : XMLElement\n    | XMLEmbeddedExpression\n    ;\n```\n\nAn XML document results in a value typed as `System.Xml.Linq.XDocument`. Unlike the XML 1.0 specification, XML documents in XML literal expressions are required to specify the XML document prologue; XML literal expressions without the XML document prologue are interpreted as their individual entity. For example:\n\n```vb\nDim doc As System.Xml.Linq.XDocument = _\n    <?xml version=\"1.0\"?>\n    <?instruction?>\n    <customer>Bob</>\n\nDim pi As System.Xml.Linq.XProcessingInstruction = _\n    <?instruction?>\n```\n\nAn XML document can contain an embedded expression whose type can be any type; at runtime, however, the object must satisfy the requirements of the `XDocument` constructor or a run-time error will occur.\n\nUnlike regular XML, XML document expressions do not support DTDs (Document Type Declarations). Also, the encoding attribute, if supplied, will be ignored since the encoding of the Xml literal expression is always the same as the encoding of the source file itself.\n\n__Note.__ Although the encoding attribute is ignored, it is still valid attribute in order to maintain the ability to include any valid Xml 1.0 documents in source code.\n\n\n### XML Elements\n\n```antlr\nXMLElement\n    : XMLEmptyElement\n    | XMLElementStart XMLContent XMLElementEnd\n    ;\n\nXMLEmptyElement\n    : '<' XMLQualifiedNameOrExpression XMLAttribute* XMLWhitespace? '/' '>'\n    ;\n\nXMLElementStart\n    : '<' XMLQualifiedNameOrExpression XMLAttribute* XMLWhitespace? '>'\n    ;\n\nXMLElementEnd\n    : '<' '/' '>'\n    | '<' '/' XMLQualifiedName XMLWhitespace? '>'\n    ;\n\nXMLContent\n    : XMLCharacterData? ( XMLNestedContent XMLCharacterData? )+\n    ;\n\nXMLCharacterData\n    : '<Any XMLCharacterDataString that does not contain the string \"]]>\">'\n    ;\n\nXMLCharacterDataString\n    : '<Any Unicode character except < or &>'+\n    ;\n\nXMLNestedContent\n    : XMLElement\n    | XMLReference\n    | XMLCDATASection\n    | XMLProcessingInstruction\n    | XMLComment\n    | XMLEmbeddedExpression\n    ;\n\nXMLAttribute\n    : XMLWhitespace XMLAttributeName XMLWhitespace? '=' XMLWhitespace? XMLAttributeValue\n    | XMLWhitespace XMLEmbeddedExpression\n    ;\n\nXMLAttributeName\n    : XMLQualifiedNameOrExpression\n    | XMLNamespaceAttributeName\n    ;\n\nXMLAttributeValue\n    : DoubleQuoteCharacter XMLAttributeDoubleQuoteValueCharacter* DoubleQuoteCharacter\n    | SingleQuoteCharacter XMLAttributeSingleQuoteValueCharacter* SingleQuoteCharacter\n    | XMLEmbeddedExpression\n    ;\n\nXMLAttributeDoubleQuoteValueCharacter\n    : '<Any XMLCharacter except <, &, or DoubleQuoteCharacter>'\n    | XMLReference\n    ;\n\nXMLAttributeSingleQuoteValueCharacter\n    : '<Any XMLCharacter except <, &, or SingleQuoteCharacter>'\n    | XMLReference\n    ;\n\nXMLReference\n    : XMLEntityReference\n    | XMLCharacterReference\n    ;\n\nXMLEntityReference\n    : '&' XMLEntityName ';'\n    ;\n\nXMLEntityName\n    : 'lt' | 'gt' | 'amp' | 'apos' | 'quot'\n    ;\n\nXMLCharacterReference\n    : '&' '#' XMLNumericCharacter+ ';'\n    | '&' '#' 'x' XMLHexNumericCharacter+ ';'\n    ;\n```\n\nAn XML element results in a value typed as `System.Xml.Linq.XElement`. Unlike regular XML, XML elements can omit the name in the closing tag and the current most-nested element will be closed. For example:\n\n```vb\nDim name = <name>Bob</>\n```\n\nAttribute declarations in an XML element result in values typed as `System.Xml.Linq.XAttribute`. Attribute values are normalized according to the XML specification. When the value of an attribute is `Nothing` the attribute will not be created, so the attribute value expression will not have to be checked for `Nothing`. For example:\n\n```vb\nDim expr = Nothing\n\n' Throws null argument exception\nDim direct = New System.Xml.Linq.XElement( _\n    \"Name\", _\n    New System.Xml.Linq.XAttribute(\"Length\", expr))\n\n' Doesn't throw exception, the result is <Name/>\nDim literal = <Name Length=<%= expr %>/>\n```\n\nXML elements and attributes can contain nested expressions in the following places:\n\nThe name of the element, in which case the embedded expression must be a value of a type implicitly convertible to `System.Xml.Linq.XName`. For example:\n\n```vb\nDim name = <<%= \"name\" %>>Bob</>\n```\n\nThe name of an attribute of the element, in which case the embedded expression must be a value of a type implicitly convertible to `System.Xml.Linq.XName`. For example:\n\n```vb\nDim name = <name <%= \"length\" %>=\"3\">Bob</>\n```\n\nThe value of an attribute of the element, in which case the embedded expression can be a value of any type. For example:\n\n```vb\nDim name = <name length=<%= 3 %>>Bob</>\n```\n\nAn attribute of the element, in which case the embedded expression can be a value of any type. For example:\n\n```vb\nDim name = <name <%= new XAttribute(\"length\", 3) %>>Bob</>\n```\n\nThe content of the element, in which case the embedded expression can be a value of any type. For example:\n\n```vb\nDim name = <name><%= \"Bob\" %></>\n```\n\nIf the type of the embedded expression is `Object()`, the array will be passed as a paramarray to the `XElement` constructor.\n\n\n### XML Namespaces\n\nXML elements can contain XML namespace declarations, as defined by the XML namespaces 1.0 specification.\n\n```antlr\nXMLNamespaceAttributeName\n    : XMLPrefixedNamespaceAttributeName\n    | XMLDefaultNamespaceAttributeName\n    ;\n\nXMLPrefixedNamespaceAttributeName\n    : 'xmlns' ':' XMLNamespaceName\n    ;\n\nXMLDefaultNamespaceAttributeName\n    : 'xmlns'\n    ;\n\nXMLNamespaceName\n    : XMLNamespaceNameStartCharacter XMLNamespaceNameCharacter*\n    ;\n\nXMLNamespaceNameStartCharacter\n    : '<Any XMLNameCharacter except :>'\n    ;\n\nXMLNamespaceNameCharacter\n    : XMLLetter\n    | '_'\n    ;\n\nXMLQualifiedNameOrExpression\n    : XMLQualifiedName\n    | XMLEmbeddedExpression\n    ;\n\nXMLQualifiedName\n    : XMLPrefixedName\n    | XMLUnprefixedName\n    ;\n\nXMLPrefixedName\n    : XMLNamespaceName ':' XMLNamespaceName\n    ;\n\nXMLUnprefixedName\n    : XMLNamespaceName\n    ;\n```\n\nThe restrictions on defining the namespaces `xml` and `xmlns` are enforced and will produce compile-time errors. XML namespace declarations cannot have an embedded expression for their value; the value supplied must be a non-empty string literal. For example:\n\n```vb\n' Declares a valid namespace\nDim customer = <db:customer xmlns:db=\"http://example.org/database\">Bob</>\n\n' Error: xmlns cannot be re-defined\nDim bad1 = <elem xmlns:xmlns=\"http://example.org/namespace\"/>\n\n' Error: cannot have an embedded expression\nDim bad2 = <elem xmlns:db=<%= \"http://example.org/database\" %>>Bob</>\n```\n\n__Note.__ This specification contains only enough of a description of XML namespace to describe the behavior of the Visual Basic language. More information on XML namespaces can be found at http://www.w3.org/TR/REC-xml-names/.\n\nXML element and attribute names can be qualified using namespace names. Namespaces are bound as in regular XML, with the exception that any namespace imports declared at the file level are considered to be declared in a context enclosing the declaration, which is itself enclosed by any namespace imports declared by the compilation environment. If a namespace name cannot be found, a compile-time error occurs. For example:\n\n```vb\nImports System.Xml.Linq\nImports <xmlns:db=\"http://example.org/database\">\n\nModule Test\n    Sub Main()\n        ' Binds to the imported namespace above.\n        Dim c1 = <db:customer>Bob</>\n\n        ' Binds to the namespace declaration in the element\n        Dim c2 = _\n            <db:customer xmlns:db=\"http://example.org/database-other\">Mary</>\n\n        ' Binds to the inner namespace declaration\n        Dim c3 = _\n            <database xmlns:db=\"http://example.org/database-one\">\n                <db:customer xmlns:db=\"http://example.org/database-two\">Joe</>\n            </>\n\n        ' Error: namespace db2 cannot be found\n        Dim c4 = _\n            <db2:customer>Jim</>\n    End Sub\nEnd Module\n```\n\nXML namespaces declared in an element do not apply to XML literals inside embedded expressions. For example:\n\n```vb\n' Error: Namespace prefix 'db' is not declared\nDim customer = _\n    <db:customer xmlns:db=\"http://example.org/database\">\n        <%= <db:customer>Bob</> %>\n    </>\n```\n\n__Note.__ This is because the embedded expression can be anything, including a function call. If the function call contained an XML literal expression, it is not clear whether programmers would expect the XML namespace to be applied or ignored.\n\n\n### XML Processing Instructions\n\nAn XML processing instruction results in a value typed as `System.Xml.Linq.XProcessingInstruction`. XML processing instructions cannot contain embedded expressions, as they are valid syntax within the processing instruction.\n\n```antlr\nXMLProcessingInstruction\n    : '<' '?' XMLProcessingTarget ( XMLWhitespace XMLProcessingValue? )? '?' '>'\n    ;\n\nXMLProcessingTarget\n    : '<Any XMLName except a casing permutation of the string \"xml\">'\n    ;\n\nXMLProcessingValue\n    : '<Any XMLString that does not contain a question-mark followed by \">\">'\n    ;\n```\n\n### XML Comments\n\nAn XML comment results in a value typed as `System.Xml.Linq.XComment`. XML comments cannot contain embedded expressions, as they are valid syntax within the comment.\n\n```antlr\nXMLComment\n    : '<' '!' '-' '-' XMLCommentCharacter* '-' '-' '>'\n    ;\n\nXMLCommentCharacter\n    : '<Any XMLCharacter except dash (0x002D)>'\n    | '-' '<Any XMLCharacter except dash (0x002D)>'\n    ;\n```\n\n### CDATA sections\n\nA CDATA section results in a value typed as `System.Xml.Linq.XCData`. CDATA sections cannot contain embedded expressions, as they are valid syntax within the CDATA section.\n\n```antlr\nXMLCDATASection\n    : '<' '!' ( 'CDATA' '[' XMLCDATASectionString? ']' )? '>'\n    ;\n\nXMLCDATASectionString\n    : '<Any XMLString that does not contain the string \"]]>\">'\n    ;\n```\n\n## XML Member Access Expressions\n\nAn XML member access expression accesses the members of an XML value.\n\n```antlr\nXMLMemberAccessExpression\n    : Expression '.' LineTerminator? '<' XMLQualifiedName '>'\n    | Expression '.' LineTerminator? '@' LineTerminator? '<' XMLQualifiedName '>'\n    | Expression '.' LineTerminator? '@' LineTerminator? IdentifierOrKeyword\n    | Expression '.' '.' '.' LineTerminator? '<' XMLQualifiedName '>'\n    ;\n```\n\nThere are three types of XML member access expressions:\n\n* *Element access*, in which an XML name follows a single dot. For example:\n\n  ```vb\n  Dim customer = _\n      <customer>\n          <name>Bob</>\n      </>\n  Dim customerName = customer.<name>.Value\n  ```\n\n  Element access maps to the function:\n\n  ```vb\n  Function Elements(name As System.Xml.Linq.XName) As _\n      System.Collections.Generic.IEnumerable(Of _\n          System.Xml.Linq.XNode)\n  ```\n\n  So the above example is equivalent to:\n\n  ```vb\n  Dim customerName = customer.Elements(\"name\").Value\n  ```\n\n* *Attribute access*, in which a Visual Basic identifier follows a dot and an at sign, or an XML name follows a dot and an at sign. For example:\n\n  ```vb\n  Dim customer = <customer age=\"30\"/>\n  Dim customerAge = customer.@age\n  ```\n\n  Attribute access maps to the function:\n\n  ```vb\n  Function AttributeValue(name As System.Xml.Linq.XName) as String\n  ```\n\n  So the above example is equivalent to:\n\n  ```vb\n  Dim customerAge = customer.AttributeValue(\"age\")\n  ```\n\n  __Note.__ The `AttributeValue` extension method (as well as the related extension property `Value`) is not currently defined in any assembly. If the extension members are needed, they are automatically defined in the assembly being produced.\n\n* *Descendents access*, in which an XML names follows three dots. For example:\n\n  ```vb\n  Dim company = _\n      <company>\n          <customers>\n              <customer>Bob</>\n              <customer>Mary</>\n              <customer>Joe</>\n          </>\n      </>\n  Dim customers = company...<customer>\n  ```\n\n  Descendents access maps to the function:\n\n  ```vb\n  Function Descendents(name As System.Xml.Linq.XName) As _\n      System.Collections.Generic.IEnumerable(Of _\n          System.Xml.Linq.XElement)\n  ```\n\n  So the above example is equivalent to:\n\n  ```vb\n  Dim customers = company.Descendants(\"customer\")\n  ```\n\nThe base expression of an XML member access expression must be a value and must be of the type:\n\n* If an element or descendents access,  `System.Xml.Linq.XContainer` or a derived type, or `System.Collections.Generic.IEnumerable(Of T)` or a derived type, where `T` is `System.Xml.Linq.XContainer` or a derived type.\n\n* If an attribute access, `System.Xml.Linq.XElement` or a derived type, or `System.Collections.Generic.IEnumerable(Of T)` or a derived type, where `T` is `System.Xml.Linq.XElement` or a derived type.\n\nNames in XML member access expressions cannot be empty. They can be namespace qualified, using any namespaces defined by imports. For example:\n\n```vb\nImports <xmlns:db=\"http://example.org/database\">\n\nModule Test\n    Sub Main()\n        Dim customer = _\n            <db:customer>\n                <db:name>Bob</>\n            </>\n        Dim name = customer.<db:name>\n    End Sub\nEnd Module\n```\n\nWhitespace is not allowed after the dot(s) in an XML member access expression, or between the angle brackets and the name. For example:\n\n```vb\nDim customer = _\n    <customer age=\"30\">\n        <name>Bob</>\n    </>\n' All the following are error cases\nDim age = customer.@ age\nDim name = customer.< name >\nDim names = customer...< name >\n```\n\nIf the types in the `System.Xml.Linq` namespace are not available, then an XML member access expression will cause a compile-time error.\n\n\n## Await Operator\n\nThe await operator is related to async methods, which are described in Section [Async Methods](statements.md#async-methods).\n\n```antlr\nAwaitOperatorExpression\n    : 'Await' Expression\n    ;\n```\n\n`Await` is a reserved word if the immediately enclosing method or lambda expression in which it appears has an `Async` modifier, and if the `Await` appears after that `Async` modifier; it is unreserved elsewhere. It is also unreserved in preprocessor directives. The await operator is only allowed in the body of a method or lambda expressions where it is a reserved word. Within the immediately enclosing method or lambda, an await expression may not occur inside the body of a `Catch` or `Finally` block, nor inside the body of a `SyncLock` statement, nor inside a query expression.\n\nThe await operator takes a single expression which must be classified as a value and whose type must be an *awaitable* type, or `Object`. If its type is `Object` then all processing is deferred until run-time. A type `C` is said to be awaitable if all of the following are true:\n\n* `C` contains an accessible instance or extension method named `GetAwaiter` which has no arguments and which returns some type `E`;\n\n* `E` contains a readable instance or extension property named `IsCompleted` which takes no arguments and has type Boolean;\n\n* `E` contains an accessible instance or extension method named `GetResult` which takes no arguments;\n\n* `E` implements either `System.Runtime.CompilerServices.INotifyCompletion` or `ICriticalNotifyCompletion`.\n\nIf `GetResult` was a `Sub`, then the await expression is classified as void. Otherwise, the await expression is classified as a value and its type is the return type of the `GetResult` method.\n\nHere is an example of a class that can be awaited:\n\n```vb\nClass MyTask(Of T)\n    Function GetAwaiter() As MyTaskAwaiter(Of T)\n        Return New MyTaskAwaiter With {.m_Task = Me}\n    End Function\n\n    ...\nEnd Class\n\nStructure MyTaskAwaiter(Of T)\n    Implements INotifyCompletion\n\n    Friend m_Task As MyTask(Of T)\n\n    ReadOnly Property IsCompleted As Boolean\n        Get\n            Return m_Task.IsCompleted\n        End Get\n    End Property\n\n    Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted\n        ' r is the \"resumptionDelegate\"\n        Dim sc = SynchronizationContext.Current\n        If sc Is Nothing Then\n            m_Task.ContinueWith(Sub() r())\n        Else\n            m_Task.ContinueWith(Sub() sc.Post(Sub() r(), Nothing))\n        End If\n    End Sub\n\n    Function GetResult() As T\n        If m_Task.IsCanceled Then Throw New TaskCanceledException(m_Task)\n        If m_Task.IsFaulted Then Throw m_Task.Exception.InnerException\n        Return m_Task.Result\n    End Function\nEnd Structure\n```\n\n__Note.__ Library authors are recommended to follow the pattern that they invoke the continuation delegate on the same `SynchronizationContext` as their `OnCompleted` was itself invoked on. Also, the resumption delegate should not be executed synchronously within the `OnCompleted` method since that can lead to stack overflow: instead, the delegate should be queued for subsequent execution.\n\nWhen control flow reaches an `Await` operator, behavior is as follows.\n\n1.  The `GetAwaiter` method of the await operand is invoked. The result of this invocation is termed the *awaiter*.\n\n2.  The awaiter's `IsCompleted` property is retrieved. If the result is true then:\n\n    21. The `GetResult` method of the awaiter is invoked. If `GetResult` was a function, then the value of the await expression is the return value of this function.\n\n3.  If the IsCompleted property isn't true then:\n\n    31. Either `ICriticalNotifyCompletion.UnsafeOnCompleted` is invoked on the awaiter (if the awaiter's type `E` implements `ICriticalNotifyCompletion`) or `INotifyCompletion.OnCompleted` (otherwise). In both cases it passes a *resumption delegate* associated with the current instance of the async method.\n\n    32. The control point of the current async method instance is suspended, and control flow resumes in the *current caller* (defined in Section [Async Methods](statements.md#async-methods)).\n\n    33. If later the resumption delegate is invoked,\n\n        331. the resumption delegate first restores `System.Threading.Thread.CurrentThread.ExecutionContext` to what it was at the time `OnCompleted` was called,\n        332. then it resumes control flow at the control point of the async method instance (see Section [Async Methods](statements.md#async-methods)),\n        333. where it calls the `GetResult` method of the awaiter, as in 2.1 above.\n\nIf the await operand has type Object, then this behavior is deferred until runtime:\n\n- Step 1 is accomplished by calling GetAwaiter() with no arguments; it may therefore bind at runtime to instance methods which take optional parameters.\n- Step 2 is accomplished by retrieving the IsCompleted() property with no arguments, and by attempting an intrinsic conversion to Boolean.\n- Step 3.a is accomplished by attempting `TryCast(awaiter, ICriticalNotifyCompletion)`, and if this fails then `DirectCast(awaiter, INotifyCompletion)`.\n\nThe resumption delegate passed in 3.a may only be invoked once. If it is invoked more than once, the behavior is undefined.\n\n"
  },
  {
    "path": "spec/general-concepts.md",
    "content": "# General Concepts\n\nThis chapter covers a number of concepts that are required to understand the semantics of the Microsoft Visual Basic language. Many of the concepts should be familiar to Visual Basic programmers or C/C++ programmers, but their precise definitions may differ.\n\n## Declarations\n\nA Visual Basic program is made up of named entities. These entities are introduced through *declarations* and represent the \"meaning\" of the program.\n\nAt a top level, *namespaces* are entities that organize other entities, such as nested namespaces and types. *Types* are entities that describe values and define executable code. Types may contain nested types and type members. *Type members* are constants, variables, methods, operators, properties, events, enumeration values, and constructors.\n\nAn entity that can contain other entities defines a *declaration space*. Entities are introduced into a declaration space either through declarations or inheritance; the containing declaration space is called the entities' *declaration context*. Declaring an entity in a declaration space in turn defines a new declaration space that can contain further nested entity declarations; thus, the declarations in a program form a hierarchy of declaration spaces.\n\nExcept in the case of overloaded type members, it is invalid for declarations to introduce identically named entities of the same kind into the same declaration context. Additionally, a declaration space may never contain different kinds of entities with the same name; for example, a declaration space may never contain a variable and a method by the same name.\n\n__Note.__ It may be possible in other languages to create a declaration space that contains different kinds of entities with the same name (for example, if the language is case sensitive and allows different declarations based on casing). In that situation, the most accessible entity is considered bound to that name; if more than one type of entity is most accessible then the name is ambiguous. `Public` is more accessible than `Protected Friend`, `Protected Friend` is more accessible than `Protected` or `Friend`, and `Protected` or `Friend` is more accessible than `Private`.\n\nThe declaration space of a namespace is \"open ended,\" so two namespace declarations with the same fully qualified name contribute to the same declaration space. In the example below, the two namespace declarations contribute to the same declaration space, in this case declaring two classes with the fully qualified names `Data.Customer` and `Data.Order:`\n\n```vb\nNamespace Data\n    Class Customer\n    End Class\nEnd Namespace\n\nNamespace Data\n    Class Order\n    End Class\nEnd Namespace\n```\n\nBecause the two declarations contribute to the same declaration space, a compile-time error would occur if each contained a declaration of a class with the same name.\n\n### Overloading and Signatures\n\nThe only way to declare identically named entities of the same kind in a declaration space is through *overloading*. Only methods, operators, instance constructors, and properties may be overloaded.\n\nOverloaded type members must possess unique signatures. The signature of a type member consists of the number of type parameters, and the number and types of the member's parameters. Conversion operators also include the return type of the operator in the signature.\n\nThe following are not part of a member's signature, and hence cannot be overloaded on:\n\n* Modifiers to a type member (for example, `Shared` or `Private`).\n\n* Modifiers to a parameter (for example, `ByVal` or `ByRef`).\n\n* The names of the parameters.\n\n* The return type of a method or operator (except for conversion operators) or the element type of a property.\n\n* Constraints on a type parameter.\n\nThe following example shows a set of overloaded method declarations along with their signatures. This declaration would not be valid since several of the method declarations have identical signatures.\n\n```vb\nInterface ITest\n    Sub F1()                              ' Signature is ().\n    Sub F2(x As Integer)                  ' Signature is (Integer).\n    Sub F3(ByRef x As Integer)            ' Signature is (Integer).\n    Sub F4(x As Integer, y As Integer)    ' Signature is (Integer, Integer).\n    Function F5(s As String) As Integer   ' Signature is (String).\n    Function F6(x As Integer) As Integer  ' Signature is (Integer).\n    Sub F7(a() As String)                 ' Signature is (String()).\n    Sub F8(ParamArray a() As String)      ' Signature is (String()).\n    Sub F9(Of T)()                        ' Signature is !1().\n    Sub F10(Of T, U)(x As T, y As U)      ' Signature is !2(!1, !2)\n    Sub F11(Of U, T)(x As T, y As U)      ' Signature is !2(!2, !1)\n    Sub F12(Of T)(x As T)                 ' Signature is !1(!1)\n    Sub F13(Of T As IDisposable)(x As T)  ' Signature is !1(!1)\nEnd Interface\n```\n\nIt is valid to define a generic type that may contain members with identical signatures based on the type arguments supplied. Overload resolution rules are used to try and disambiguate between such overloads, although there may be situations in which it is impossible to disambiguate. For example:\n\n```vb\nClass C(Of T)\n    Sub F(x As Integer)\n    End Sub\n\n    Sub F(x As T)\n    End Sub\n\n    Sub G(Of U)(x As T, y As U)\n    End Sub\n\n    Sub G(Of U)(x As U, y As T)\n    End Sub\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim x As New C(Of Integer)\n        x.F(10)                   ' Calls C(Of T).F(Integer)\n        x.G(Of Integer)(10, 10)    ' Error: Can't choose between overloads\n    End Sub\nEnd Module\n```\n\n## Scope\n\nThe *scope* of an entity's name is the set of all declaration spaces within which it is possible to refer to that name without qualification. In general, the scope of an entity's name is its entire declaration context; however, an entity's declaration may contain nested declarations of entities with the same name. In that case, the nested entity *shadows*, or hides, the outer entity, and access to the shadowed entity is only possible through qualification.\n\nShadowing through nesting occurs in namespaces or types nested within namespaces, in types nested within other types, and in the bodies of type members. Shadowing through the nesting of declarations always occurs implicitly; no explicit syntax is required.\n\nIn the following example, within the `F` method, the instance variable `i` is shadowed by the local variable `i`, but within the `G` method, `i` still refers to the instance variable.\n\n```vb\nClass Test\n    Private i As Integer = 0\n\n    Sub F()\n        Dim i As Integer = 1\n    End Sub\n\n    Sub G()\n        i = 1\n    End Sub\nEnd Class\n```\n\nWhen a name in an inner scope hides a name in an outer scope, it shadows all overloaded occurrences of that name. In the following example, the call `F(1)` invokes the `F` declared in `Inner` because all outer occurrences of `F` are hidden by the inner declaration. For the same reason, the call `F(\"Hello\")` is in error.\n\n```vb\nClass Outer\n    Shared Sub F(i As Integer)\n    End Sub\n\n    Shared Sub F(s As String)\n    End Sub\n\n    Class Inner\n        Shared Sub F(l As Long)\n        End Sub\n\n        Sub G()\n            F(1) ' Invokes Outer.Inner.F.\n            F(\"Hello\") ' Error.\n        End Sub\n    End Class\nEnd Class\n```\n\n## Inheritance\n\nAn inheritance relationship is one in which one type (the *derived* type) derives from another (the *base* type), such that the derived type's declaration space implicitly contains the accessible non-constructor type members and nested types of its base type. In the following example, class `A` is the base class of `B`, and `B` is derived from `A`.\n\n```vb\nClass A\nEnd Class\n\nClass B\n    Inherits A\nEnd Class\n```\n\nSince `A` does not explicitly specify a base class, its base class is implicitly `Object`.\n\nThe following are important aspects of inheritance:\n\n* Inheritance is transitive. If type *C* is derived from type *B*, and type *B* is derived from type *A*, type *C* inherits the type members declared in type *B* as well as the type members declared in type *A*.\n\n* A derived type extends, but cannot narrow, its base type. A derived type can add new type members, and it can shadow inherited type members, but it cannot remove the definition of an inherited type member.\n\n* Because an instance of a type contains all of the type members of its base type, a conversion always exists from a derived type to its base type.\n\n* All types must have a base type, except for the type `Object`. Thus, `Object` is the ultimate base type of all types, and all types can be converted to it.\n\n* Circularity in derivation is not permitted. That is, when a type `B` derives from a type `A`, it is an error for type `A` to derive directly or indirectly from type `B`.\n\n* A type may not directly or indirectly derive from a type nested within it.\n\nThe following example produces a compile-time error because the classes circularly depend on each other.\n\n```vb\nClass A\n    Inherits B\nEnd Class\n\nClass B\n    Inherits C\nEnd Class\n\nClass C\n    Inherits A\nEnd Class\n```\n\nThe following example also produces a compile-time error because `B` indirectly derives from its nested class `C` through class `A`.\n\n```vb\nClass A\n    Inherits B.C\nEnd Class\n\nClass B\n    Inherits A\n\n    Public Class C\n    End Class \nEnd Class\n```\n\nThe next example does not produce an error because class `A` does not derive from class `B`.\n\n```vb\nClass A\n    Class B\n        Inherits A\n    End Class \nEnd Class\n```\n\n### MustInherit and NotInheritable Classes\n\nA `MustInherit` class is an incomplete type that can act only as a base type. A `MustInherit` class cannot be instantiated, so it is an error to use the `New` operator on one. It is valid to declare variables of `MustInherit` classes; such variables can only be assigned `Nothing` or a value that is of a class derived from the `MustInherit` class.\n\nWhen a regular class is derived from a `MustInherit` class, the regular class must override all inherited `MustOverride` members. For example:\n\n```vb\nMustInherit Class A\n    Public MustOverride Sub F()\nEnd Class\n\nMustInherit Class B\n    Inherits A\n\n    Public Sub G()\n    End Sub\nEnd Class \n\nClass C\n    Inherits B\n\n    Public Overrides Sub F()\n    End Sub \nEnd Class\n```\n\nThe `MustInherit` class `A` introduces a `MustOverride` method `F`. Class `B` introduces an additional method `G`, but does not provide an implementation of `F`. Class `B` must therefore also be declared `MustInherit`. Class `C` overrides `F` and provides an actual implementation. Since there are no outstanding `MustOverride` members in class `C`, it is not required to be `MustInherit`.\n\nA `NotInheritable` class is a class from which another class cannot be derived. `NotInheritable` classes are primarily used to prevent unintended derivation.\n\nIn this example, class `B` is in error because it attempts to derive from the `NotInheritable` class `A`. A class cannot be marked both `MustInherit` and `NotInheritable`.\n\n```vb\nNotInheritable Class A\nEnd Class\n\nClass B\n    ' Error, a class cannot derive from a NotInheritable class.\n    Inherits A\nEnd Class\n```\n\n### Interfaces and Multiple Inheritance\n\nUnlike other types, which only derive from a single base type, an interface may derive from multiple base interfaces. Because of this, an interface can inherit an identically named type member from different base interfaces. In such a case, the multiply-inherited name is not available in the derived interface, and referring to any of those type members through the derived interface causes a compile-time error, regardless of signatures or overloading. Instead, conflicting type members must be referenced through a base interface name.\n\nIn the following example, the first two statements cause compile-time errors because the multiply-inherited member `Count` is not available in interface `IListCounter`:\n\n```vb\nInterface IList\n    Property Count() As Integer\nEnd Interface\n\nInterface ICounter\n    Sub Count(i As Integer)\nEnd Interface\n\nInterface IListCounter\n    Inherits IList\n    Inherits ICounter \nEnd Interface \n\nModule Test\n    Sub F(x As IListCounter)\n        x.Count(1)                  ' Error, Count is not available.\n        x.Count = 1                 ' Error, Count is not available.\n        CType(x, IList).Count = 1   ' Ok, invokes IList.Count.\n        CType(x, ICounter).Count(1) ' Ok, invokes ICounter.Count.\n    End Sub \nEnd Module\n```\n\nAs illustrated by the example, the ambiguity is resolved by casting `x` to the appropriate base interface type. Such casts have no run-time costs; they merely consist of viewing the instance as a less-derived type at compile time.\n\nWhen a single type member is inherited from the same base interface through multiple paths, the type member is treated as if it were only inherited once. In other words, the derived interface only contains one instance of each type member inherited from a particular base interface. For example:\n\n```vb\nInterface IBase\n    Sub F(i As Integer)\nEnd Interface\n\nInterface ILeft\n    Inherits IBase\nEnd Interface\n\nInterface IRight\n    Inherits IBase\nEnd Interface\n\nInterface IDerived\n    Inherits ILeft, IRight\nEnd Interface\n\nClass Derived\n    Implements IDerived\n\n    ' Only have to implement F once.\n    Sub F(i As Integer) Implements IDerived.F\n    End Sub\nEnd Class\n```\n\nIf a type member name is shadowed in one path through the inheritance hierarchy, then the name is shadowed in all paths. In the following example, the `IBase.F` member is shadowed by the `ILeft.F` member, but is not shadowed in `IRight`:\n\n```vb\nInterface IBase\n    Sub F(i As Integer)\nEnd Interface \n\nInterface ILeft\n    Inherits IBase\n\n    Shadows Sub F(i As Integer)\nEnd Interface \n\nInterface IRight\n    Inherits IBase\n\n    Sub G()\nEnd Interface \n\nInterface IDerived\n    Inherits ILeft, IRight \nEnd Interface \n\nClass Test\n    Sub H(d As IDerived)\n        d.F(1)                  ' Invokes ILeft.F.\n        CType(d, IBase).F(1)    ' Invokes IBase.F.\n        CType(d, ILeft).F(1)    ' Invokes ILeft.F.\n        CType(d, IRight).F(1)   ' Invokes IBase.F.\n    End Sub \nEnd Class\n```\n\nThe invocation `d.F(1)` selects `ILeft.F`, even though `IBase.F` appears to not be shadowed in the access path that leads through `IRight`. Because the access path from `IDerived` to `ILeft` to `IBase` shadows `IBase.F`, the member is also shadowed in the access path from `IDerived` to `IRight` to `IBase`.\n\n### Shadowing\n\nA derived type shadows the name of an inherited type member by re-declaring it. Shadowing a name does not remove the inherited type members with that name; it merely makes all of the inherited type members with that name unavailable in the derived class. The shadowing declaration may be any type of entity.\n\nEntities than can be overloaded can choose one of two forms of shadowing. *Shadowing by name* is specified using the `Shadows` keyword. An entity that shadows by name hides everything by that name in the base class, including all overloads. *Shadowing by name and signature* is specified using the `Overloads` keyword. An entity that shadows by name and signature hides everything by that name with the same signature as the entity. For example:\n\n```vb\nClass Base\n    Sub F()\n    End Sub\n\n    Sub F(i As Integer)\n    End Sub\n\n    Sub G()\n    End Sub\n\n    Sub G(i As Integer)\n    End Sub\nEnd Class\n\nClass Derived\n    Inherits Base\n\n    ' Only hides F(Integer).\n    Overloads Sub F(i As Integer)\n    End Sub\n\n    ' Hides G() and G(Integer).\n    Shadows Sub G(i As Integer)\n    End Sub\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim x As New Derived()\n\n        x.F() ' Calls Base.F().\n        x.G() ' Error: Missing parameter.\n    End Sub\nEnd Module\n```\n\nShadowing a method with a `ParamArray` argument by name and signature hides only the individual signature, not all possible expanded signatures. This is true even if the signature of the shadowing method matches the unexpanded signature of the shadowed method. The following example:\n\n```vb\nClass Base\n    Sub F(ParamArray x() As Integer)\n        Console.WriteLine(\"Base\")\n    End Sub\nEnd Class\n\nClass Derived \n    Inherits Base\n\n    Overloads Sub F(x() As Integer)\n        Console.WriteLine(\"Derived\")\n    End Sub\nEnd Class\n\nModule Test\n    Sub Main\n        Dim d As New Derived()\n        d.F(10)\n    End Sub\nEnd Module\n```\n\nprints `Base`, even though `Derived.F` has the same signature as the unexpanded form of `Base.F`.\n\nConversely, a method with a `ParamArray` argument only shadows methods with the same signature, not all possible expanded signatures. The following example:\n\n```vb\nClass Base\n    Sub F(x As Integer)\n        Console.WriteLine(\"Base\")\n    End Sub\nEnd Class\n\nClass Derived\n    Inherits Base\n\n    Overloads Sub F(ParamArray x() As Integer)\n        Console.WriteLine(\"Derived\")\n    End Sub\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim d As New Derived()\n        d.F(10)\n    End Sub\nEnd Module\n```\n\nprints `Base`, even though `Derived.F` has an expanded form that has the same signature as `Base.F`.\n\nA shadowing method or property that does not specify `Shadows` or `Overloads` assumes `Overloads` if the method or property is declared `Overrides`, `Shadows` otherwise. If one member of a set of overloaded entities specifies the `Shadows` or `Overloads` keyword, they all must specify it. The `Shadows` and `Overloads` keywords cannot be specified at the same time. Neither `Shadows` nor `Overloads` can be specified in a standard module; members in a standard module implicitly shadow members inherited from `Object`.\n\nIt is valid to shadow the name of a type member that has been multiply-inherited through interface inheritance (and which is thereby unavailable), thus making the name available in the derived interface.\n\nFor example:\n\n```vb\nInterface ILeft\n    Sub F()\nEnd Interface\n\nInterface IRight\n    Sub F()\nEnd Interface\n\nInterface ILeftRight\n    Inherits ILeft, IRight\n\n    Shadows Sub F()\nEnd Interface\n\nModule Test\n    Sub G(i As ILeftRight)\n        i.F() ' Calls ILeftRight.F.\n        CType(i, ILeft).F() ' Calls ILeft.F.\n        CType(i, IRight).F() ' Calls IRight.F.\n    End Sub\nEnd Module\n```\n\nBecause methods are allowed to shadow inherited methods, it is possible for a class to contain several `Overridable` methods with the same signature. This does not present an ambiguity problem, since only the most-derived method is visible. In the following example, the `C` and `D` classes contain two `Overridable` methods with the same signature:\n\n```vb\nClass A\n    Public Overridable Sub F()\n        Console.WriteLine(\"A.F\")\n    End Sub \nEnd Class \n\nClass B\n    Inherits A\n\n    Public Overrides Sub F()\n        Console.WriteLine(\"B.F\")\n    End Sub \nEnd Class \n\nClass C\n    Inherits B\n\n    Public Shadows Overridable Sub F()\n        Console.WriteLine(\"C.F\")\n    End Sub \nEnd Class \n\nClass D\n    Inherits C\n\n    Public Overrides Sub F()\n        Console.WriteLine(\"D.F\")\n    End Sub \nEnd Class \n\nModule Test\n    Sub Main()\n        Dim d As New D()\n        Dim a As A = d\n        Dim b As B = d\n        Dim c As C = d\n        a.F()\n        b.F()\n        c.F()\n        d.F()\n    End Sub \nEnd Module\n```\n\nThere are two `Overridable` methods here: one introduced by class `A` and the one introduced by class `C`. The method introduced by class `C` hides the method inherited from class `A`. Thus, the `Overrides` declaration in class `D` overrides the method introduced by class `C`, and it is not possible for class `D` to override the method introduced by class `A`. The example produces the output:\n\n```console\nB.F\nB.F\nD.F\nD.F\n```\n\nIt is possible to invoke the hidden `Overridable` method by accessing an instance of class `D` through a less-derived type in which the method is not hidden.\n\nIt is not valid to shadow a `MustOverride` method, because in most cases this would make the class unusable. For example:\n\n```vb\nMustInherit Class Base\n    Public MustOverride Sub F()\nEnd Class\n\nMustInherit Class Derived\n    Inherits Base\n\n    Public Shadows Sub F()\n    End Sub\nEnd Class\n\nClass MoreDerived\n    Inherits Derived\n\n    ' Error: MustOverride method Base.F is not overridden.\nEnd Class\n```\n\nIn this case, the class `MoreDerived` is required to override the `MustOverride` method `Base.F`, but because the class `Derived` shadows `Base.F`, this is not possible. There is no way to declare a valid descendent of `Derived`.\n\nIn contrast to shadowing a name from an outer scope, shadowing an accessible name from an inherited scope causes a warning to be reported, as in the following example:\n\n```vb\nClass Base\n    Public Sub F()\n    End Sub\n\n    Private Sub G()\n    End Sub \nEnd Class\n\nClass Derived\n    Inherits Base\n\n    Public Sub F() ' Warning: shadowing an inherited name.\n    End Sub\n\n    Public Sub G() ' No warning, Base.G is not accessible here.\n    End Sub\nEnd Class\n```\n\nThe declaration of method `F` in class `Derived` causes a warning to be reported. Shadowing an inherited name is specifically not an error, since that would preclude separate evolution of base classes. For example, the above situation might have come about because a later version of class `Base` introduced a method `F` that was not present in an earlier version of the class. Had the above situation been an error, *any* change made to a base class in a separately versioned class library could potentially cause derived classes to become invalid.\n\nThe warning caused by shadowing an inherited name can be eliminated through use of the `Shadows` or `Overloads` modifier:\n\n```vb\nClass Base\n    Public Sub F()\n    End Sub \nEnd Class \n\nClass Derived\n    Inherits Base\n\n    Public Shadows Sub F() 'OK.\n    End Sub\nEnd Class\n```\n\nThe `Shadows` modifier indicates the intention to shadow the inherited member. It is not an error to specify the `Shadows` or `Overloads` modifier if there is no type member name to shadow.\n\nA declaration of a new member shadows an inherited member only within the scope of the new member, as in the following example:\n\n```vb\nClass Base\n    Public Shared Sub F()\n    End Sub \nEnd Class \n\nClass Derived\n    Inherits Base\n\n    Private Shared Shadows Sub F() ' Shadows Base.F in class Derived only.\n    End Sub \nEnd Class \n\nClass MoreDerived\n    Inherits Derived\n\n    Shared Sub G()\n        F() ' Invokes Base.F.\n    End Sub \nEnd Class\n```\n\nIn the example above, the declaration of method `F` in class `Derived` shadows the method `F` that was inherited from class `Base`, but since the new method `F` in class `Derived` has `Private` access, its scope does not extend to class `MoreDerived`. Thus, the call `F()` in `MoreDerived.G` is valid and will invoke `Base.F`. In the case of overloaded type members, the entire set of overloaded type members is treated as if they all had the most permissive access for the purposes of shadowing.\n\n```vb\nClass Base\n    Public Sub F()\n    End Sub\nEnd Class\n\nClass Derived\n    Inherits Base\n\n    Private Shadows Sub F()\n    End Sub\n\n    Public Shadows Sub F(i As Integer)\n    End Sub\nEnd Class\n\nClass MoreDerived\n    Inherits Derived\n\n    Public Sub G()\n        F()   ' Error. No accessible member with this signature.\n    End Sub\nEnd Class\n```\n\nIn this example, even though the declaration of `F()` in `Derived` is declared with `Private` access, the overloaded `F(Integer)` is declared with `Public` access. Therefore, for the purpose of shadowing, the name `F` in `Derived` is treated as if it was `Public`, so both methods shadow `F` in `Base`.\n\n## Implementation\n\nAn *implementation* relationship exists when a type declares that it implements an interface and the type implements all the type members of the interface. A type that implements a particular interface is convertible to that interface. Interfaces cannot be instantiated, but it is valid to declare variables of interfaces; such variables can only be assigned a value that is of a class that implements the interface. For example:\n\n```vb\nInterface ITestable\n    Function Test(value As Byte) As Boolean\nEnd Interface\n\nClass TestableClass\n    Implements ITestable\n\n    Function Test(value As Byte) As Boolean Implements ITestable.Test\n        Return value > 128\n    End Function\nEnd Class\n\nModule Test\n    Sub F()\n        Dim x As ITestable = New TestableClass\n        Dim b As Boolean\n\n        b = x.Test(34)\n    End Sub\nEnd Module\n```\n\nA type implementing an interface with multiply-inherited type members must still implement those methods, even though they cannot be accessed directly from the derived interface being implemented. For example:\n\n```vb\nInterface ILeft\n    Sub Test()\nEnd Interface\n\nInterface IRight\n    Sub Test()\nEnd Interface\n\nInterface ILeftRight\n    Inherits ILeft, IRight\nEnd Interface\n\nClass LeftRight\n    Implements ILeftRight\n\n    ' Has to reference ILeft explicitly.\n    Sub TestLeft() Implements ILeft.Test\n    End Sub\n\n    ' Has to reference IRight explicitly.\n    Sub TestRight() Implements IRight.Test\n    End Sub\n\n    ' Error: Test is not available in ILeftRight.\n    Sub TestLeftRight() Implements ILeftRight.Test\n    End Sub\nEnd Class\n```\n\nEven `MustInherit` classes must provide implementations of all the members of implemented interfaces; however, they can defer implementation of these methods by declaring them as `MustOverride`. For example:\n\n```vb\nInterface ITest\n    Sub Test1()\n    Sub Test2()\nEnd Interface\n\nMustInherit Class TestBase\n    Implements ITest\n\n    ' Provides an implementation.\n    Sub Test1() Implements ITest.Test1\n    End Sub\n\n    ' Defers implementation.\n    MustOverride Sub Test2() Implements ITest.Test2\nEnd Class\n\nClass TestDerived\n    Inherits TestBase\n\n    ' Have to implement MustOverride method.\n    Overrides Sub Test2()\n    End Sub\nEnd Class\n```\n\nA type may choose to re-implement an interface that its base type implements. To re-implement the interface, the type must explicitly state that it implements the interface. A type re-implementing an interface may choose to re-implement only some, but not all, of the members of the interface -- any members not re-implemented continue to use the base type's implementation. For example:\n\n```vb\nClass TestBase\n    Implements ITest\n\n    Sub Test1() Implements ITest.Test1\n        Console.WriteLine(\"TestBase.Test1\")\n    End Sub\n\n    Sub Test2() Implements ITest.Test2\n        Console.WriteLine(\"TestBase.Test2\")\n    End Sub\nEnd Class\n\nClass TestDerived\n    Inherits TestBase\n    Implements ITest  ' Required to re-implement\n\n    Sub DerivedTest1() Implements ITest.Test1\n        Console.WriteLine(\"TestDerived.DerivedTest1\")\n    End Sub\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim Test As ITest = New TestDerived()\n        Test.Test1()\n        Test.Test2()\n    End Sub\nEnd Module\n```\n\nThis example prints:\n\n```console\nTestDerived.DerivedTest1\nTestBase.Test2\n```\n\nWhen a derived type implements an interface whose base interfaces are implemented by the derived type's base types, the derived type can choose to only implement the interface's type members that are not already implemented by the base types. For example:\n\n```vb\nInterface IBase\n    Sub Base()\nEnd Interface\n\nInterface IDerived\n    Inherits IBase\n\n    Sub Derived()\nEnd Interface\n\nClass Base\n    Implements IBase\n\n    Public Sub Base() Implements IBase.Base\n    End Sub\nEnd Class\n\nClass Derived\n    Inherits Base\n    Implements IDerived\n\n    ' Required: IDerived.Derived not implemented by Base.\n    Public Sub Derived() Implements IDerived.Derived\n    End Sub\nEnd Class\n```\n\nAn interface method can also be implemented using an overridable method in a base type. In that case, a derived type may also override the overridable method and alter the implementation of the interface. For example:\n\n```vb\nClass Base\n    Implements ITest\n\n    Public Sub Test1() Implements ITest.Test1\n        Console.WriteLine(\"TestBase.Test1\")\n    End Sub\n\n    Public Overridable Sub Test2() Implements ITest.Test2\n        Console.WriteLine(\"TestBase.Test2\")\n    End Sub\nEnd Class\n\nClass Derived\n    Inherits Base\n\n    ' Overrides base implementation.\n    Public Overrides Sub Test2()\n        Console.WriteLine(\"TestDerived.Test2\")\n    End Sub\nEnd Class\n```\n\n### Implementing Methods\n\nA type *implements* a type member of an implemented interface by supplying a method with an `Implements` clause. The two type members must have the same number of parameters, all of the types and modifiers of the parameters must match, including the default value of optional parameters, the return type must match, and all of the constraints on method parameters must match. For example:\n\n```vb\nInterface ITest\n    Sub F(ByRef x As Integer)\n    Sub G(Optional y As Integer = 20)\n    Sub H(Paramarray z() As Integer)\nEnd Interface\n\nClass Test\n    Implements ITest\n\n    ' Error: ByRef/ByVal mismatch.\n    Sub F(x As Integer) Implements ITest.F\n    End Sub\n\n    ' Error: Defaults do not match.\n    Sub G(Optional y As Integer = 10) Implements ITest.G\n    End Sub\n\n    ' Error: Paramarray does not match.\n    Sub H(z() As Integer) Implements ITest.H\n    End Sub\nEnd Class\n```\n\nA single method may implement any number of interface type members if they all meet the above criteria. For example:\n\n```vb\nInterface ITest\n    Sub F(i As Integer)\n    Sub G(i As Integer)\nEnd Interface\n\nClass Test\n\n    Implements ITest\n\n    Sub F(i As Integer) Implements ITest.F, ITest.G\n    End Sub\nEnd Class\n```\n\nWhen implementing a method in a generic interface, the implementing method must supply the type arguments that correspond to the interface's type parameters. For example:\n\n```vb\nInterface I1(Of U, V) \n    Sub M(x As U, y As List(Of V)) \nEnd Interface\n\nClass C1(Of W, X)\n    Implements I1(Of W, X)\n\n    ' W corresponds to U and X corresponds to V\n    Public Sub M(x As W, y As List(Of X)) Implements I1(Of W, X).M\n    End Sub \nEnd Class\n\nClass C2\n    Implements I1(Of String, Integer)\n\n    ' String corresponds to U and Integer corresponds to V\n    Public Sub M(x As String, y As List(Of Integer)) _\n        Implements I1(Of String, Integer).M\n    End Sub\nEnd Class\n```\n\nNote that it is possible that a generic interface may not be implementable for some set of type arguments.\n\n```vb\nInterface I1(Of T, U)\n    Sub S1(x As T)\n    Sub S1(y As U)\nEnd Interface\n\nClass C1\n    ' Unable to implement because I1.S1 has two identical signatures\n    Implements I1(Of Integer, Integer)\nEnd Class\n```\n\n## Polymorphism\n\n*Polymorphism* provides the ability to vary the implementation of a method or property. With polymorphism, the same method or property can perform different actions depending on the run-time type of the instance that invokes it. Methods or properties that are polymorphic are called *overridable*. By contrast, the implementation of a non-overridable method or property is invariant; the implementation is the same whether the method or property is invoked on an instance of the class in which it is declared or an instance of a derived class. When a non-overridable method or property is invoked, the compile-time type of the instance is the determining factor. For example:\n\n```vb\nClass Base\n    Public Overridable Property X() As Integer\n        Get\n        End Get\n\n        Set\n        End Set\n    End Property\nEnd Class\n\nClass Derived\n    Inherits Base\n\n    Public Overrides Property X() As Integer\n        Get\n        End Get\n\n        Set\n        End Set\n    End Property\nEnd Class\n\nModule Test\n    Sub F()\n        Dim Z As Base\n\n        Z = New Base()\n        Z.X = 10            ' Calls Base.X\n        Z = New Derived()\n        Z.X = 10            ' Calls Derived.X\n    End Sub\nEnd Module\n```\n\nAn overridable method may also be `MustOverride`, which means that it provides no method body and must be overridden. `MustOverride` methods are only allowed in `MustInherit` classes.\n\nIn the following example, the class `Shape` defines the abstract notion of a geometrical shape object that can paint itself:\n\n```vb\nMustInherit Public Class Shape\n    Public MustOverride Sub Paint(g As Graphics, r As Rectangle)\nEnd Class \n\nPublic Class Ellipse\n    Inherits Shape\n\n    Public Overrides Sub Paint(g As Graphics, r As Rectangle)\n        g.drawEllipse(r)\n    End Sub \nEnd Class \n\nPublic Class Box\n    Inherits Shape\n\n    Public Overrides Sub Paint(g As Graphics, r As Rectangle)\n        g.drawRect(r)\n    End Sub \nEnd Class\n```\n\nThe `Paint` method is `MustOverride` because there is no meaningful default implementation. The `Ellipse` and `Box` classes are concrete `Shape` implementations. Because these classes are not `MustInherit`, they are required to override the `Paint` method and provide an actual implementation.\n\nIt is an error for a base access to reference a `MustOverride` method, as the following example demonstrates:\n\n```vb\nMustInherit Class A\n    Public MustOverride Sub F()\nEnd Class\n\nClass B\n    Inherits A\n\n    Public Overrides Sub F()\n        MyBase.F() ' Error, MyBase.F is MustOverride.\n    End Sub \nEnd Class\n```\n\nAn error is reported for the `MyBase.F()` invocation because it references a `MustOverride` method.\n\n### Overriding Methods\n\nA type may *override* an inherited overridable method by declaring a method with the same name and , signature, and marking the declaration with the `Overrides` modifier.There are additional requirements on overriding methods, listed below. Whereas an `Overridable` method declaration introduces a new method, an `Overrides` method declaration replaces the inherited implementation of the method.\n\nAn overriding method may be declared `NotOverridable`, which prevents any further overriding of the method in derived types. In effect, `NotOverridable` methods become non-overridable in any further derived classes.\n\nConsider the following example:\n\n```vb\nClass A\n    Public Overridable Sub F()\n        Console.WriteLine(\"A.F\")\n    End Sub\n\n    Public Overridable Sub G()\n        Console.WriteLine(\"A.G\")\n    End Sub\nEnd Class\n\nClass B\n    Inherits A\n\n    Public Overrides NotOverridable Sub F()\n        Console.WriteLine(\"B.F\")\n    End Sub\n\n    Public Overrides Sub G()\n        Console.WriteLine(\"B.G\")\n    End Sub\nEnd Class\n\nClass C\n    Inherits B\n\n    Public Overrides Sub G()\n        Console.WriteLine(\"C.G\")\n    End Sub\nEnd Class\n```\n\nIn the example, class `B` provides two `Overrides` methods: a method `F` that has the `NotOverridable` modifier and a method `G` that does not. Use of the `NotOverridable` modifier prevents class `C` from further overriding method `F`.\n\nAn overriding method may also be declared `MustOverride`, even if the method that it is overriding is not declared `MustOverride`. This requires that the containing class be declared `MustInherit` and that any further derived classes that are not declared `MustInherit` must override the method. For example:\n\n```vb\nClass A\n    Public Overridable Sub F()\n        Console.WriteLine(\"A.F\")\n    End Sub\nEnd Class\n\nMustInherit Class B\n    Inherits A\n\n    Public Overrides MustOverride Sub F()\nEnd Class\n```\n\nIn the example, class `B` overrides `A.F` with a `MustOverride` method. This means that any classes derived from `B` will have to override `F`, unless they are declared `MustInherit` as well.\n\nA compile-time error occurs unless all of the following are true of an overriding method:\n\n* The declaration context contains a single accessible inherited method with the same signature and return type (if any) as the overriding method.\n* The inherited method being overridden is overridable. In other words, the inherited method being overridden is not `Shared` or `NotOverridable`.\n* The accessibility domain of the method being declared is the same as the accessibility domain of the inherited method being overridden. There is one exception: a `Protected Friend` method must be overridden by a `Protected` method if the other method is in another assembly that the overriding method does not have `Friend` access to.\n* The parameters of the overriding method match the overridden method's parameters in regards to usage of the `ByVal`, `ByRef`, `ParamArray,` and `Optional` modifiers, including the values provided for optional parameters.\n* The type parameters of the overriding method match the overridden method's type parameters in regards to type constraints.\n\nWhen overriding a method in a base generic type, the overriding method must supply the type arguments that correspond to the base type parameters. For example:\n\n```vb\nClass Base(Of U, V) \n    Public Overridable Sub M(x As U, y As List(Of V)) \n    End Sub\nEnd Class\n\nClass Derived(Of W, X)\n    Inherits Base(Of W, X)\n\n    ' W corresponds to U and X corresponds to V\n    Public Overrides Sub M(x As W, y As List(Of X)) \n    End Sub \nEnd Class\n\nClass MoreDerived\n    Inherits Derived(Of String, Integer)\n\n    ' String corresponds to U and Integer corresponds to V\n    Public Overrides Sub M(x As String, y As List(Of Integer))\n    End Sub\nEnd Class\n```\n\nNote that it is possible that an overridable method in a generic class may not be able to be overridden for some sets of type arguments. If the method is declared `MustOverride`, this means that some inheritance chains may not be possible. For example:\n\n```vb\nMustInherit Class Base(Of T, U)\n    Public MustOverride Sub S1(x As T)\n    Public MustOverride Sub S1(y As U)\nEnd Class\n\nClass Derived\n    Inherits Base(Of Integer, Integer)\n\n    ' Error: Can't override both S1's at once\n    Public Overrides Sub S1(x As Integer)\n    End Sub\nEnd Class\n```\n\nAn override declaration can access the overridden base method using a base access, as in the following example:\n\n```vb\nClass Base\n    Private x As Integer\n\n    Public Overridable Sub PrintVariables()\n        Console.WriteLine(\"x = \" & x)\n    End Sub\nEnd Class\n\nClass Derived\n    Inherits Base\n\n    Private y As Integer\n\n    Public Overrides Sub PrintVariables()\n        MyBase.PrintVariables()\n        Console.WriteLine(\"y = \" & y)\n    End Sub\nEnd Class\n```\n\nIn the example, the invocation of `MyBase.PrintVariables()` in class `Derived` invokes the `PrintVariables` method declared in class `Base`. A base access disables the overridable invocation mechanism and simply treats the base method as a non-overridable method. Had the invocation in `Derived` been written `CType(Me, Base).PrintVariables()`, it would recursively invoke the `PrintVariables` method declared in `Derived`, not the one declared in `Base`.\n\nOnly when it includes an `Overrides` modifier can a method override another method. In all other cases, a method with the same signature as an inherited method simply shadows the inherited method, as in the example below:\n\n```vb\nClass Base\n    Public Overridable Sub F()\n    End Sub\nEnd Class\n\nClass Derived\n    Inherits Base\n\n    Public Overridable Sub F() ' Warning, shadowing inherited F().\n    End Sub\nEnd Class\n```\n\nIn the example, the method `F` in class `Derived` does not include an `Overrides` modifier and therefore does not override method `F` in class `Base`. Rather, method `F` in class `Derived` shadows the method in class `Base`, and a warning is reported because the declaration does not include a `Shadows` or `Overloads` modifier.\n\nIn the following example, method `F` in class `Derived` shadows the overridable method `F` inherited from class `Base`:\n\n```vb\nClass Base\n    Public Overridable Sub F()\n    End Sub\nEnd Class\n\nClass Derived\n    Inherits Base\n\n    Private Shadows Sub F() ' Shadows Base.F within Derived.\n    End Sub\nEnd Class\n\nClass MoreDerived\n    Inherits Derived\n\n    Public Overrides Sub F() ' Ok, overrides Base.F.\n    End Sub\nEnd Class\n```\n\nSince the new method `F` in class `Derived` has `Private` access, its scope only includes the class body of `Derived` and does not extend to class `MoreDerived`. The declaration of method `F` in class `MoreDerived` is therefore permitted to override the method `F` inherited from class `Base`.\n\nWhen an `Overridable` method is invoked, the most derived implementation of the instance method is called, based on the type of the instance, regardless of whether the call is to the method in the base class or the derived class. The most derived implementation of an `Overridable` method `M` with respect to a class `R` is determined as follows:\n\n* If `R` contains the introducing `Overridable` declaration of `M`, this is the most derived implementation of `M`.\n\n* Otherwise, if `R` contains an override of `M`, this is the most derived implementation of `M`.\n\n* Otherwise, the most derived implementation of `M` is the same as that of the direct base class of `R`.\n\n## Accessibility\n\nA declaration specifies the *accessibility* of the entity it declares. An entity's accessibility does not change the scope of an entity's name. The *accessibility domain* of a declaration is the set of all declaration spaces in which the declared entity is accessible.\n\nThe five access types are `Public`, `Protected`, `Friend`, `Protected Friend`, and `Private`. `Public` is the most permissive access type, and the four other types are all subsets of `Public`. The least permissive access type is `Private`, and the four other access types are all supersets of `Private`.\n\n```antlr\nAccessModifier\n    : 'Public'\n    | 'Protected'\n    | 'Friend'\n    | 'Private'\n    | 'Protected' 'Friend'\n    ;\n```\n\nThe access type for a declaration is specified via an optional access modifier, which can be `Public`, `Protected`, `Friend`, `Private`, or the combination of `Protected` and `Friend`. If no access modifier is specified, the default access type depends on the declaration context; the permitted access types also depend on the declaration context.\n\n* Entities declared with the `Public` modifier have `Public` access. There are no restrictions on the use of `Public` entities.\n\n* Entities declared with the `Protected` modifier have `Protected` access. `Protected` access can only be specified on members of classes (both regular type members and nested classes) or on `Overridable` members of standard modules and structures (which must, by definition, be inherited from `System.Object` or `System.ValueType`). A `Protected` member is accessible to a derived class, provided that either the member is not an instance member, or the access takes place through an instance of the derived class. `Protected` access is not a superset of `Friend` access.\n\n* Entities declared with the `Friend` modifier have `Friend` access. An entity with `Friend` access is accessible only within the program that contains the entity declaration or any assemblies that have been given `Friend` access through the `System.Runtime.CompilerServices.InternalsVisibleToAttribute` attribute.\n\n* Entities declared with the `Protected Friend` modifiers have the union of `Protected` and `Friend` access.\n\n* Entities declared with the `Private` modifier have `Private` access. A `Private` entity is accessible only within its declaration context, including any nested entities.\n\nThe accessibility in a declaration does not depend on the accessibility of the declaration context. For example, a type declared with `Private` access may contain a type member with `Public` access.\n\nThe following code demonstrates various accessibility domains:\n\n```vb\nPublic Class A\n    Public Shared X As Integer\n    Friend Shared Y As Integer\n    Private Shared Z As Integer\nEnd Class\n\nFriend Class B\n    Public Shared X As Integer\n    Friend Shared Y As Integer\n    Private Shared Z As Integer\n\n    Public Class C\n        Public Shared X As Integer\n        Friend Shared Y As Integer\n        Private Shared Z As Integer\n    End Class\n\n    Private Class D\n        Public Shared X As Integer\n        Friend Shared Y As Integer\n        Private Shared Z As Integer\n    End Class\nEnd Class\n```\n\nThe classes and members in this example have the following accessibility domains:\n\n* The accessibility domain of `A` and `A.X` is unlimited.\n\n* The accessibility domain of `A.Y`, `B`, `B.X`, `B.Y`, `B.C`, `B.C.X`, and `B.C.Y` is the containing program.\n\n* The accessibility domain of `A.Z` is `A.`\n\n* The accessibility domain of `B.Z`, `B.D`, `B.D.X`, and `B.D.Y` is `B`, including `B.C` and `B.D`.\n\n* The accessibility domain of `B.C.Z` is `B.C`.\n\n* The accessibility domain of `B.D.Z` is `B.D`.\n\nAs the example illustrates, the accessibility domain of a member is never larger than that of a containing type. For example, even though all `X` members have `Public` declared accessibility, all but `A.X` have accessibility domains that are constrained by a containing type.\n\nAccess to `Protected` instance members must be through an instance of the derived type so that unrelated types cannot gain access to each other's protected members. For example:\n\n```vb\nClass User\n    Protected Password As String\nEnd Class\n\nClass Employee\n    Inherits User\nEnd Class\n\nClass Guest\n    Inherits User\n\n    Public Function GetPassword(u As User) As String\n        ' Error: protected access has to go through derived type.\n        Return U.Password\n    End Function\nEnd Class\n```\n\nIn the above example, the class `Guest` only has access to the protected `Password` field if it is qualified with an instance of `Guest`. This prevents `Guest` from gaining access to the `Password` field of an `Employee` object simply by casting it to `User`.\n\nFor the purposes of `Protected` member access in generic types, the declaration context includes type parameters. This means that a derived type with one set of type arguments does not have access to the `Protected` members of a derived type with a different set of type arguments. For example:\n\n```vb\nClass Base(Of T)\n    Protected x As T\nEnd Class\n\nClass Derived(Of T)\n    Inherits Base(Of T)\n\n    Public Sub F(y As Derived(Of String))\n        ' Error: Derived(Of T) cannot access Derived(Of String)'s \n        '     protected members\n        y.x = \"a\"\n    End Sub\nEnd Class\n```\n\n__Note.__ The C# language (and possibly other languages) allows a generic type to access `Protected` members regardless of what type arguments are supplied. This should be kept in mind when designing generic classes that contain `Protected` members.\n\n\n### Constituent Types\n\nThe *constituent types* of a declaration are the types that are referenced by the declaration. For example, the type of a constant, the return type of a method and the parameter types of a constructor are all constituent types. The accessibility domain of a constituent type of a declaration must be the same as or a superset of the accessibility domain of the declaration itself. For example:\n\n```vb\nPublic Class X\n    Private Class Y\n    End Class\n\n    ' Error: Exposing private class Y outside of X.\n    Public Function Z() As Y\n    End Function\n\n    ' Valid: Not exposing outside of X.\n    Private Function A() As Y\n    End Function\nEnd Class\n\nFriend Class B\n    Private Class C\n    End Class\n\n    ' Error: Exposing private class Y outside of B.\n    Public Function D() As C\n    End Function\nEnd Class\n```\n\n## Type and Namespace Names\n\nMany language constructs require a namespace or type to be specified; these can be specified by using a qualified form of the namespace or type's name. A *qualified name* consists of a series of identifiers separated by periods; the identifier on the right side of a period is resolved in the declaration space specified by the identifier on the left side of the period.\n\nThe *fully qualified name* of a namespace or type is a qualified name that contains the name of all containing namespaces and types. In other words, the fully qualified name of a namespace or type is `N.T`, where `T` is the name of the entity and `N` is the fully qualified name of its containing entity.\n\nThe example below shows several namespace and type declarations together with their associated fully qualified names in in-line comments.\n\n```vb\nClass A            ' A.\nEnd Class\n\nNamespace X        ' X.\n    Class B        ' X.B.\n        Class C    ' X.B.C.\n        End Class\n    End Class\n\n    Namespace Y    ' X.Y.\n        Class D    ' X.Y.D.\n        End Class\n    End Namespace \nEnd Namespace \n\nNamespace X.Y      ' X.Y.\n    Class E        ' X.Y.E.\n    End Class\nEnd Namespace\n```\n\nObserve that the namespace X.Y has been declared in two different locations in the source code, but these two partial declarations constitute just a single namespace called X.Y which contains both class D and class E.\n\nIn some situations, a qualified name may begin with the keyword `Global`. The keyword represents the unnamed outermost namespace, which is useful in situations where a declaration shadows an enclosing namespace. The `Global` keyword allows \"escaping\" out to the outermost namespace in that situation. For example:\n\n```vb\nNamespace NS1\n    Class System\n    End Class\n\n    Module Test\n        Sub Main()\n            ' Error: Class System does not contain Int32\n            Dim x As System.Int32\n\n\n            ' Legal, binds to System in outermost namespace\n            Dim y As Global.System.Int32\n        End Sub\n    End Module\nEnd Namespace\n```\n\nIn the above example, the first method call is invalid because the identifier `System` binds to the class `System`, not the namespace `System`. The only way to access the `System` namespace is to use `Global` to escape out to the outermost namespace. `Global` cannot be used in an `Imports` statement or `Namespace` declaration.\n\nBecause other languages may introduce types and namespaces that match keywords in the language, Visual Basic recognizes keywords to be part of a qualified name as long as they follow a period. Keywords used in this way are treated as identifiers. For example, the qualified identifier `X.Default.Class` is a valid qualified identifier, while `Default.Class` is not.\n\n### Qualified Name Resolution for namespaces and types\n\nGiven a qualified namespace or type name of the form `N.R(Of A)`, where `R` is the rightmost identifier in the qualified name and `A` is an optional type argument list, the following steps describe how to determine to which namespace or type the qualified name refers:\n\n1. Resolve `N`, using the rules for either qualified or unqualified name resolution.\n\n2. If resolution of `N` fails, or resolves to a type parameter, a compile-time error occurs.\n\n3. Otherwise, if `R` matches the name of a namespace in N and no type arguments were supplied, or `R` matches an accessible type in `N` with the same number of type parameters as type arguments, if any, then the qualified name refers to that namespace or type.\n\n4. Otherwise, if `N` contains one or more standard modules, and `R` matches the name of an accessible type with the same number of type parameters as type arguments, if any, in exactly one standard module, then the qualified name refers to that type. If `R` matches the name of accessible types with the same number of type parameters as type arguments, if any, in more than one standard module, a compile-time error occurs.\n\n5. Otherwise, a compile-time error occurs.\n\n__Note.__ An implication of this resolution process is that type members do not shadow namespaces or types when resolving namespace or type names.\n\n### Unqualified Name Resolution for namespaces and types\n\nGiven an unqualified name `R(Of A)`, where `A` is an optional type argument list, the following steps describe how to determine to which namespace or type the unqualified name refers:\n\n1. If R matches the name of a type parameter of the current method, and no type arguments were supplied, then the unqualified name refers to that type parameter.\n\n2.  For each nested type containing the name reference, starting from the innermost type and going to the outermost:\n    1. If `R` matches the name of a type parameter in the current type and no type arguments were supplied, then the unqualified name refers to that type parameter.\n    2. Otherwise, if `R` matches the name of an accessible nested type with the same number of type parameters as type arguments, if any, then the unqualified name refers to that type.\n\n3. For each nested namespace containing the name reference, starting from the innermost namespace and going to the outermost namespace:\n    1. If `R` matches the name of a nested namespace in the current namespace and no type argument list is supplied, then the unqualified name refers to that nested namespace.\n    2. Otherwise, if `R` matches the name of an accessible type with the same number of type parameters as type arguments, if any, in the current namespace, then the unqualified name refers to that type.\n    3. Otherwise, if the namespace contains one or more accessible standard modules, and `R` matches the name of an accessible nested type with the same number of type parameters as type arguments, if any, in exactly one standard module, then the unqualified name refers to that nested type. If `R` matches the name of accessible nested types with the same number of type parameters as type arguments, if any, in more than one standard module, a compile-time error occurs.\n\n4. If the source file has one or more import aliases, and `R` matches the name of one of them, then the unqualified name refers to that import alias. If a type argument list is supplied, a compile-time error occurs.\n\n5. If the source file containing the name reference has one or more imports:\n    1. If `R` matches the name of an accessible type with the same number of type parameters as type arguments, if any, in exactly one import, then the unqualified name refers to that type. If `R` matches the name of an accessible type with the same number of type parameters as type arguments, if any, in more than one import and all are not the same type, a compile-time error occurs.\n    2. Otherwise, if no type argument list was supplied and `R` matches the name of a namespace with accessible types in exactly one import, then the unqualified name refers to that namespace. If no type argument list was supplied and `R` matches the name of a namespace with accessible types in more than one import and all are not the same namespace, a compile-time error occurs.\n    3. Otherwise, if the imports contain one or more accessible standard modules, and `R` matches the name of an accessible nested type with the same number of type parameters as type arguments, if any, in exactly one standard module, then the unqualified name refers to that type. If `R` matches the name of accessible nested types with the same number of type parameters as type arguments, if any, in more than one standard module, a compile-time error occurs.\n\n6. If the compilation environment defines one or more import aliases, and `R` matches the name of one of them, then the unqualified name refers to that import alias. If a type argument list is supplied, a compile-time error occurs.\n\n7. If the compilation environment defines one or more imports:\n    1. If `R` matches the name of an accessible type with the same number of type parameters as type arguments, if any, in exactly one import, then the unqualified name refers to that type. If `R` matches the name of an accessible type with the same number of type parameters as type arguments, if any, in more than one import, a compile-time error occurs.\n    2. Otherwise, if no type argument list was supplied and `R` matches the name of a namespace with accessible types in exactly one import, then the unqualified name refers to that namespace. If no type argument list was supplied and `R` matches the name of a namespace with accessible types in more than one import, a compile-time error occurs.\n    3. Otherwise, if the imports contain one or more accessible standard modules, and `R` matches the name of an accessible nested type with the same number of type parameters as type arguments, if any, in exactly one standard module, then the unqualified name refers to that type. If `R` matches the name of accessible nested types with the same number of type parameters as type arguments, if any, in more than one standard module, a compile-time error occurs.\n\n8. Otherwise, a compile-time error occurs.\n\n__Note.__ An implication of this resolution process is that type members do not shadow namespaces or types when resolving namespace or type names.\n\nNormally, a name can only occur once in a particular namespace. However, because namespaces can be declared across multiple .NET assemblies, it is possible to have a situation where two assemblies define a type with the same fully qualified name. In that case, a type declared in the current set of source files is preferred over a type declared in an external .NET assembly. Otherwise, the name is ambiguous and there is no way to disambiguate the name.\n\n## Variables\n\nA *variable* represents a storage location. Every variable has a type that determines what values can be stored in the variable. Because Visual Basic is a type-safe language, every variable in a program has a type and the language guarantees that values stored in variables are always of the appropriate type. Variables are always initialized to the default value of their type before any reference to the variable can be made. It is not possible to access uninitialized memory.\n\n## Generic Types and Methods\n\nTypes (except for standard modules and enumerated types) and methods can declare *type parameters*, which are types that will not be provided until an instance of the type is declared or the method is invoked. Types and methods with type parameters are also known as *generic types* and *generic methods*, respectively, because the type or method must be written generically, without specific knowledge of the types that will be supplied by code that uses the type or method.\n\n__Note.__ At this time, even though methods and delegates can be generic, properties, events and operators cannot be generic themselves. They may, however, use type parameters from the containing class.\n\nFrom the perspective of the generic type or method, a type parameter is a placeholder type that will be filled in with an actual type when the type or method is used. Type arguments are substituted for the type parameters in the type or method at the point at which the type or method is used. For example, a generic stack class could be implemented as:\n\n```vb\nPublic Class Stack(Of ItemType)\n    Protected Items(0 To 99) As ItemType\n    Protected CurrentIndex As Integer = 0\n\n    Public Sub Push(data As ItemType)\n        If CurrentIndex = 100 Then\n            Throw New ArgumentException(\"Stack is full.\")\n        End If\n\n        Items(CurrentIndex) = Data\n        CurrentIndex += 1\n    End Sub\n\n    Public Function Pop() As ItemType\n        If CurrentIndex = 0 Then\n            Throw New ArgumentException(\"Stack is empty.\")\n        End If\n\n        CurrentIndex -= 1\n        Return Items(CurrentIndex + 1) \n    End Function\nEnd Class\n```\n\nDeclarations that use the `Stack(Of ItemType)` class must supply a type argument for the type parameter `ItemType`. This type is then filled in wherever `ItemType` is used within the class:\n\n```vb\nOption Strict On\n\nModule Test\n    Sub Main()\n        Dim s1 As New Stack(Of Integer)()\n        Dim s2 As New Stack(Of Double)()\n\n        s1.Push(10.10)   ' Error: Stack(Of Integer).Push takes an Integer\n        s2.Push(10.10)   ' OK: Stack(Of Double).Push takes a Double\n        Console.WriteLine(s2.Pop().GetType().ToString()) ' Prints: Double\n    End Sub\nEnd Module\n```\n\n### Type Parameters\n\nType parameters may be supplied on type or method declarations. Each type parameter is an identifier which is a place-holder for a type argument that is supplied to create a constructed type or method. By contrast, a type argument is the actual type that is substituted for the type parameter when a generic type or method is used.\n\n```antlr\nTypeParameterList\n    : OpenParenthesis 'Of' TypeParameter ( Comma TypeParameter )* CloseParenthesis\n    ;\n\nTypeParameter\n    : VarianceModifier? Identifier TypeParameterConstraints?\n    ;\n\nVarianceModifier\n    : 'In' | 'Out'\n    ;\n```\n\nEach type parameter in a type or method declaration defines a name in the declaration space of that type or method. Thus, it cannot have the same name as another type parameter, a type member, a method parameter, or a local variable. The scope of a type parameter on a type or method is the entire type or method. Because type parameters are scoped to the entire type declaration, nested types can use outer type parameters. This also means that type parameters must always be specified when accessing types nested inside generic types:\n\n```vb\nPublic Class Outer(Of T)\n    Public Class Inner\n        Public Sub F(x As T)\n            ...\n        End Sub\n    End Class\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim x As New Outer(Of Integer).Inner()\n        ...\n    End Sub\nEnd Module\n```\n\nUnlike other members of a class, type parameters are not inherited. Type parameters in a type can only be referred to by their simple name; in other words, they cannot be qualified with the containing type name. Although it is bad programming style, the type parameters in a nested type can hide a member or type parameter declared in the outer type:\n\n```vb\nClass Outer(Of T)\n    Class Inner(Of T)\n        Public t1 As T    ' Refers to Inner's T\n    End Class\nEnd Class\n```\n\nTypes and methods may be overloaded based on the number of type parameters (or *arity*) that the types or methods declare. For example, the following declarations are legal:\n\n```vb\nModule C\n    Sub M()\n    End Sub\n\n    Sub M(Of T)()\n    End Sub\n\n    Sub M(Of T, U)()\n    End Sub\nEnd Module\n\nStructure C(Of T)\n    Dim x As T\nEnd Structure\n\nClass C(Of T, U)\nEnd Class\n```\n\nIn the case of types, overloads are always matched against the number of type arguments specified. This is useful when using both generic and non-generic classes together in the same program:\n\n```vb\nClass Queue \nEnd Class      \n\nClass Queue(Of T)\nEnd Class\n\nClass X\n    Dim q1 As Queue                 ' Non-generic queue\n    Dim q2 As Queue(Of Integer)     ' Generic queue\nEnd Class\n```\n\nRules for methods overloaded on type parameters are covered in the section on method overload resolution.\n\nWithin the containing declaration, type parameters are considered full types. Since a type parameter can be instantiated with many different actual type arguments, type parameters have slightly different operations and restrictions than other types as described below:\n\n* A type parameter cannot be used directly to declare a base class or interface.\n\n* The rules for member lookup on type parameters depend on the constraints, if any, applied to the type parameter.\n\n* The available conversions for a type parameter depend on the constraints, if any, applied to the type parameters.\n\n* In the absence of a `Structure` constraint, a value with a type represented by a type parameter can be compared with `Nothing` using `Is` and `IsNot`.\n\n* A type parameter can only be used in a `New` expression if the type parameter is constrained by a `New` or a `Structure` constraint.\n\n* A type parameter cannot be used anywhere within an attribute exception within a `GetType` expression.\n\n* Type parameters can be used as type arguments to other generic types and parameters.\n\nThe following example is a generic type that extends the `Stack(Of ItemType)` class:\n\n```vb\nClass MyStack(Of ItemType)\n    Inherits Stack(Of ItemType)\n\n    Public ReadOnly Property Size() As Integer\n        Get\n            Return CurrentIndex\n        End Get\n    End Property\nEnd Class\n```\n\nWhen a declaration supplies a type argument to `MyStack`, the same type argument will be applied to `Stack` as well.\n\nAs a type, type parameters are purely a compile-time construct. At run-time, each type parameter is bound to a run-time type that was specified by supplying a type argument to the generic declaration. Thus, the type of a variable declared with a type parameter will, at run-time, be a non-generic type or a specific constructed type. The run-time execution of all statements and expressions involving type parameters uses the actual type that was supplied as the type argument for that parameter.\n\n\n### Type Constraints\n\nBecause a type argument can be any type in the type system, a generic type or method cannot make any assumptions about a type parameter. Thus, the members of a type parameter are considered to be the members of the type `Object`, since all types derive from `Object`.\n\nIn the case of a collection like `Stack(Of ItemType)`, this fact may not be a particularly important restriction, but there may be cases where a generic type may wish to make an assumption about the types that will be supplied as type arguments. *Type constraints* can be placed on type parameters that restrict which types can be supplied as a type parameter and allow generic types or methods to assume more about type parameters.\n\n```antlr\nTypeParameterConstraints\n    : 'As' Constraint\n    | 'As' OpenCurlyBrace ConstraintList CloseCurlyBrace\n    ;\n\nConstraintList\n    : Constraint ( Comma Constraint )*\n    ;\n\nConstraint\n    : TypeName\n    | 'New'\n    | 'Structure'\n    | 'Class'\n    ;\n```\n\n\n```vb\nPublic Class DisposableStack(Of ItemType As IDisposable)\n    Implements IDisposable\n\n    Private _items(0 To 99) As ItemType\n    Private _currentIndex As Integer = 0\n\n    Public Sub Push(data As ItemType)\n        ...\n    End Sub\n\n    Public Function Pop() As ItemType\n        ...\n    End Function\n\n    Private Sub Dispose() Implements IDisposable.Dispose\n        For Each item As IDisposable In _items\n            If item IsNot Nothing Then\n                item.Dispose()\n            End If\n        Next item\n    End Sub\nEnd Class\n```\n\nIn this example, the `DisposableStack(Of ItemType)` constrains its type parameter to only types that implement the interface `System.IDisposable`. As a result, it can implement a `Dispose` method that disposes any objects still left in the queue.\n\nA type constraint must be one of the special constraints `Class`, `Structure`, or `New`, or it must be a type `T` where:\n\n* `T` is a class, an interface, or a type parameter.\n\n* `T` is not `NotInheritable`.\n\n* `T` is not one of, or a type inherited from one of, the following special types: `System.Array`, `System.Delegate`, `System.MulticastDelegate`, `System.Enum`, or `System.ValueType`.\n\n* `T` is not `Object`. Since all types derive from `Object`, such a constraint would have no effect if it were permitted.\n\n* `T` must be at least as accessible as the generic type or method being declared.\n\nMultiple type constraints can be specified for a single type parameter by enclosing the type constraints in curly braces (`{}`).. Only one type constraint for a given type parameter can be a class. It is an error to combine a `Structure` special constraint with a named class constraint or the `Class` special constraint.\n\n```vb\nClass ControlFactory(Of T As {Control, New})\n    ...\nEnd Class\n```\n\nType constraints can use the containing types or any of the containing types' type parameters. In the following example, the constraint requires that the type argument supplied implements a generic interface using itself as a type argument:\n\n```vb\nClass Sorter(Of V As IComparable(Of V))\n    ...\nEnd Class\n```\n\nThe special type constraint `Class` constrains the supplied type argument to any reference type.\n\n__Note.__ The special type constraint `Class` can be satisfied by an interface. And a structure can implement an interface. Therefore, the constraint `(Of T As U, U As Class)` might be satisfied with \"T\" a structure (which does not satisfy the `Class` special constraint), and \"U\" an interface that it implements (which does satisfy the `Class` special constraint).\n\nThe special type constraint `Structure` constrains the supplied type argument to any value type except `System.Nullable(Of T)`.\n\n__Note.__ Structure constraints do not allow `System.Nullable(Of T)` so that it is not possible to supply `System.Nullable(Of T)` as a type argument to itself.\n\nThe special type constraint `New` requires that the supplied type argument must have an accessible parameterless constructor and cannot be declared `MustInherit`. For example:\n\n```vb\nClass Factory(Of T As New)\n    Function CreateInstance() As T\n        Return New T()\n    End Function\nEnd Class\n```\n\nA class type constraint requires that the supplied type argument must either be that type as or inherit from it. An interface type constraint requires that the supplied type argument must implement that interface. A type parameter constraint requires that the supplied type argument must derive from or implement all of the bounds given for the matching type parameter. For example:\n\n```vb\nClass List(Of T)\n    Sub AddRange(Of S As T)(collection As IEnumerable(Of S))\n        ...\n    End Sub\nEnd Class\n```\n\nIn this example, the type parameter `S` on `AddRange` is constrained to the type parameter `T` of `List`. This means that a `List(Of Control)` would constrain `AddRange`'s type parameter to any type that is or inherits from `Control`.\n\nA type parameter constraint `Of S As T` is resolved by transitively adding all of `T`'s constraints onto `S`, other than the special constraints (`Class`, `Structure`, `New`). It is an error to have circular constraints (e.g. `Of S As T, T As S`). It is an error to have a type parameter constraint which itself has the `Structure` constraint. After adding constraints, it is possible that a number of special situations may occur:\n\n* If multiple class constraints exist, the most derived class is considered to be the constraint. If one or more class constraints have no inheritance relationship, the constraint is unsatisfiable and it is an error.\n\n * If a type parameter combines a `Structure` special constraint with a named class constraint or the `Class` special constraint, it is an error. A class constraint may be `NotInheritable`, in which case no derived types of that constraint are accepted and it is an error.\n\nThe type may be one of, or a type inherited from, the following special types: `System.Array`, `System.Delegate`, `System.MulticastDelegate`, `System.Enum`, or `System.ValueType`. In that case, only the type, or a type inherited from it, is accepted. A type parameter constrained to one of these types can only use the conversions allowed by the `DirectCast` operator. For example:\n\n```vb\nMustInherit Class Base(Of T)\n    MustOverride Sub S1(Of U As T)(x As U)\nEnd Class\n\nClass Derived\n    Inherits Base(Of Integer)\n\n    ' The constraint of U must be Integer, which is normally not allowed.\n    Overrides Sub S1(Of U As Integer)(x As U)\n        Dim y As Integer = x    ' OK\n        Dim z As Long = x       ' Error: Can't convert\n    End Sub\nEnd Class\n```\n\nAdditionally, a type parameter constrained to a value type due to one of the above relaxations cannot call any methods defined on that value type. For example:\n\n```vb\nClass C1(Of T)\n    Overridable Sub F(Of G As T)(x As G)\n    End Sub\nEnd Class\n\nClass C2\n    Inherits C1(Of IntPtr)\n\n    Overrides Sub F(Of G As IntPtr)(ByVal x As G)\n        ' Error: Cannot access structure members\n         x.ToInt32()\n    End Sub\nEnd Class\n```\n\nIf the constraint, after substitution, ends up as an array type, any covariant array type is allowed as well. For example:\n\n```vb\nModule Test\n    Class B\n    End Class\n\n    Class D\n        Inherits B\n    End Class\n\n    Function F(Of T, U As T)(x As U) As T\n        Return x\n    End Function\n\n    Sub Main()\n        Dim a(9) As B\n        Dim b(9) As D\n\n        a = F(Of B(), D())(b)\n    End Sub\nEnd Module\n```\n\nA type parameter with a class or interface constraint is considered to have the same members as that class or interface constraint. If a type parameter has multiple constraints, then the type parameter is considered to have the union of all the members of the constraints. If there are members with the same name in more than one constraint, then members are hidden in the following order: the class constraint hides members in interface constraints, which hide members in `System.ValueType` (if `Structure` constraint is specified), which hides members in `Object`. If a member with the same name appears in more than one interface constraint the member is unavailable (as in multiple interface inheritance) and the type parameter must be cast to the desired interface. For example:\n\n```vb\nClass C1\n    Sub S1(x As Integer)\n    End Sub\nEnd Class\n\nInterface I1\n    Sub S1(x As Integer)\nEnd Interface\n\nInterface I2\n    Sub S1(y As Double)\nEnd Interface\n\nModule Test\n    Sub T1(Of T As {C1, I1, I2})()\n        Dim a As T\n        a.S1(10)       ' Calls C1.S1, which is preferred\n        a.S1(10.10)    ' Also calls C1.S1, class is still preferred\n    End Sub\n\n    Sub T2(Of T As {I1, I2})()\n        Dim a As T\n        a.S1(10)    ' Error: Call is ambiguous between I1.S1, I2.S1\n    End Sub\nEnd Module\n```\n\nWhen supplying type parameters as type arguments, the type parameters must satisfy the constraints of the matching type parameters.\n\n```vb\nClass Base(Of T As Class)\nEnd Class\n\nClass Derived(Of V)\n    ' Error: V does not satisfy the constraints of T\n    Inherits Base(Of V)\nEnd Class\n```\n\nValues of a constrained type parameter can be used to access the instance members, including instance methods, specified in the constraint.\n\n```vb\nInterface IPrintable\n    Sub Print()\nEnd Interface\n\nClass Printer(Of V As IPrintable)\n    Sub PrintOne(v1 As V)\n        V1.Print()\n    End Sub\nEnd Class\n```\n\n### Type Parameter Variance\n\nA type parameter in an interface or a delegate type declaration can optionally specify a *variance modifier*. Type parameters with variance modifiers restrict how the type parameter can be used in the interface or delegate type but allow a generic interface or delegate type to be converted to another generic type with variant compatible type arguments. For example:\n\n```vb\nClass Base\nEnd Class\n\nClass Derived\n    Inherits Base\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim x As IEnumerable(Of Derived) = ...\n\n        ' OK, as IEnumerable(Of Base) is variant compatible\n        ' with IEnumerable(Of Derived)\n        Dim y As IEnumerable(Of Base) = x\n    End Sub\nEnd Module\n```\n\nGeneric interfaces that have type parameters with variance modifiers have several restrictions:\n\n* They cannot contain an event declaration that specifies a parameter list (but a custom event declaration or an event declaration with a delegate type is allowed).\n\n* They cannot contain a nested class, structure, or enumerated type.\n\n__Note.__ These restrictions are due to the fact that types nested in generic types implicitly copy the generic parameters of their parent. In the case of nested classes, structures, or enumerated types, those kinds of types cannot have variance modifiers on their type parameters. In the case of an event declaration with a parameter list, the generated nested delegate class could have confusing errors when a type that appears to be used in an `In` position (i.e. a parameter type) is actually used in an `Out` position (i.e. the type of the event).\n\nA type parameter that is declared with the Out modifier is *covariant*. Informally, a covariant type parameter can only be used in an output position -- i.e. a value that is being returned from the interface or delegate type -- and cannot be used in an input position. A type `T` is considered to be *valid covariantly* if:\n\n* `T` is a class, structure, or enumerated type.\n\n* `T` is non-generic delegate or interface type.\n\n* `T` is an array type whose element type is valid covariantly.\n\n* `T` is a type parameter which was not declared as an `Out` type parameter.\n\n* `T` is a constructed interface or delegate type `X(Of P1,...,Pn)` with type arguments `A1,...,An` such that:\n\n  * If `Pi` was declared as an Out type parameter then `Ai` is valid covariantly.\n\n  * If `Pi` was declared as an In type parameter then `Ai` is valid contravariantly.\n\nThe following must be valid covariantly in an interface or delegate type:\n\n* The base interface of an interface.\n\n* The return type of a function or the delegate type.\n\n* The type of a property if there is a `Get` accessor.\n\n* The type of any `ByRef` parameter.\n\nFor example:\n\n```vb\nDelegate Function D(Of Out T, U)(x As U) As T\n\nInterface I1(Of Out T)\nEnd Interface\n\nInterface I2(Of Out T)\n    Inherits I1(Of T)\n\n    ' OK, T is only used in an Out position\n    Function M1(x As I1(Of T)) As T\n\n    ' Error: T is used in an In position\n    Function M2(x As T) As T\nEnd Interface\n```\n\n__Note.__ `Out` is not a reserved word.\n\nA type parameter that is declared with the In modifier is *contravariant*. Informally, a contravariant type parameter can only be used in an input position -- i.e. a value that is being passed in to the interface or delegate type -- and cannot be used in an output position. A type `T` is considered to be *valid contravariantly* if:\n\n* `T` is a class, structure, or enumerated type.\n\n* `T` is a non-generic delegate or interface type.\n\n* `T` is an array type whose element type is valid contravariantly.\n\n* `T` is a type parameter which was not declared as an In type parameter.\n\n* `T` is a constructed interface or delegate type `X(Of P1,...,Pn)` with type arguments `A1,...,An` such that:\n\n  * If `Pi` was declared as an `Out` type parameter then `Ai` is valid contravariantly.\n\n  * If `Pi` was declared as an `In` type parameter then `Ai` is valid covariantly.\n\nThe following must be valid contravariantly in an interface or delegate type:\n\n* The type of a parameter.\n\n* A type constraint on a method type parameter.\n\n* The type of a property if it has a `Set` accessor.\n\n* The type of an event.\n\nFor example:\n\n```vb\nDelegate Function D(Of T, In U)(x As U) As T\n\nInterface I1(Of In T)\nEnd Interface\n\nInterface I2(Of In T)\n    ' OK, T is only used in an In position\n    Sub M1(x As I1(Of T))\n\n    ' Error: T is used in an Out position\n    Function M2() As T\nEnd Interface\n```\n\nIn the case where a type must be valid be contravariantly and covariantly (such as a property with both a `Get` and `Set` accessor or a `ByRef` parameter), a variant type parameter cannot be used.\n\n\nCo- and contra-variance give rise to a \"diamond ambiguity problem\". Consider the following code:\n\n```vb\nClass C\n    Implements IEnumerable(Of String)\n    Implements IEnumerable(Of Exception)\n     \n    Public Function GetEnumerator1() As IEnumerator(Of String) _\n       Implements IEnumerable(Of String).GetEnumerator\n       Console.WriteLine(\"string\")\n    End Function\n     \n    Public Function GetEnumerator2() As IEnumerator(Of Exception) _\n       Implements IEnumerable(Of Execption).GetEnumerator\n       Console.WriteLine(\"exception\")\n    End Function\nEnd Class\n     \nDim c As IEnumerable(Of Object) = New C\nc.GetEnumerator()\n```\n\nThe class `C` can be converted to `IEnumerable(Of Object)` in two ways, both through covariant conversion from `IEnumerable(Of String)` and through covariant conversion from `IEnumerable(Of Exception)`. The CLR does not specify which of the two methods will be called by `c.GetEnumerator()`. In general, whenever a class is declared to implement a covariant interface with two different generic arguments that have a common supertype (e.g. in this case `String` and `Exception` have the common supertype `Object`), or a class is declared to implement a contravariant interface with two different generic arguments that have a common subtype, then ambiguity is likely to arise. The compiler gives a warning on such declarations.\n"
  },
  {
    "path": "spec/introduction.md",
    "content": "# Introduction to Visual Basic\n\nThe Microsoft&reg; Visual Basic&reg; programming language is a high-level programming language for the Microsoft .NET Framework. Although it is designed to be an approachable and easy-to-learn language, it is also powerful enough to satisfy the needs of experienced programmers. The Visual Basic programming language has a syntax that is similar to English, which promotes the clarity and readability of Visual Basic code. Wherever possible, meaningful words or phrases are used instead of abbreviations, acronyms, or special characters. Extraneous or unneeded syntax is generally allowed but not required.\n\nThe Visual Basic programming language can be either a strongly typed or a loosely typed language. Loose typing defers much of the burden of type checking until a program is already running. This includes not only type checking of conversions but also of method calls, meaning that the binding of a method call can be deferred until run-time. This is useful when building prototypes or other programs in which speed of development is more important than execution speed. The Visual Basic programming language also provides strongly typed semantics that performs all type checking at compile-time and disallows run-time binding of method calls. This guarantees maximum performance and helps ensure that type conversions are correct. This is useful when building production applications in which speed of execution and execution correctness is important.\n\nThis document describes the Visual Basic language. It is meant to be a complete language description rather than a language tutorial or a user's reference manual.\n\n## Grammar Notation\n\nThis specification describes two grammars: a lexical grammar and a syntactic grammar. The lexical grammar defines how characters can be combined to form tokens; the syntactic grammar defines how the tokens can be combined to form Visual Basic programs. There are also several secondary grammars used for preprocessing operations like conditional compilation.\n\nThe grammars in this specification are written in ANTLR format -- see http://www.antlr.org/.\n\nCase is unimportant in Visual Basic programs. For simplicity, all terminals will be given in standard casing, but any casing will match them. Terminals that are printable elements of the ASCII character set are represented by their corresponding ASCII characters. Visual Basic is also width insensitive when matching terminals, allowing full-width Unicode characters to match their half-width Unicode equivalents, but only on a whole-token basis. A token will not match if it contains mixed half-width and full-width characters.\n\nLine breaks and indentation may be added for readability and are not part of the production.\n\n## Compatibility\n\nAn important feature of a programming language is compatibility between different versions of the language. If a newer version of a language does not accept the same code as a previous version of the language, or interprets it differently than the previous version, then a burden can be placed on a programmer when upgrading his code from one version of the language to another. As such, compatibility between versions must be preserved except when the benefit to language consumers is of a clear and overwhelming nature.\n\nThe following policy governs changes to the Visual Basic language between versions. The term language, when used in this context, refers only to the syntactic and semantic aspects of the Visual Basic language itself and does not include any .NET Framework classes included as a part of the `Microsoft.VisualBasic` namespace (and sub-namespaces). All classes in the .NET Framework are covered by a separate versioning and compatibility policy outside the scope of this document.\n\n### Kinds of compatibility breaks\n\nIn an ideal world, compatibility would be 100% between the existing version of Visual Basic and all future versions of Visual Basic. However, there may be situations where the need for a compatibility break may outweigh the cost it may impose on programmers. Such situations are:\n\n* *New warnings.* Introducing a new warning is not, per se, a compatibility break. However, because many developers compile with \"treat warnings as errors\" turned on, extra care must be taken when introducing warnings.\n\n* *New keywords.* Introducing new keywords may be necessary when introducing new language features. Reasonable efforts will be made to choose keywords that minimize the possibility of collision with users' identifiers and to use existing keywords where it makes sense. Help will be provided to upgrade projects from previous versions and escape any new keywords.\n\n* *Compiler bugs.* When the compiler's behavior is at odds with a documented behavior in the language specification, fixing the compiler behavior to match the documented behavior may be necessary.\n\n* *Specification bug.* When the compiler is consistent with the language specification but the language specification is clearly wrong, changing the language specification and the compiler behavior may be necessary. The phrase \"clearly wrong\" means that the documented behavior runs counter to what a clear and unambiguous majority of users would expect and produces highly undesirable behavior for users.\n\n* *Specification ambiguity.* When the language specification should spell out what happens in a particular situation but doesn't, and the compiler handles the situation in a way that is either inconsistent or clearly wrong (using the same definition from the previous point), clarifying the specification and correcting the compiler behavior may be necessary. In other words, when the specification covers cases a, b, d and e, but omits any mention of what happens in case c, and the compiler behaves incorrectly in case c, it may be necessary to document what happens in case c and change the behavior of the compiler to match. (Note that if the specification was ambiguous as to what happens in a situation and the compiler behaves in a manner that is not clearly wrong, the compiler behavior becomes the de facto specification.)\n\n* *Making run-time errors into compile-time errors.* In a situation where code is 100% guaranteed to fail at runtime (i.e. the user code has an unambiguous bug in it), it may be desirable to add a compile-time error that catches the situation.\n\n* *Specification omission.* When the language specification does not specifically allow or disallow a particular situation and the compiler handles the situation in a way that is undesirable (if the compiler behavior was clearly wrong, it would a specification bug, not a specification omission), it may be necessary to clarify the specification and change the compiler behavior. In addition to the usual impact analysis, changes of this kind are further restricted to cases where the impact of the change is considered to be extremely minimal and the benefit to developers is very high.\n\n* *New features.* In general, introducing new features should not change existing parts of the language specification or the existing behavior of the compiler. In the situation where introducing a new feature requires changing the existing language specification, such a compatibility break is reasonable only if the impact would be extremely minimal and the benefit of the feature is high.\n\n* *Security.* In extraordinary situations, security concerns may necessitate a compatibility break, such as removing or modifying a feature that is inherently insecure and poses a clear security risk for users.\n\nThe following situations are not acceptable reasons for introducing compatibility breaks:\n\n* *Undesirable or regrettable behavior.* Language design or compiler behavior which is reasonable but considered undesirable or regrettable in retrospect is not a justification for breaking backward compatibility. The language deprecation process, covered below, must be used instead.\n\n* *Anything else.* Otherwise, compiler behavior remains backwards compatible.\n\n### Impact Criteria\n\nWhen considering whether a compatibility break might be acceptable, several criteria are used to determine what the impact of the change might be. The greater the impact, the higher the bar for accepting the compatibility breaks.\n\nThe criteria are:\n\n* What is the scope of the change? In other words, how many programs are likely to be affected? How many users are likely to be affected? How common will it be to write code that is affected by the change?\n\n* Do any workarounds exist to get the same behavior prior to the change?\n\n* How obvious is the change? Will users get immediate feedback that something has changed, or will their programs just execute differently?\n\n* Can the change be reasonably addressed during upgrade? Is it possible to write a tool that can find the situation in which the change occurs with perfect accuracy and change the code to work around the change?\n\n* What is the community feedback on the change?\n\n### Language deprecation\n\nOver time, parts of the language or compiler may become deprecated. As discussed previously, it is not acceptable to break compatibility to remove such deprecated features. Instead, the following steps must be followed:\n\n1. Given a feature that exists in version *A* of Visual Studio, feedback must be solicited from the user community on deprecation of the feature and full notice given before any final deprecation decision is made. The deprecation process may be reversed or abandoned at any point based on user community feedback.\n\n2. full version (i.e. not a point release) *B* of Visual Studio must be released with compiler warnings that warn of deprecated usage. The warnings must be on by default and can be turned off. The deprecations must be clearly documented in the product documentation and on the web.\n\n3. A full version *C* of Visual Studio must be released with compiler warnings that cannot be turned off.\n\n4. A full version *D* of Visual Studio must subsequently be released with the deprecated compiler warnings converted into compiler errors. The release of *D* must occur after the end of the Mainstream Support Phase (5 years as of this writing) of release *A*.\n\n5. Finally, a version *E* of Visual Studio may be released that removes the compiler errors.\n\nChanges that cannot be handled within this deprecation framework will not be allowed.\n"
  },
  {
    "path": "spec/lexical-grammar.md",
    "content": "# Lexical Grammar\n\nCompilation of a Visual Basic program first involves translating the raw stream of Unicode characters into an ordered set of lexical tokens. Because the Visual Basic language is not free-format, the set of tokens is then further divided into a series of logical lines. A *logical line* spans from either the start of the stream or a line terminator through to the next line terminator that is not preceded by a line continuation or through to the end of the stream.\n\n__Note.__ With the introduction of XML literal expressions in version 9.0 of the language, Visual Basic no longer has a distinct lexical grammar in the sense that Visual Basic code can be tokenized without regard to the syntactic context. This is due to the fact that XML and Visual Basic have different lexical rules and the set of lexical rules in use at any particular time depends on what syntactic construct is being processed at that moment. This specification retains this lexical grammar section as a guide to the lexical rules of regular Visual Basic code.\n\n```antlr\nLogicalLineStart\n    : LogicalLine*\n    ;\n\nLogicalLine\n    : LogicalLineElement* Comment? LineTerminator\n    ;\n\nLogicalLineElement\n    : WhiteSpace\n    | LineContinuation\n    | Token\n    ;\n\nToken\n    : Identifier\n    | Keyword\n    | Literal\n    | Separator\n    | Operator\n    ;\n```\n\n## Characters and Lines\n\nVisual Basic programs are composed of characters from the Unicode character set.\n\n```antlr\nCharacter:\n    '<Any Unicode character except a LineTerminator>'\n    ;\n```\n\n### Line Terminators\n\nUnicode line break characters separate logical lines.\n\n```antlr\nLineTerminator\n    : '<Unicode 0x00D>'\n    | '<Unicode 0x00A>'\n    | '<CR>'\n    | '<LF>'\n    | '<Unicode 0x2028>'\n    | '<Unicode 0x2029>'\n    ;\n```\n\n### Line Continuation\n\nA *line continuation* consists of at least one white-space character that immediately precedes a single underscore character as the last character (other than white space) in a text line. A line continuation allows a logical line to span more than one physical line. Line continuations are treated as if they were white space, even though they are not.\n\n```antlr\nLineContinuation\n    : WhiteSpace '_' WhiteSpace* LineTerminator\n    ;\n```\n\nThe following program shows some line continuations:\n\n```vb\nModule Test\n    Sub Print( _\n        Param1 As Integer, _\n        Param2 As Integer )\n\n        If (Param1 < Param2) Or _\n            (Param1 > Param2) Then\n            Console.WriteLine(\"Not equal\")\n        End If\n    End Function\nEnd Module\n```\n\nSome places in the syntactic grammar allow for *implicit line continuations*. When a line terminator is encountered\n\n* after a comma (`,`), open parenthesis (`(`), open curly brace (`{`), or open embedded expression (`<%=`)\n\n* after a member qualifier (`.` or `.@` or `...`), provided that something is being qualified (i.e. is not using an implicit `With` context)\n\n* before a close parenthesis (`)`), close curly brace (`}`), or close embedded expression (`%>`)\n\n* after a less-than (`<`) in an attribute context\n\n* before a greater-than (`>`) in an attribute context\n\n* after a greater-than (`>`) in a non-file-level attribute context\n\n* before and after query operators (`Where`, `Order`, `Select`, etc.)\n\n* after binary operators (`+`, `-`, `/`, `*`, etc.) in an expression context\n\n* after assignment operators (`=`, `:=`, `+=`, `-=`, etc.) in any context.\n\nthe line terminator is treated as if it was a line continuation.\n\n```antlr\nComma\n    : ',' LineTerminator?\n    ;\n\nPeriod\n    : '.' LineTerminator?\n    ;\n\nOpenParenthesis\n    : '(' LineTerminator?\n    ;\n\nCloseParenthesis\n    : LineTerminator? ')'\n    ;\n\nOpenCurlyBrace\n    : '{' LineTerminator?\n    ;\n\nCloseCurlyBrace\n    : LineTerminator? '}'\n    ;\n\nEquals\n    : '=' LineTerminator?\n    ;\n\nColonEquals\n    : ':' '=' LineTerminator?\n    ;\n```\n\nFor example, the previous example could also be written as:\n\n```vb\nModule Test\n    Sub Print(\n        Param1 As Integer,\n        Param2 As Integer)\n\n        If (Param1 < Param2) Or\n            (Param1 > Param2) Then\n            Console.WriteLine(\"Not equal\")\n        End If\n    End Function\nEnd Module\n```\n\nImplicit line continuations will only ever be inferred directly before or after the specified token. They will not be inferred before or after a line continuation. For example:\n\n```vb\nDim y = 10\n' Error: Expression expected for assignment to x\nDim x = _\n\ny\n```\n\nLine continuations will not be inferred in conditional compilation contexts. (__Note.__ This last restriction is required because text in conditional compilation blocks that are not compiled do not have to be syntactically valid. Thus, text in the block might accidentally get \"picked up\" by the conditional compilation statement, especially as the language gets extended in the future.)\n\n\n### White Space\n\n*White space* serves only to separate tokens and is otherwise ignored. Logical lines containing only white space are ignored. (__Note.__\nLine terminators are not considered white space.)\n\n```antlr\nWhiteSpace\n    : '<Unicode class Zs>'\n    | '<Unicode Tab 0x0009>'\n    ;\n```\n\n### Comments\n\nA *comment* begins with a single-quote character or the keyword `REM`. A single-quote character is either an ASCII single-quote character, a Unicode left single-quote character, or a Unicode right single-quote character. Comments can begin anywhere on a source line, and the end of the physical line ends the comment. The compiler ignores the characters between the beginning of the comment and the line terminator. Consequently, comments cannot extend across multiple lines by using line continuations.\n\n```antlr\nComment\n    : CommentMarker Character*\n    ;\n\nCommentMarker\n    : SingleQuoteCharacter\n    | 'REM'\n    ;\n\nSingleQuoteCharacter\n    : '\\''\n    | '<Unicode 0x2018>'\n    | '<Unicode 0x2019>'\n    ;\n```\n\n## Identifiers\n\nAn *identifier* is a name. Visual Basic identifiers conform to the Unicode Standard Annex 15 with one exception: identifiers may begin with an underscore (connector) character. If an identifier begins with an underscore, it must contain at least one other valid identifier character to disambiguate it from a line continuation.\n\n```antlr\nIdentifier\n    : NonEscapedIdentifier TypeCharacter?\n    | Keyword TypeCharacter\n    | EscapedIdentifier\n    ;\n\nNonEscapedIdentifier\n    : '<Any IdentifierName but not Keyword>'\n    ;\n\nEscapedIdentifier\n    : '[' IdentifierName ']'\n    ;\n\nIdentifierName\n    : IdentifierStart IdentifierCharacter*\n    ;\n\nIdentifierStart\n    : AlphaCharacter\n    | UnderscoreCharacter IdentifierCharacter\n    ;\n\nIdentifierCharacter\n    : UnderscoreCharacter\n    | AlphaCharacter\n    | NumericCharacter\n    | CombiningCharacter\n    | FormattingCharacter\n    ;\n\nAlphaCharacter\n    : '<Unicode classes Lu,Ll,Lt,Lm,Lo,Nl>'\n    ;\n\nNumericCharacter\n    : '<Unicode decimal digit class Nd>'\n    ;\n\nCombiningCharacter\n    : '<Unicode combining character classes Mn, Mc>'\n    ;\n\nFormattingCharacter\n    : '<Unicode formatting character class Cf>'\n    ;\n\nUnderscoreCharacter\n    : '<Unicode connection character class Pc>'\n    ;\n\nIdentifierOrKeyword\n    : Identifier\n    | Keyword\n    ;\n```\n\nRegular identifiers may not match keywords, but escaped identifiers or identifiers with a type character can. An *escaped identifier* is an identifier delimited by square brackets. Escaped identifiers follow the same rules as regular identifiers except that they may match keywords and may not have type characters.\n\nThis example defines a class named `class` with a shared method named `shared` that takes a parameter named `boolean` and then calls the method.\n\n```vb\nClass [class]\n    Shared Sub [shared]([boolean] As Boolean)\n        If [boolean] Then\n            Console.WriteLine(\"true\")\n        Else\n            Console.WriteLine(\"false\")\n        End If\n    End Sub\nEnd Class\n\nModule [module]\n    Sub Main()\n        [class].[shared](True)\n    End Sub\nEnd Module\n```\n\nIdentifiers are case insensitive, so two identifiers are considered to be the same identifier if they differ only in case. (__Note.__ The Unicode Standard one-to-one case mappings are used when comparing identifiers and any locale-specific case mappings are ignored.)\n\n\n### Type Characters\n\nA *type character* denotes the type of the preceding identifier. The type character is not considered part of the identifier.\n\n```antlr\nTypeCharacter\n    : IntegerTypeCharacter\n    | LongTypeCharacter\n    | DecimalTypeCharacter\n    | SingleTypeCharacter\n    | DoubleTypeCharacter\n    | StringTypeCharacter\n    ;\n\nIntegerTypeCharacter\n    : '%'\n    ;\n\nLongTypeCharacter\n    : '&'\n    ;\n\nDecimalTypeCharacter\n    : '@'\n    ;\n\nSingleTypeCharacter\n    : '!'\n    ;\n\nDoubleTypeCharacter\n    : '#'\n    ;\n\nStringTypeCharacter\n    : '$'\n    ;\n```\n\nIf a declaration includes a type character, the type character must agree with the type specified in the declaration itself; otherwise, a compile-time error occurs. If the declaration omits the type (for example, if it does not specify an `As` clause), the type character is implicitly substituted as the type of the declaration.\n\nNo white space may come between an identifier and its type character. There are no type characters for `Byte`, `SByte`, `UShort`, `Short`, `UInteger` or `ULong`, due to a lack of suitable characters.\n\nAppending a type character to an identifier that conceptually does not have a type (for example, a namespace name) or to an identifier whose type disagrees with the type of the type character causes a compile-time error.\n\nThe following example shows the use of type characters:\n\n```vb\n' The follow line will cause an error: standard modules have no type.\nModule Test1#\nEnd Module\n\nModule Test2\n\n    ' This function takes a Long parameter and returns a String.\n    Function Func$(Param&)\n\n        ' The following line causes an error because the type character\n        ' conflicts with the declared type of Func and Param.\n        Func# = CStr(Param@)\n\n        ' The following line is valid.\n        Func$ = CStr(Param&)\n    End Function\nEnd Module\n```\n\nThe type character `!` presents a special problem in that it can be used both as a type character and as a separator in the language. To remove ambiguity, a `!` character is a type character as long as the character that follows it cannot start an identifier. If it can, then the `!` character is a separator, not a type character.\n\n\n## Keywords\n\nA *keyword* is a word that has special meaning in a\nlanguage construct. All keywords are reserved by the language and may not be used as identifiers unless the identifiers are escaped. (__Note.__ `EndIf`, `GoSub`, `Let`, `Variant`, and `Wend` are retained as keywords, although they are no longer used in Visual Basic.)\n\n```antlr\nKeyword\n    : 'AddHandler'      | 'AddressOf'      | 'Alias'       | 'And'\n    | 'AndAlso'         | 'As'             | 'Boolean'     | 'ByRef'\n\t| 'Byte'            | 'ByVal'          | 'Call'        | 'Case'        \n\t| 'Catch'           | 'CBool'          | 'CByte'       | 'CChar'       \n\t| 'CDate'           | 'CDbl'           | 'CDec'        | 'Char'        \n\t| 'CInt'            | 'Class'          | 'CLng'        | 'CObj'        \n\t| 'Const'           | 'Continue'       | 'CSByte'      | 'CShort'      \n\t| 'CSng'            | 'CStr'           | 'CType'       | 'CUInt'       \n\t| 'CULng'           | 'CUShort'        | 'Date'        | 'Decimal'     \n\t| 'Declare'         | 'Default'        | 'Delegate'    | 'Dim'         \n\t| 'DirectCast'      | 'Do'             | 'Double'      | 'Each'        \n\t| 'Else'            | 'ElseIf'         | 'End'         | 'EndIf'       \n\t| 'Enum'            | 'Erase'          | 'Error'       | 'Event'       \n\t| 'Exit'            | 'False'          | 'Finally'     | 'For'         \n\t| 'Friend'          | 'Function'       | 'Get'         | 'GetType'     \n\t| 'GetXmlNamespace' | 'Global'         | 'GoSub'       | 'GoTo'        \n\t| 'Handles'         | 'If'             | 'Implements'  | 'Imports'     \n\t| 'In'              | 'Inherits'       | 'Integer'     | 'Interface'   \n\t| 'Is'              | 'IsNot'          | 'Let'         | 'Lib'         \n\t| 'Like'            | 'Long'           | 'Loop'        | 'Me'          \n\t| 'Mod'             | 'Module'         | 'MustInherit' | 'MustOverride'\n\t| 'MyBase'          | 'MyClass'        | 'Namespace'   | 'Narrowing'   \n\t| 'New'             | 'Next'           | 'Not'         | 'Nothing'     \n\t| 'NotInheritable'  | 'NotOverridable' | 'Object'      | 'Of'          \n\t| 'On'              | 'Operator'       | 'Option'      | 'Optional'    \n\t| 'Or'              | 'OrElse'         | 'Overloads'   | 'Overridable' \n\t| 'Overrides'       | 'ParamArray'     | 'Partial'     | 'Private'     \n\t| 'Property'        | 'Protected'      | 'Public'      | 'RaiseEvent'  \n\t| 'ReadOnly'        | 'ReDim'          | 'REM'         | 'RemoveHandler'\n\t| 'Resume'          | 'Return'         | 'SByte'       | 'Select'      \n\t| 'Set'             | 'Shadows'        | 'Shared'      | 'Short'       \n\t| 'Single'          | 'Static'         | 'Step'        | 'Stop'        \n\t| 'String'          | 'Structure'      | 'Sub'         | 'SyncLock'    \n\t| 'Then'            | 'Throw'          | 'To'          | 'True'        \n\t| 'Try'             | 'TryCast'        | 'TypeOf'      | 'UInteger'    \n\t| 'ULong'           | 'UShort'         | 'Using'       | 'Variant'     \n\t| 'Wend'            | 'When'           | 'While'       | 'Widening'    \n\t| 'With'            | 'WithEvents'     | 'WriteOnly'   | 'Xor'         \n    ;\n```\n\n## Literals\n\nA *literal* is a textual representation of a particular value of a type. Literal types include Boolean, integer, floating point, string, character, and date.\n\n```antlr\nLiteral\n    : BooleanLiteral\n    | IntegerLiteral\n    | FloatingPointLiteral\n    | StringLiteral\n    | CharacterLiteral\n    | DateLiteral\n    | Nothing\n    ;\n```\n\n### Boolean Literals\n\n`True` and `False` are literals of the `Boolean` type that map to the true and false state, respectively.\n\n```antlr\nBooleanLiteral\n    : 'True' | 'False'\n    ;\n```\n\n### Integer Literals\n\nInteger literals can be decimal (base 10), hexadecimal (base 16), or octal (base 8). A decimal integer literal is a string of decimal digits (0-9). A hexadecimal literal is `&H` followed by a string of hexadecimal digits (0-9, A-F). An octal literal is `&O` followed by a string of octal digits (0-7). Decimal literals directly represent the decimal value of the integral literal, whereas octal and hexadecimal literals represent the binary value of the integer literal (thus, `&H8000S` is -32768, not an overflow error).\n\n```antlr\nIntegerLiteral\n    : IntegralLiteralValue IntegralTypeCharacter?\n    ;\n\nIntegralLiteralValue\n    : IntLiteral\n    | HexLiteral\n    | OctalLiteral\n    ;\n\nIntegralTypeCharacter\n    : ShortCharacter\n    | UnsignedShortCharacter\n    | IntegerCharacter\n    | UnsignedIntegerCharacter\n    | LongCharacter\n    | UnsignedLongCharacter\n    | IntegerTypeCharacter\n    | LongTypeCharacter\n    ;\n\nShortCharacter\n    : 'S'\n    ;\n\nUnsignedShortCharacter\n    : 'US'\n    ;\n\nIntegerCharacter\n    : 'I'\n    ;\n\nUnsignedIntegerCharacter\n    : 'UI'\n    ;\n\nLongCharacter\n    : 'L'\n    ;\n\nUnsignedLongCharacter\n    : 'UL'\n    ;\n\nIntLiteral\n    : Digit+\n    ;\n\nHexLiteral\n    : '&' 'H' HexDigit+\n    ;\n\nOctalLiteral\n    : '&' 'O' OctalDigit+\n    ;\n\nDigit\n    : '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'\n    ;\n\nHexDigit\n    : '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'\n    | 'A' | 'B' | 'C' | 'D' | 'E' | 'F'\n    ;\n\nOctalDigit\n    : '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7'\n    ;\n```\n\nThe 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. (__Note.__ There isn't a type character for `Byte` because the most natural character would be `B`, which is a legal character in a hexadecimal literal.)\n\n\n### Floating-Point Literals\n\nA floating-point literal is an integer literal followed by an optional decimal point (the ASCII period character) and mantissa, and an optional base 10 exponent. By default, a floating-point literal is of type `Double`. If the `Single`, `Double`, or `Decimal` type character is specified, the literal is of that type. If a floating-point literal's type is of insufficient size to hold the floating-point literal, a compile-time error results.\n\n__Note.__ It is worth noting that the `Decimal` data type can encode trailing zeros in a value. The specification currently makes no comment about whether trailing zeros in a `Decimal` literal should be honored by a compiler.\n\n```antlr\nFloatingPointLiteral\n    : FloatingPointLiteralValue FloatingPointTypeCharacter?\n    | IntLiteral FloatingPointTypeCharacter\n    ;\n\nFloatingPointTypeCharacter\n    : SingleCharacter\n    | DoubleCharacter\n    | DecimalCharacter\n    | SingleTypeCharacter\n    | DoubleTypeCharacter\n    | DecimalTypeCharacter\n    ;\n\nSingleCharacter\n    : 'F'\n    ;\n\nDoubleCharacter\n    : 'R'\n    ;\n\nDecimalCharacter\n    : 'D'\n    ;\n\nFloatingPointLiteralValue\n    : IntLiteral '.' IntLiteral Exponent?\n    | '.' IntLiteral Exponent?\n    | IntLiteral Exponent\n    ;\n\nExponent\n    : 'E' Sign? IntLiteral\n    ;\n\nSign\n    : '+'\n    | '-'\n    ;\n```\n\n### String Literals\n\nA string literal is a sequence of zero or more Unicode characters beginning and ending with an ASCII double-quote character, a Unicode left double-quote character, or a Unicode right double-quote character. Within a string, a sequence of two double-quote characters is an escape sequence representing a double quote in the string.\n\n```antlr\nStringLiteral\n    : DoubleQuoteCharacter StringCharacter* DoubleQuoteCharacter\n    ;\n\nDoubleQuoteCharacter\n    : '\"'\n    | '<unicode left double-quote 0x201c>'\n    | '<unicode right double-quote 0x201D>'\n    ;\n\nStringCharacter\n    : '<Any character except DoubleQuoteCharacter>'\n    | DoubleQuoteCharacter DoubleQuoteCharacter\n    ;\n```\n\nA string constant is of the `String` type.\n\n```vb\nModule Test\n    Sub Main()\n\n        ' This prints out: \".\n        Console.WriteLine(\"\"\"\")\n\n        ' This prints out: a\"b.\n        Console.WriteLine(\"a\"\"b\")\n\n        ' This causes a compile error due to mismatched double-quotes.\n        Console.WriteLine(\"a\"b\")\n    End Sub\nEnd Module\n```\n\nThe compiler is allowed to replace a constant string expression with a string literal. Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator using binary comparison semantics appear in the same program, these string literals may refer to the same string instance. For instance, the output of the following program may return `True` because the two literals may refer to the same string instance.\n\n```vb\nModule Test\n    Sub Main()\n        Dim a As Object = \"he\" & \"llo\"\n        Dim b As Object = \"hello\"\n        Console.WriteLine(a Is b)\n    End Sub\nEnd Module\n```\n\n\n### Character Literals\n\nA character literal represents a single Unicode character of the `Char` type. Two double-quote characters is an escape sequence representing the double-quote character.\n\n```antlr\nCharacterLiteral\n    : DoubleQuoteCharacter StringCharacter DoubleQuoteCharacter 'C'\n    ;\n```\n\n\n```vb\nModule Test\n    Sub Main()\n\n        ' This prints out: a.\n        Console.WriteLine(\"a\"c)\n\n        ' This prints out: \".\n        Console.WriteLine(\"\"\"\"c)\n    End Sub\nEnd Module\n```\n\n\n### Date Literals\n\nA date literal represents a particular moment in time expressed as a value of the `Date` type.\n\n```antlr\nDateLiteral\n    : '#' WhiteSpace* DateOrTime WhiteSpace* '#'\n    ;\n\nDateOrTime\n    : DateValue WhiteSpace+ TimeValue\n    | DateValue\n    | TimeValue\n    ;\n\nDateValue\n    : MonthValue '/' DayValue '/' YearValue\n    | MonthValue '-' DayValue '-' YearValue\n    ;\n\nTimeValue\n    : HourValue ':' MinuteValue ( ':' SecondValue )? WhiteSpace* AMPM?\n    | HourValue WhiteSpace* AMPM\n    ;\n\nMonthValue\n    : IntLiteral\n    ;\n\nDayValue\n    : IntLiteral\n    ;\n\nYearValue\n    : IntLiteral\n    ;\n\nHourValue\n    : IntLiteral\n    ;\n\nMinuteValue\n    : IntLiteral\n    ;\n\nSecondValue\n    : IntLiteral\n    ;\n\nAMPM\n    : 'AM' | 'PM'\n    ;    \n```\n\nThe literal may specify both a date and a time, just a date, or just a time. If the date value is omitted, then January 1 of the year 1 in the Gregorian calendar is assumed. If the time value is omitted, then 12:00:00 AM is assumed.\n\nTo avoid problems with interpreting the year value in a date value, the year value cannot be two digits. When expressing a date in the first century AD/CE, leading zeros must be specified.\n\nA time value may be specified either using a 24-hour value or a 12-hour value; time values that omit an `AM` or `PM` are assumed to be 24-hour values. If a time value omits the minutes, the literal `0` is used by default. If a time value omits the seconds, the literal `0` is used by default. If both minutes and second are omitted, then `AM` or `PM` must be specified. If the date value specified is outside the range of the `Date` type, a compile-time error occurs.\n\nThe following example contains several date literals.\n\n```vb\nDim d As Date\n\nd = # 8/23/1970 3:45:39AM #\nd = # 8/23/1970 #              ' Date value: 8/23/1970 12:00:00AM.\nd = # 3:45:39AM #              ' Date value: 1/1/1 3:45:39AM.\nd = # 3:45:39 #                ' Date value: 1/1/1 3:45:39AM.\nd = # 13:45:39 #               ' Date value: 1/1/1 1:45:39PM.\nd = # 1AM #                    ' Date value: 1/1/1 1:00:00AM.\nd = # 13:45:39PM #             ' This date value is not valid.\n```\n\n\n### Nothing\n\n`Nothing` is a special literal; it does not have a type and is convertible to all types in the type system, including type parameters. When converted to a particular type, it is the equivalent of the default value of that type.\n\n```antlr\nNothing\n    : 'Nothing'\n    ;\n```\n\n## Separators\n\nThe following ASCII characters are separators:\n\n```antlr\nSeparator\n    : '(' | ')' | '{' | '}' | '!' | '#' | ',' | '.' | ':' | '?'\n    ;\n```\n\n## Operator Characters\n\nThe following ASCII characters or character sequences denote operators:\n\n```antlr\nOperator\n    : '&' | '*' | '+' | '-' | '/' | '\\\\' | '^' | '<' | '=' | '>'\n    ;\n```\n\n"
  },
  {
    "path": "spec/overload-resolution.md",
    "content": "# Overloaded Method Resolution\n\nIn practice, the rules for determining overload resolution are intended to find the overload that is \"closest\" to the actual arguments supplied. If there is a method whose parameter types match the argument types, then that method is obviously the closest. Barring that, one method is closer than another if all of its parameter types are narrower than (or the same as) the parameter types of the other method. If neither method's parameters are narrower than the other, then there is no way for to determine which method is closer to the arguments.\n\n__Note.__ Overload resolution does not take into account the expected return type of the method. \n\nAlso note that because of the named parameter syntax, the ordering of the actual and formal parameters may not be the same.\n\nGiven a method group, the most applicable method in the group for an argument list is determined using the following steps. If, after applying a particular step, no members remain in the set, then a compile-time error occurs. If only one member remains in the set, then that member is the most applicable member. The steps are:\n\n1.  First, if no type arguments have been supplied, apply type inference to any methods which have type parameters. If type inference succeeds for a method, then the inferred type arguments are used for that particular method. If type inference fails for a method, then that method is eliminated from the set.\n\n2.  Next, eliminate all members from the set that are inaccessible or not applicable (Section [Applicability To Argument List](overload-resolution.md#applicability-to-argument-list)) to the argument list\n\n3.  Next, if one or more arguments are `AddressOf` or lambda expressions, then calculate the *delegate relaxation levels* for each such argument as below. If the worst (lowest) delegate relaxation level in `N` is worse than the lowest delegate relaxation level in `M`, then eliminate `N` from the set. The delegate relaxation levels are as follows:\n\n    31. *Error delegate relaxation level* -- if the `AddressOf` or lambda cannot be converted to the delegate type.\n  \n    32. *Narrowing delegate relaxation of return type or parameters* -- if the argument is `AddressOf` or a lambda with a declared type and the conversion from its return type to the delegate return type is narrowing; or if the argument is a regular lambda and the conversion from any of its return expressions to the delegate return type is narrowing, or if the argument is an async lambda and the delegate return type is `Task(Of T)` and the conversion from any of its return expressions to `T` is narrowing; or if the argument is an iterator lambda and the delegate return type `IEnumerator(Of T)` or `IEnumerable(Of T)` and the conversion from any of its yield operands to `T` is narrowing.\n\n    33. *Widening delegate relaxation to delegate without signature* -- if delegate type is `System.Delegate` or `System.MultiCastDelegate` or `System.Object`.\n\n    34. *Drop return or arguments delegate relaxation* -- if the argument is `AddressOf` or a lambda with a declared return type and the delegate type lacks a return type; or if the argument is a lambda with one or more return expressions and the delegate type lacks a return type; or if the argument is `AddressOf` or lambda with no parameters and the delegate type has parameters.\n\n    35. *Widening delegate relaxation of return type* -- if the argument is `AddressOf` or a lambda with a declared return type, and there is a widening conversion from its return type to that of the delegate; or if the argument is a regular lambda where the conversion from all return expressions to the delegate return type is widening or identity with at least one widening; or if the argument is an async lambda and the delegate is `Task(Of T)` or `Task` and the conversion from all return expressions to `T`/`Object` respectively is widening or identity with at least one widening; or if the argument is an iterator lambda and the delegate is `IEnumerator(Of T)` or `IEnumerable(Of T)` or `IEnumerator` or `IEnumerable` and the conversion from all return expressions to `T`/`Object` is widening or identity with at least one widening.\n\n    36. *Identity delegate relaxation* -- if the argument is an `AddressOf` or a lambda which matches the delegate exactly, with no widening or narrowing or dropping of parameters or returns or yields.Next, if some members of the set do not requiring narrowing conversions to be applicable to any of the arguments, then eliminate all members that do. For example:\n\n    ```vb\n    Sub f(x As Object)\n    End Sub\n\n    Sub f(x As Short)\n    End Sub\n\n    Sub f(x As Short())\n    End Sub\n\n    f(\"5\") ' picks the Object overload, since String->Short is narrowing\n    f(5)   ' picks the Object overload, since Integer->Short is narrowing\n    f({5}) ' picks the Object overload, since Integer->Short is narrowing\n    f({})  ' a tie-breaker rule subsequent to [3] picks the Short() overload\n\n    ```\n\n4.  Next, elimination is done based on narrowing as follows. (Note that, if Option Strict is On, then all members that require narrowing have already been judged inapplicable (Section [Applicability To Argument List](overload-resolution.md#applicability-to-argument-list)) and removed by Step 2.)\n\n    41. If some instance members of the set only require narrowing conversions where the argument expression type is `Object`, then eliminate all other members.\n    42. If the set contains more than one member which requires narrowing only from `Object`, then the invocation target expression is reclassified as a late-bound method access (and an error is given if the type containing the method group is an interface, or if any of the applicable members were extension members).\n    43. If there are any candidates that only require narrowing from numeric literals, then chose the most specific among all remaining candidates by the steps below. If the winner requires only narrowing from numeric literals, then it is picked as the result of overload resolution; otherwise it is an error.\n\n    __Note.__ The justification for this rule is that if a program is loosely-typed (that is, most or all variables are declared as `Object`), overload resolution can be difficult when many conversions from `Object` are narrowing. Rather than have the overload resolution fail in many situations (requiring strong typing of the arguments to the method call), resolution the appropriate overloaded method to call is deferred until run time. This allows the loosely-typed call to succeed without additional casts. An unfortunate side-effect of this, however, is that performing the late-bound call requires casting the call target to `Object`. In the case of a structure value, this means that the value must be boxed to a temporary. If the method eventually called tries to change a field of the structure, this change will be lost once the method returns. Interfaces are excluded from this special rule because late binding always resolves against the members of the runtime class or structure type, which may have different names than the members of the interfaces they implement.\n\n5.  Next, if any instance methods remain in the set which do not require narrowing, then eliminate all extension methods from the set. For example:\n\n    ```vb\n    Imports System.Runtime.CompilerServices\n\n    Class C3\n        Sub M1(d As Integer)\n        End Sub\n    End Class\n\n    Module C3Extensions\n        <Extension> _\n        Sub M1(c3 As C3, c As Long)\n        End Sub\n\n        <Extension> _\n        Sub M1(c3 As C3, c As Short)\n        End Sub\n    End Module\n\n    Module Test\n        Sub Main()\n            Dim c As New C3()\n            Dim sVal As Short = 10\n            Dim lVal As Long = 20\n\n            ' Calls C3.M1, since C3.M1 is applicable.\n            c.M1(sVal)\n\n            ' Calls C3Extensions.M1 since C3.M1 requires a narrowing conversion\n            c.M1(lVal)\n        End Sub\n    End Module\n    ```\n\n    __Note.__ Extension methods are ignored if there are applicable instance methods to guarantee that adding an import (that might bring new extension methods into scope) will not cause a call on an existing instance method to rebind to an extension method. Given the broad scope of some extension methods (i.e. those defined on interfaces and/or type parameters), this is a safer approach to binding to extension methods.\n\n6.  Next, if, given any two members of the set `M` and `N`, `M` is more *specific* (Section [Specificity of members/types given an argument list](overload-resolution.md#specificity-of-memberstypes-given-an-argument-list)) than `N` given the argument list, eliminate `N` from the set. If more than one member remains in the set and the remaining members are not equally specific given the argument list, a compile-time error results.\n\n7.  Otherwise, given any two members of the set, `M` and `N`, apply the following tie-breaking rules, in order:\n\n    71. If `M` does not have a ParamArray parameter but `N` does, or if both do but `M` passes fewer arguments into the ParamArray parameter than `N` does, then eliminate `N` from the set. For example:\n\n        ```vb\n        Module Test\n            Sub F(a As Object, ParamArray b As Object())\n                Console.WriteLine(\"F(Object, Object())\")\n            End Sub\n\n            Sub F(a As Object, b As Object, ParamArray c As Object())\n                Console.WriteLine(\"F(Object, Object, Object())\")\n            End Sub\n\n           Sub G(Optional a As Object = Nothing)\n              Console.WriteLine(\"G(Object)\")\n           End Sub\n\n           Sub G(ParamArray a As Object())\n              Console.WriteLine(\"G(Object())\")\n           End Sub    Sub Main()\n                F(1)\n                F(1, 2)\n                F(1, 2, 3)\n              G()\n            End Sub\n        End Module\n        ```\n\n        The above example produces the following output:\n\n        ```console\n        F(Object, Object())\n        F(Object, Object, Object())\n        F(Object, Object, Object())\n        G(Object)\n        ```\n\n        __Note.__ When a class declares a method with a paramarray parameter, it is not uncommon to also include some of the expanded forms as regular methods. By doing so it is possible to avoid the allocation of an array instance that occurs when an expanded form of a method with a paramarray parameter is invoked.\n\n    72. If `M` is defined in a more derived type than `N`, eliminate `N` from the set. For example:\n\n        ```vb\n        Class Base\n            Sub F(Of T, U)(x As T, y As U)\n            End Sub\n        End Class\n\n        Class Derived\n            Inherits Base\n\n            Overloads Sub F(Of T, U)(x As U, y As T)\n            End Sub\n        End Class\n\n        Module Test\n            Sub Main()\n                Dim d As New Derived()\n\n                ' Calls Derived.F\n                d.F(10, 10)\n            End Sub\n        End Module\n        ```\n\n        This rule also applies to the types that extension methods are defined on. For example:\n\n        ```vb\n        Imports System.Runtime.CompilerServices\n\n        Class Base\n        End Class\n\n        Class Derived\n            Inherits Base\n        End Class\n\n        Module BaseExt\n            <Extension> _\n            Sub M(b As Base, x As Integer)\n            End Sub\n        End Module\n\n        Module DerivedExt\n            <Extension> _\n            Sub M(d As Derived, x As Integer)\n            End Sub\n        End Module\n\n        Module Test\n            Sub Main()\n                Dim b As New Base()\n                Dim d As New Derived()\n\n                ' Calls BaseExt.M\n                b.M(10)\n\n                ' Calls DerivedExt.M \n                d.M(10)\n            End Sub\n        End Module\n        ```\n\n    73. If `M` and `N` are extension methods and the target type of `M` is a class or structure and the target type of `N` is an interface, eliminate `N` from the set. For example:\n\n        ```vb\n        Imports System.Runtime.CompilerServices\n\n        Interface I1\n        End Interface\n\n        Class C1\n            Implements I1\n        End Class\n\n        Module Ext1\n            <Extension> _\n            Sub M(i As I1, x As Integer)\n            End Sub\n        End Module\n\n        Module Ext2\n            <Extension> _\n            Sub M(c As C1, y As Integer)\n            End Sub\n        End Module\n\n        Module Test\n            Sub Main()\n                Dim c As New C1()\n\n                ' Calls Ext2.M, because Ext1.M is hidden since it extends\n                ' an interface.\n                c.M(10)\n\n                ' Calls Ext1.M\n                CType(c, I1).M(10)\n            End Sub\n        End Module\n        ```\n\n    74. If `M` and `N` are extension methods, and the target type of `M` and `N` are identical after type parameter substitution, and the target type of `M` before type parameter substitution does not contain type parameters but the target type of `N` does, then has fewer type parameters than the target type of `N`, eliminate `N` from the set. For example:\n\n        ```vb\n        Imports System.Runtime.CompilerServices\n\n        Module Module1\n            Sub Main()\n                Dim x As Integer = 1\n                x.f(1) ' Calls first \"f\" extension method\n\n                Dim y As New Dictionary(Of Integer, Integer)\n                y.g(1) ' Ambiguity error\n            End Sub\n\n            <Extension()> Sub f(x As Integer, z As Integer)\n            End Sub\n\n            <Extension()> Sub f(Of T)(x As T, z As T)\n            End Sub\n\n            <Extension()> Sub g(Of T)(y As Dictionary(Of T, Integer), z As T)\n            End Sub\n\n            <Extension()> Sub g(Of T)(y As Dictionary(Of T, T), z As T)\n            End Sub\n        End Module\n        ```\n\n    75. Before type arguments have been substituted, if `M` is *less generic* (Section [Genericity](overload-resolution.md#genericity)) than `N`, eliminate `N` from the set.\n\n    76. If `M` is not an extension method and `N` is, eliminate `N` from the set.\n\n    77. If `M` and `N` are extension methods and `M` was found before `N` (Section [Extension Method Collection](expressions.md#extension-method-collection)), eliminate `N` from the set. For example:\n\n        ```vb\n        Imports System.Runtime.CompilerServices\n\n        Class C1\n        End Class\n\n        Namespace N1\n            Module N1C1Extensions\n                <Extension> _\n                Sub M1(c As C1, x As Integer)\n                End Sub\n            End Module\n        End Namespace\n\n        Namespace N1.N2\n            Module N2C1Extensions\n                <Extension> _\n                Sub M1(c As C1, y As Integer)\n                End Sub\n            End Module\n        End Namespace\n\n        Namespace N1.N2.N3\n            Module Test\n                Sub Main()\n                    Dim x As New C1()\n\n                    ' Calls N2C1Extensions.M1\n                    x.M1(10)\n                End Sub\n            End Module\n        End Namespace\n        ```\n\n        If the extension methods were found in the same step, then those extension methods are ambiguous. The call may always be disambiguated using the name of the standard module containing the extension method and calling the extension method as if it was a regular member. For example:\n\n        ```vb\n        Imports System.Runtime.CompilerServices\n\n        Class C1\n        End Class\n\n        Module C1ExtA\n            <Extension> _\n            Sub M(c As C1)\n            End Sub\n        End Module\n\n        Module C1ExtB\n            <Extension> _\n            Sub M(c As C1)\n            End Sub\n        End Module\n\n        Module Main\n            Sub Test()\n                Dim c As New C1()\n\n                C1.M()               ' Ambiguous between C1ExtA.M and BExtB.M\n                C1ExtA.M(c)          ' Calls C1ExtA.M\n                C1ExtB.M(c)          ' Calls C1ExtB.M\n            End Sub\n        End Module\n        ```\n\n    78. If `M` and `N` both required type inference to produce type arguments, and `M` did not require determining the dominant type for any of its type arguments (i.e. each the type arguments inferred to a single type), but `N` did, eliminate `N` from the set.\n\n        __Note.__ This rule ensures that overload resolution that succeeded in previous versions (where inferring multiple types for a type argument would cause an error), continue to produce the same results.\n\n    79. If overload resolution is being done to resolve the target of a delegate-creation expression from an `AddressOf` expression, and both the delegate and `M` are functions while `N` is a subroutine, eliminate `N` from the set. Likewise, if both the delegate and `M` are subroutines, while `N` is a function, eliminate `N` from the set.\n\n    710. If `M` did not use any optional parameter defaults in place of explicit arguments, but `N` did, then eliminate `N` from the set.\n\n    711. Before type arguments have been substituted, if `M` has *greater depth of genericity* (Section [Genericity](overload-resolution.md#genericity)) than `N`, then eliminate `N` from the set.\n\n8. Otherwise, the call is ambiguous and a compile-time error occurs.\n\n#### Specificity of members/types given an argument list\n\nA member `M` is considered *equally specific* as `N`, given an argument-list `A`, if their signatures are the same or if each parameter type in `M` is the same as the corresponding parameter type in `N`.\n\n__Note.__ Two members can end up in a method group with the same signature due to extension methods. Two members can also be equally specific but not have the same signature due to type parameters or paramarray expansion.\n\nA member `M` is considered *more specific* than `N` if their signatures are different and at least one parameter type in `M` is more specific than a parameter type in `N`, and no parameter type in `N` is more specific than a parameter type in `M`. Given a pair of parameters `Mj` and `Nj` that matches an argument `Aj`, the type of `Mj` is considered *more specific* than the type of `Nj` if one of the following conditions is true:\n\n* There exists a widening conversion from the type of `Mj` to the type `Nj`. (__Note.__ Because parameters types are being compared without regard to the actual argument in this case, the widening conversion from constant expressions to a numeric type the value fits into is not considered in this case.)\n\n* `Aj` is the literal `0`, `Mj` is a numeric type and `Nj` is an enumerated type. (__Note.__ This rule is necessary because the literal `0` widens to any enumerated type. Since an enumerated type widens to its underlying type, this means that overload resolution on `0` will, by default, prefer enumerated types over numeric types. We received a lot of feedback that this behavior was counterintuitive.)\n\n* `Mj` and `Nj` are both numeric types, and `Mj` comes earlier than `Nj` in the list\n`Byte`, `SByte`, `Short`, `UShort`, `Integer`, `UInteger`, `Long`, `ULong`, `Decimal`, `Single`, `Double`. (__Note.__ The rule about the numeric types is useful because the signed and unsigned numeric types of a particular size only have narrowing conversions between them. The above rule breaks the tie between the two types in favor of the more \"natural\" numeric type. This is particularly important when doing overload resolution on a type that widens to both the signed and unsigned numeric types of a particular size, for example, a numeric literal that fits into both.)\n\n* `Mj` and `Nj` are delegate function types and the return type of `Mj` is more specific than the return type of `Nj` If `Aj` is classified as a lambda method, and `Mj` or `Nj` is `System.Linq.Expressions.Expression(Of T)`, then the type argument of the type (assuming it is a delegate type) is substituted for the type being compared.\n\n* `Mj` is identical to the type of `Aj`, and `Nj` is not. (__Note.__ It is interesting to note that the previous rule differs slightly from C#, in that C# requires that the delegate function types have identical parameter lists before comparing return types, while Visual Basic does not.)\n\n#### Genericity\n\nA member `M` is determined to be *less generic* than a member `N` as follows:\n\n1. If, for each pair of matching parameters `Mj` and `Nj`, `Mj` is less or equally generic than `Nj` with respect to type parameters on the method, and at least one `Mj` is less generic with respect to type parameters on the method.\n2. Otherwise, if for each pair of matching parameters `Mj` and `Nj`, `Mj` is less or equally generic than `Nj` with respect to type parameters on the type, and at least one `Mj` is less generic with respect to type parameters on the type, then `M` is less generic than `N`.\n\nA parameter `M` is considered to be equally generic to a parameter `N` if their types `Mt` and `Nt` both refer to type parameters or both don't refer to type parameters. `M` is considered to be less generic than `N` if `Mt` does not refer to a type parameter and `Nt` does.\n\nFor example:\n\n```vb\nClass C1(Of T)\n    Sub S1(Of U)(x As U, y As T)\n    End Sub\n\n    Sub S1(Of U)(x As U, y As U)\n    End Sub\n\n    Sub S2(x As Integer, y As T)\n    End Sub\n\n    Sub S2(x As T, y As T)\n    End Sub\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim x As C1(Of Integer) = New C1(Of Integer)\n\n        x.S1(10, 10)    ' Calls S1(U, T)\n        x.S2(10, 10)    ' Calls S2(Integer, T)\n    End Sub\nEnd Module\n```\n\nExtension method type parameters that were fixed during currying are considered type parameters on the type, not type parameters on the method. For example:\n\n```vb\nImports System.Runtime.CompilerServices\n\nModule Ext1\n    <Extension> _\n    Sub M1(Of T, U)(x As T, y As U, z As U)\n    End Sub\nEnd Module\n\nModule Ext2\n    <Extension> _\n    Sub M1(Of T, U)(x As T, y As U, z As T)\n    End Sub\nEnd Module\n\nModule Test\n    Sub Main()\n        Dim i As Integer = 10\n\n        i.M1(10, 10)\n    End Sub\nEnd Module\n```\n\n#### Depth of genericity\n\nA member `M` is determined to have *greater depth of genericity* than a member `N` if, for each pair of matching parameters  `Mj` and `Nj`, `Mj` has greater or equal *depth of genericity* than `Nj`, and at least one `Mj` is has greater depth of genericity. Depth of genericity is defined as follows:\n\n* Anything other than a type parameter has greater depth of genericity than a type parameter;\n\n* Recursively, a constructed type has greater depth of genericity than another constructed type (with the same number of type arguments) if at least one type argument has greater depth of genericity and no type argument has less depth than the corresponding type argument in the other.\n\n* An array type has greater depth of genericity than another array type (with the same number of dimensions) if the element type of the first has greater depth of genericity than the element type of the second.\n\nFor example:\n\n```vb\nModule Test\n\n    Sub f(Of T)(x As Task(Of T))\n    End Sub\n\n    Sub f(Of T)(x As T)\n    End Sub\n\n    Sub Main()\n        Dim x As Task(Of Integer) = Nothing\n        f(x)            ' Calls the first overload\n    End Sub\nEnd Module\n```\n\n### Applicability To Argument List\n\nA method is *applicable* to a set of type arguments, positional arguments, and named arguments if the method can be invoked using the argument lists. The argument lists are matched against the parameter lists as follows:\n\n1. First, match each positional argument in order to the list of method parameters. If there are more positional arguments than parameters and the last parameter is not a paramarray, the method is not applicable. Otherwise, the paramarray parameter is expanded with parameters of the paramarray element type to match the number of positional arguments. If a positional argument is omitted that would go into a paramarray, the method is not applicable.\n2. Next, match each named argument to a parameter with the given name. If one of the named arguments fails to match, matches a paramarray parameter, or matches an argument already matched with another positional or named argument, the method is not applicable.\n3. Next, if type arguments have been specified, they are matched against the type parameter list . If the two lists do not have the same number of elements, the method is not applicable, unless the type argument list is empty. If the type argument list is empty, type inference is used to try and infer the type argument list. If type inferencing fails, the method is not applicable. Otherwise, the type arguments are filled in the place of the type parameters in the signature.If parameters that have not been matched are not optional, the method is not applicable.\n4. If the argument expressions are not implicitly convertible to the types of the parameters they match, then the method is not applicable.\n5. If a parameter is ByRef, and there is not an implicit conversion from the type of the parameter to the type of the argument, then the method is not applicable.\n6. If type arguments violate the method's constraints (including the inferred type arguments from Step 3), the method is not applicable. For example:\n\n```vb\nModule Module1\n    Sub Main()\n        f(Of Integer)(New Exception)\n        ' picks the first overload (narrowing),\n        ' since the second overload (widening) violates constraints \n    End Sub\n\n    Sub f(Of T)(x As IComparable)\n    End Sub\n\n    Sub f(Of T As Class)(x As Object)\n    End Sub\nEnd Module\n```\n\nIf a single argument expression matches a paramarray parameter and the type of the argument expression is convertible to both the type of the paramarray parameter and the paramarray element type, the method is applicable in both its expanded and unexpanded forms, with two exceptions. If the conversion from the type of the argument expression to the paramarray type is narrowing, then the method is only applicable in its expanded form. If the argument expression is the literal `Nothing`, then the method is only applicable in its unexpanded form. For example:\n\n```vb\nModule Test\n    Sub F(ParamArray a As Object())\n        Dim o As Object\n\n        For Each o In a\n            Console.Write(o.GetType().FullName)\n            Console.Write(\" \")\n        Next o\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Dim a As Object() = { 1, \"Hello\", 123.456 }\n        Dim o As Object = a\n\n        F(a)\n        F(CType(a, Object))\n        F(o)\n        F(CType(o, Object()))\n    End Sub\nEnd Module\n```\n\nThe above example produces the following output:\n\n```console\nSystem.Int32 System.String System.Double\nSystem.Object[]\nSystem.Object[]\nSystem.Int32 System.String System.Double\n```\n\nIn the first and last invocations of `F`, the normal form of `F` is applicable because a widening conversion exists from the argument type to the parameter type (both are of type `Object()`), and the argument is passed as a regular value parameter. In the second and third invocations, the normal form of `F` is not applicable because no widening conversion exists from the argument type to the parameter type (conversions from `Object` to `Object()` are narrowing). However, the expanded form of `F` is applicable, and a one-element `Object()` is created by the invocation. The single element of the array is initialized with the given argument value (which itself is a reference to an `Object()`).\n\n### Passing Arguments, and Picking Arguments for Optional Parameters\n\nIf a parameter is a value parameter, the matching argument expression must be classified as a value. The value is converted to the type of the parameter and passed in as the parameter at run time. If the parameter is a reference parameter and the matching argument expression is classified as a variable whose type is the same as the parameter, then a reference to the variable is passed in as the parameter at run time.\n\nOtherwise, if the matching argument expression is classified as a variable, value, or property access, then a temporary variable of the type of the parameter is allocated. Before the method invocation at run time, the argument expression is reclassified as a value, converted to the type of the parameter, and assigned to the temporary variable. Then a reference to the temporary variable is passed in as the parameter. After the method invocation is evaluated, if the argument expression is classified as a variable or property access, the temporary variable is assigned to the variable expression or the property access expression. If the property access expression has no `Set` accessor, then the assignment is not performed.\n\nFor optional parameters where an argument has not been provided, the compiler picks arguments as described below. In all cases it tests against the parameter type after generic type substitution.\n\n* If the optional parameter has the attribute `System.Runtime.CompilerServices.CallerLineNumber`, and the invocation is from a location in source code, and a numeric literal representing that location's line number has an intrinsic conversion to the parameter type, then the numeric literal is used. If the invocation spans multiple lines, then the choice of which line to use is implementation-dependent.\n\n* If the optional parameter has the attribute `System.Runtime.CompilerServices.CallerFilePath`, and the invocation is from a location in source code, and a string literal representing that location's file path has an intrinsic conversion to the parameter type, then the string literal is used. The format of the file path is implementation-dependent.\n\n* If the optional parameter has the attribute `System.Runtime.CompilerServices.CallerMemberName`, and the invocation is within the body of a type member or in an attribute applied to any part of that type member, and a string literal representing that member name has an intrinsic conversion to the parameter type, then the string literal is used. For invocations that are part of property accessors or custom event handlers, then the member name used is that of the property or event itself. For invocations that are part of an operator or constructor, then an implementation-specific name is used.\n\nIf none of the above apply, then the optional parameter's default value is used (or `Nothing` if no default value is supplied). And if more than one of the above apply, then the choice of which to use is implementation-dependent.\n\nThe `CallerLineNumber` and `CallerFilePath` attributes are useful for logging. The `CallerMemberName` is useful for implementing `INotifyPropertyChanged`. Here are examples.\n\n```vb\nSub Log(msg As String,\n        <CallerFilePath> Optional file As String = Nothing,\n        <CallerLineNumber> Optional line As Integer? = Nothing)\n    Console.WriteLine(\"{0}:{1} - {2}\", file, line, msg)\nEnd Sub\n\nWriteOnly Property p As Integer\n    Set(value As Integer)\n        Notify(_p, value)\n    End Set\nEnd Property\n\nPrivate _p As Integer\n\nSub Notify(Of T As IEquatable(Of T))(ByRef v1 As T, v2 As T,\n        <CallerMemberName> Optional prop As String = Nothing)\n    If v1 IsNot Nothing AndAlso v1.Equals(v2) Then Return\n    If v1 Is Nothing AndAlso v2 Is Nothing Then Return\n    v1 = v2\n    RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(prop))\nEnd Sub\n```\n\nIn addition to the optional parameters above, Microsoft Visual Basic also recognizes some additional optional parameters if they are imported from metadata (i.e. from a DLL reference):\n\n* Upon importing from metadata, Visual Basic also treats the parameter `<Optional>` as indicative that the parameter is optional: in this way it is possible to import a declaration which has an optional parameter but no default value, even though this can't be expressed using the `Optional` keyword.\n\n* If the optional parameter has the attribute `Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute`, and the numeric literal 1 or 0 has a conversion to the parameter type, then the compiler uses as argument either the literal 1 if `Option Compare Text` is in effect, or the literal 0 if `Optional Compare Binary` is in effect.\n\n* If the optional parameter has the attribute `System.Runtime.CompilerServices.IDispatchConstantAttribute`, and it has type `Object`, and it does not specify a default value, then the compiler uses the argument `New System.Runtime.InteropServices.DispatchWrapper(Nothing)`.\n\n* If the optional parameter has the attribute `System.Runtime.CompilerServices.IUnknownConstantAttribute`, and it has type `Object`, and it does not specify a default value, then the compiler uses the argument `New System.Runtime.InteropServices.UnknownWrapper(Nothing)`.\n\n* If the optional parameter has type `Object`, and it does not specify a default value, then the compiler uses the argument `System.Reflection.Missing.Value`.\n\n### Conditional Methods\n\nIf the target method to which an invocation expression refers is a subroutine that is not a member of an interface and if the method has one or more `System.Diagnostics.ConditionalAttribute` attributes, evaluation of the expression depends on the conditional compilation constants defined at that point in the source file. Each instance of the attribute specifies a string, which names a conditional compilation constant. Each conditional compilation constant is evaluated as if it were part of a conditional compilation statement. If the constant evaluates to `True`, the expression is evaluated normally at run time. If the constant evaluates to `False`, the expression is not evaluated at all.\n\nWhen looking for the attribute, the most derived declaration of an overridable method is checked.\n\n__Note.__ The attribute is not valid on functions or interface methods and is ignored if specified on either kind of method. Thus, conditional methods will only appear in invocation statements.\n\n### Type Argument Inference\n\nWhen a method with type parameters is called without specifying type arguments, *type argument inference* is used to try and infer type arguments for the call. This allows a more natural syntax to be used for calling a method with type parameters when the type arguments can be trivially inferred. For example, given the following method declaration:\n\n```vb\nModule Util\n    Function Choose(Of T)(b As Boolean, first As T, second As T) As T\n        If b Then\n            Return first\n        Else\n            Return second\n        End If\n    End Function\nEnd Class\n```\n\nit is possible to invoke the `Choose` method without explicitly specifying a type argument:\n\n```vb\n' calls Choose(Of Integer)\nDim i As Integer = Util.Choose(True, 5, 213)\n' calls Choose(Of String)\nDim s As String = Util.Choose(False, \"a\", \"b\") \n```\n\nThrough type argument inference, the type arguments `Integer` and `String` are determined from the arguments to the method.\n\nType argument inference occurs *before* expression reclassification is performed on lambda methods or method pointers in the argument list, since reclassification of those two kinds of expressions may require the type of the parameter to be known.  Given a set of arguments `A1,...,An`, a set of matching parameters `P1,...,Pn` and a set of method type parameters `T1,...,Tn`, the dependencies between the arguments and method type parameters are first collected as follows:\n\n* If `An` is the `Nothing` literal, no dependencies are generated.\n\n* If `An` is a lambda method and the type of `Pn` is a constructed delegate type or `System.Linq.Expressions.Expression(Of T)`, where `T` is a constructed delegate type,\n\n* If the type of a lambda method parameter will be inferred from the type of the corresponding parameter `Pn`, and the type of the parameter depends on a method type parameter `Tn`, then `An` has a dependency on `Tn`.\n\n* If the type of a lambda method parameter is specified and the type of the corresponding parameter `Pn` depends on a method type parameter `Tn`, then `Tn` has a dependency on `An`.\n\n* If the return type of `Pn` depends on a method type parameter `Tn`, then `Tn` has a dependency on `An`.\n\n* If `An` is a method pointer and the type of `Pn` is a constructed delegate type,\n\n* If the return type of `Pn` depends on a method type parameter `Tn`, then `Tn` has a dependency on `An`.\n\n* If `Pn` is a constructed type and the type of `Pn` depends on a method type parameter `Tn`, then `Tn` has a dependency on `An`.\n\n* Otherwise, no dependency is generated.\n\nAfter collecting dependencies, any arguments that have no dependencies are eliminated. If any method type parameters have no outgoing dependencies (i.e. the method type parameter does not depend on an argument), then type inference fails. Otherwise, the remaining arguments and method type parameters are grouped into strongly connected components. A strongly connected component is a set of arguments and method type parameters, where any element in the component is reachable via dependencies on other elements.\n\nThe strongly connected components are then topologically sorted and processed in topological order:\n\n* If the strongly typed component contains only one element,\n\n  * If the element has already been marked complete, skip it.\n\n  * If the element is an argument, then add type hints from the argument to the method type parameters that depend on it and mark the element as complete. If the argument is a lambda method with parameters that still need inferred types, then infer `Object` for the types of those parameters.\n\n  * If the element is a method type parameter, then infer the method type parameter to be the dominant type among the argument type hints and mark the element as complete. If a type hint has an array element restriction on it, then only conversions that are valid between arrays of the given type are considered (i.e. covariant and intrinsic array conversions). If a type hint has a generic argument restriction on it, then only identity conversions are considered. If no dominant type can be chosen, inference fails. If any lambda method argument types depend on this method type parameter, the type is propagated to the lambda method.\n\n* If the strongly typed component contains more than one element, then the component contains a cycle.\n\n  * For each method type parameter that is an element in the component, if the method type parameter depends on an argument that is not marked complete, convert that dependency into an assertion that will be checked at the end of the inference process.\n\n  * Restart the inference process at the point at which the strongly typed components were determined.\n\nIf type inference succeeds for all of the method type parameters, then any dependencies that were changed into assertions are checked. An assertion succeeds if the type of the argument is implicitly convertible to the inferred type of the method type parameter. If an assertion fails, then type argument inference fails.\n\nGiven an argument type `Ta` for an argument `A` and a parameter type `Tp` for a parameter `P`, type hints are generated as follows:\n\n* If `Tp` does not involve any method type parameters then no hints are generated.\n\n* If `Tp` and `Ta` are array types of the same rank, then replace `Ta` and `Tp` with the element types of `Ta` and `Tp` and restart this process with an array element restriction.\n\n* If `Tp` is a method type parameter, then `Ta` is added as a type hint with the current restriction, if any.\n\n* If `A` is a lambda method and `Tp` is a constructed delegate type or `System.Linq.Expressions.Expression(Of T)`, where `T` is a constructed delegate type, for each lambda method parameter type `TL` and corresponding delegate parameter type `TD`, replace `Ta` with `TL` and `Tp` with `TD` and restart the process with no restriction. Then, replace `Ta` with the return type of the lambda method and:\n\n  * if `A` is a regular lambda method, replace `Tp` with the return type of the delegate type;\n  * if `A` is an async lambda method and the return type of the delegate type has form `Task(Of T)` for some `T`, replace `Tp` with that `T`;\n  * if `A` is an iterator lambda method and the return type of the delegate type has form `IEnumerator(Of T)` or `IEnumerable(Of T)` for some `T`, replace `Tp` with that `T`.\n  * Next, restart the process with no restriction.\n\n* If `A` is a method pointer and `Tp` is a constructed delegate type, use the parameter types of `Tp` to determine which method pointed is most applicable to `Tp`. If there is a method that is most applicable, replace `Ta` with the return type of the method and `Tp` with the return type of the delegate type and restart the process with no restriction.\n\n* Otherwise, `Tp` must be a constructed type. Given `TG`, the generic type of `Tp`,\n\n  * If `Ta` is `TG`, inherits from `TG`, or implements the type `TG` exactly once, then for each matching type argument `Tax` from `Ta` and `Tpx` from `Tp`, replace `Ta` with `Tax` and `Tp` with `Tpx` and restart the process with a generic argument restriction.\n\n  * Otherwise, type inference fails for the generic method.\n\nThe success of type inference does not, in and of itself, guarantee that the method is applicable.\n"
  },
  {
    "path": "spec/preprocessing-directives.md",
    "content": "# Preprocessing Directives\n\nOnce a file has been lexically analyzed, several kinds of source preprocessing occur. The most important, conditional compilation, determines which source is processed by the syntactic grammar; two other types of directives -- external source directives and region directives -- provide meta-information about the source but have no effect on compilation.\n\n## Conditional Compilation\n\nConditional compilation controls whether sequences of logical lines are translated into actual code. At the beginning of conditional compilation, all logical lines are enabled; however, enclosing lines in conditional compilation statements may selectively disable those lines within the file, causing them to be ignored during the rest of the compilation process.\n\n```antlr\nCCStart\n    : CCStatement*\n    ;\n\nCCStatement\n    : CCConstantDeclaration\n    | CCIfGroup\n    | LogicalLine\n    ;\n\nCCExpression\n    : LiteralExpression\n    | CCParenthesizedExpression\n    | CCSimpleNameExpression\n    | CCCastExpression\n    | CCOperatorExpression\n    | CCConditionalExpression\n    ;\n\nCCParenthesizedExpression\n    : '(' CCExpression ')'\n    ;\n\nCCSimpleNameExpression\n    : Identifier\n    ;\n\nCCCastExpression\n    : 'DirectCast' '(' CCExpression ',' TypeName ')'\n    | 'TryCast' '(' CCExpression ',' TypeName ')'\n    | 'CType' '(' CCExpression ',' TypeName ')'\n    | CastTarget '(' CCExpression ')'\n    ;\n\nCCOperatorExpression\n    : CCUnaryOperator CCExpression\n    | CCExpression CCBinaryOperator CCExpression\n    ;\n\nCCUnaryOperator\n    : '+' | '-' | 'Not'\n    ;\n\nCCBinaryOperator\n    : '+'     | '-'     | '*'   | '/'       | '\\\\'     | 'Mod' | '^' | '='\n    | '<' '>' | '<'     | '>'   | '<' '='   | '>' '='  | '&'\n    | 'And'   | 'Or'    | 'Xor' | 'AndAlso' | 'OrElse'\n    | '<' '<' | '>' '>'\n    ;\n\nCCConditionalExpression\n    : 'If' '(' CCExpression ',' CCExpression ',' CCExpression ')'\n    | 'If' '(' CCExpression ',' CCExpression ')'\n    ;\n```\n\n\nFor example, the program\n\n```vb\n#Const A = True\n#Const B = False\n\nClass C\n\n#If A Then\n    Sub F()\n    End Sub\n#Else\n    Sub G()\n    End Sub\n#End If\n\n#If B Then\n    Sub H()\n    End Sub\n#Else\n    Sub I()\n    End Sub\n#End If\n\nEnd Class\n```\n\nproduces the exact same sequence of tokens as the program\n\n```vb\nClass C\n    Sub F()\n    End Sub\n\n    Sub I()\n    End Sub\nEnd Class\n```\n\nThe constant expressions allowed in conditional compilation directives are a subset of general constant expressions.\n\nThe preprocessor allows whitespace and explicit line continuations before and after every token.\n\n\n### Conditional Constant Directives\n\nConditional constant statements define constants that exist in a separate conditional compilation declaration space scoped to the source file.\n\n```antlr\nCCConstantDeclaration\n    : '#' 'Const' Identifier '=' CCExpression LineTerminator\n    ;\n```\n\nThe declaration space is special in that no explicit declaration of conditional compilation constants is necessary -- conditional constants can be implicitly defined in a conditional compilation directive.\n\nPrior to being assigned a value, a conditional compilation constant has the value `Nothing`. When a conditional compilation constant is assigned a value, which must be a constant expression, the type of the constant becomes the type of the value being assigned to it. A conditional compilation constant may be redefined multiple times throughout a source file.\n\nFor example, the following code prints only the string `about to print value` and the value of `Test`.\n\n```vb\nModule M1\n    Sub PrintValue(Test As Integer)\n\n#Const DebugCode = True\n\n#If DebugCode Then\n        Console.WriteLine(\"about to print value\")\n#End If\n\n#Const DebugCode = False\n\n        Console.WriteLine(Test)\n\n#If DebugCode Then\n        Console.WriteLine(\"printed value\")\n#End If\n\n    End Sub\nEnd Module\n```\n\nThe compilation environment may also define conditional constants in a conditional compilation declaration space.\n\n\n### Conditional Compilation Directives\n\nConditional compilation directives control conditional compilation.\n\n```antlr\nCCIfGroup\n    : '#' 'If' CCExpression 'Then'? LineTerminator CCStatement*\n    CCElseIfGroup* CCElseGroup? '#' 'End' 'If' LineTerminator\n    ;\n\nCCElseIfGroup\n    : '#' ElseIf CCExpression 'Then'? LineTerminator CCStatement*\n    ;\n\nCCElseGroup\n    : '#' 'Else' LineTerminator CCStatement*\n    ;\n```\n\nConditional constants can only reference constant expressions and conditional compilation constants. Each of the constant expressions within a single conditional compilation group is evaluated and converted to the `Boolean` type in textual order from first to last until one of the conditional expressions evaluates to `True`. If an expression is not convertible to `Boolean`, a compile-time error results. Permissive semantics and binary string comparisons are always used when evaluating conditional compilation constant expressions, regardless of any `Option` directives or compilation environment settings.\n\nAll lines enclosed by the group, including nested conditional compilation directives, are disabled except for lines between the statement containing the `True` expression and the next conditional statement of the group, or lines between the `Else` statement and the `End If` statement if an `Else` appears in the group and all of the expressions evaluate to `False`.\n\nIn this example, the call to `WriteToLog` in the `Trace` conditional compilation directive is not processed because the surrounding `Debug` conditional compilation directive evaluates to `False`.\n\n```vb\n#Const Debug = False   ' Debugging off\n#Const Trace = True    ' Tracing on\n\nClass PurchaseTransaction\n    Sub Commit()\n\n#If Debug Then\n        CheckConsistency()\n#If Trace Then\n        WriteToLog(Me.ToString())\n#End If\n#End If\n        ...\n    End Sub\nEnd Class\n```\n\n\n## External Source Directives\n\nA source file may include external source directives that indicate a mapping between source lines and text external to the source.\n\n```antlr\nESDStart\n    : ExternalSourceStatement*\n    ;\n\nExternalSourceStatement\n    : ExternalSourceGroup\n    | LogicalLine\n    ;\n\nExternalSourceGroup\n    : '#' 'ExternalSource' '(' StringLiteral ',' IntLiteral ')' LineTerminator\n      LogicalLine* '#' 'End' 'ExternalSource' LineTerminator\n    ;\n```\n\nExternal source directives have no effect on compilation and may not be nested. For example:\n\n```vb\nModule Test\n    Sub Main()\n\n#ExternalSource(\"c:\\wwwroot\\inetpub\\test.aspx\", 30)\n        Console.WriteLine(\"In test.aspx\")\n#End ExternalSource\n\n    End Sub\nEnd Module\n```\n\n\n## Region Directives\n\nRegion directives group lines of source code but have no other effect on compilation. The entire group can be collapsed and hidden, or expanded and viewed, in the integrated development environment (IDE).\n\n```antlr\nRegionStart\n    : RegionStatement*\n    ;\n\nRegionStatement\n    : RegionGroup\n    | LogicalLine\n    ;\n\nRegionGroup\n    : '#' 'Region' StringLiteral LineTerminator\n      RegionStatement*\n      '#' 'End' 'Region' LineTerminator\n    ;\n```\n\nRegions may be nested. Region directives are special in that they can neither start nor terminate within a method body, and they must respect the block structure of the program. For example:\n\n```vb\nModule Test\n#Region \"Startup code - do not edit\"\n    Sub Main()\n    End Sub\n#End Region\n\nEnd Module\n\n\n' Error due to Region directives breaking the block structure\nClass C\n#Region \"Fred\"\nEnd Class\n#End Region\n```\n\n\n## External Checksum Directives\n\nA source file may include an external checksum directive that indicates what checksum should be emitted for a file referenced in an external source directive. In all other respects external source directives have no effect on compilation.\n\n```antlr\nExternalChecksumStart\n    : ExternalChecksumStatement*\n    ;\n\nExternalChecksumStatement\n    : '#' 'ExternalChecksum' '('\n      StringLiteral ',' StringLiteral ',' StringLiteral\n      ')' LineTerminator\n    ;\n```\n\nAn external checksum directive contains the filename of the external file, a globally unique identifier (GUID) associated with the file and the checksum for the file. The GUID is specified as a string constant of the form \"{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\", where x is a hexadecimal digit. The checksum is specified as a string constant of the form \"xxxx...\", where x is a hexadecimal digit. The number of digits in a checksum must be an even number.\n\nAn external file may have multiple external checksum directives associated with it provided that all of the GUID and checksum values match exactly. If the name of the external file matches the name of a file being compiled, the checksum is ignored in favor of the compiler's checksum calculation.\n\nFor example:\n\n```vb\n#ExternalChecksum(\"c:\\wwwroot\\inetpub\\test.aspx\", _\n    \"{12345678-1234-1234-1234-123456789abc}\", _\n    \"1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484\")\n\nModule Test\n    Sub Main()\n\n#ExternalSource(\"c:\\wwwroot\\inetpub\\test.aspx\", 30)\n        Console.WriteLine(\"In test.aspx\")\n#End ExternalSource\n\n    End Sub\nEnd Module\n```\n\n"
  },
  {
    "path": "spec/source-files-and-namespaces.md",
    "content": "# Source Files and Namespaces\n\nA Visual Basic program consists of one or more source files. When a program is compiled, all of the source files are processed together; thus, source files can depend on each other, possibly in a circular fashion, without any forward-declaration requirement. The textual order of declarations in the program text is generally of no significance.\n\nA source file consists of an optional set of option statements, import statements, and attributes, which are followed by a namespace body. The attributes, which must each have either the `Assembly` or `Module` modifier, apply to the .NET assembly or module produced by the compilation. The body of the source file functions as an implicit namespace declaration for the global namespace, meaning that all declarations at the top level of a source file are placed in the global namespace. For example:\n\nFileA.vb:\n\n```vb\nClass A\nEnd Class\n```\n\nFileB.vb:\n\n```vb\nClass B\nEnd Class\n```\n\nThe two source files contribute to the global namespace, in this case declaring two classes with the fully qualified names `A` and `B`. Because the two source files contribute to the same declaration space, it would have been an error if each contained a declaration of a member with the same name.\n\n__Note.__ The compilation environment may override the namespace declarations into which a source file is implicitly placed.\n\nExcept where noted, statements within a Visual Basic program can be terminated either by a line terminator or by a colon.\n\n```antlr\nStart\n    : OptionStatement* ImportsStatement* AttributesStatement* NamespaceMemberDeclaration*\n    ;\n\nStatementTerminator\n    : LineTerminator\n    | ':'\n    ;\n\nAttributesStatement\n    : Attributes StatementTerminator\n    ;\n```\n\n## Program Startup and Termination\n\nProgram startup occurs when the execution environment executes a designated method, which is referred to as the program's *entry point*. This entry point method, which must always be named `Main`, must be shared, cannot be contained in a generic type, cannot have the async modifier, and must have one of the following signatures:\n\n```vb\nSub Main()\nSub Main(args() As String)\nFunction Main() As Integer\nFunction Main(args() As String) As Integer\n```\n\nThe accessibility of the entry point method is irrelevant. If a program contains more than one suitable entry point, the compilation environment must designate one as the entry point. Otherwise, a compile-time error occurs. The compilation environment may also create an entry point method if one does not exist.\n\nWhen a program begins, if the entry point has a parameter, the argument supplied by the execution environment contains the command-line arguments to the program represented as strings. If the entry point has a return type of `Integer`, then the value returned from the function is returned to the execution environment as the result of the program.\n\nIn all other respects, entry point methods behave in the same manner as other methods. When execution leaves the invocation of the entry point method made by the execution environment, the program terminates.\n\n## Compilation Options\n\nA source file can specify compilation options in the source code using *option statements*.\n\n```antlr\nOptionStatement\n    : OptionExplicitStatement\n    | OptionStrictStatement\n    | OptionCompareStatement\n    | OptionInferStatement\n    ;\n```\n\nAn `Option` statement applies only to the source file in which it appears, and only one of each type of `Option` statement may appear in a source file. For example:\n\n```vb\nOption Strict On\nOption Compare Text\nOption Strict Off    ' Not allowed, Option Strict is already specified.\nOption Compare Text  ' Not allowed, Option Compare is already specified.\n```\n\nThere are four compilation options: strict type semantics, explicit declaration semantics, comparison semantics, and local variable type inference semantics. If a source file does not include a particular `Option` statement, then the compilation environment determines which particular set of semantics will be used. There is also a fifth compilation option, integer overflow checks, which can only be specified through the compilation environment.\n\n\n### Option Explicit Statement\n\nThe `Option Explicit` statement determines whether local variables may be implicitly declared. The keywords `On` or `Off` may follow the statement; if neither is specified, the default is `On`. If no statement is specified in a file, the compilation environment determines which will be used.\n\n```antlr\nOptionExplicitStatement\n    : 'Option' 'Explicit' OnOff? StatementTerminator\n    ;\n\nOnOff\n    : 'On' | 'Off'\n    ;\n```\n\n\n__Note.__ `Explicit` and `Off` are not reserved words.\n\n```vb\nOption Explicit Off\n\nModule Test\n    Sub Main()\n        x = 5 ' Valid because Option Explicit is off.\n    End Sub\nEnd Module\n```\n\nIn this example, the local variable `x` is implicitly declared by assigning to it. The type of `x` is `Object`.\n\n\n### Option Strict Statement\n\nThe `Option Strict` statement determines whether conversions and operations on `Object` are governed by strict or permissive type semantics and whether types are implicitly typed as `Object` if no `As` clause is specified. The statement may be followed by the keywords `On` or `Off`; if neither is specified, the default is `On`. If no statement is specified in a file, the compilation environment determines which will be used.\n\n```antlr\nOptionStrictStatement\n    : 'Option' 'Strict' OnOff? StatementTerminator\n    ;\n```\n\n__Note.__ `Strict` and `Off` are not reserved words.\n\n```vb\nOption Strict On\n\nModule Test\n    Sub Main()\n        Dim x ' Error, no type specified.\n        Dim o As Object\n        Dim b As Byte = o ' Error, narrowing conversion.\n\n        o.F() ' Error, late binding disallowed.\n        o = o + 1 ' Error, addition is not defined on Object.\n    End Sub\nEnd Module\n```\n\nUnder strict semantics, the following are disallowed:\n\n* Narrowing conversions without an explicit cast operator.\n\n* Late binding.\n\n* Operations on type `Object` other than `TypeOf`...`Is`, `Is`, and `IsNot`.\n\n* Omitting the `As` clause in a declaration that does not have an inferred type.\n\n\n### Option Compare Statement\n\nThe `Option Compare` statement determines the semantics of string comparisons. String comparisons are carried out either using binary comparisons (in which the binary Unicode value of each character is compared) or text comparisons (in which the lexical meaning of each character is compared using the current culture). If no statement is specified in a file, the compilation environment controls which type of comparison will be used.\n\n```antlr\nOptionCompareStatement\n    : 'Option' 'Compare' CompareOption StatementTerminator\n    ;\n\nCompareOption\n    : 'Binary' | 'Text'\n    ;\n```\n\n__Note.__ `Compare`, `Binary`, and `Text` are not reserved words.\n\n```vb\nOption Compare Text\n\nModule Test\n    Sub Main()\n        Console.WriteLine(\"a\" = \"A\")    ' Prints True.\n    End Sub\nEnd Module\n```\n\nIn this case, the string comparison is done using a text comparison that ignores case differences. If `Option Compare Binary` had been specified, then this would have printed `False`.\n\n\n### Integer Overflow Checks\n\nInteger operations can either be checked or not checked for overflow conditions at run time. If overflow conditions are checked and an integer operation overflows, a `System.OverflowException` exception is thrown. If overflow conditions are not checked, integer operation overflows do not throw an exception. The compilation environment determines whether this option is on or off.\n\n### Option Infer Statement\n\nThe `Option Infer` statement determines whether local variable declarations that have no `As` clause have an inferred type or use `Object`. The statement may be followed by the keywords `On` or `Off`; if neither is specified, the default is `On`. If no statement is specified in a file, the compilation environment determines which will be used.\n\n```antlr\nOptionInferStatement\n    : 'Option' 'Infer' OnOff? StatementTerminator\n    ;\n```\n\n__Note.__ `Infer` and `Off` are not reserved words.\n\n```vb\nOption Infer On\n\nModule Test\n    Sub Main()\n        ' The type of x is Integer\n        Dim x = 10\n\n        ' The type of y is String\n        Dim y = \"abc\"\n    End Sub\nEnd Module\n```\n\n\n## Imports Statement\n\n`Imports` statements import the names of entities into a source file, allowing the names to be referenced without qualification, or import a namespace for use in XML expressions.\n\n```antlr\nImportsStatement\n    : 'Imports' ImportsClauses StatementTerminator\n    ;\n\nImportsClauses\n    : ImportsClause ( Comma ImportsClause )*\n    ;\n\nImportsClause\n    : AliasImportsClause\n    | MembersImportsClause\n    | XMLNamespaceImportsClause\n    ;\n```\n\nWithin member declarations in a source file that contains an `Imports` statement, the types contained in the given namespace can be referenced directly, as seen in the following example:\n\n```vb\nImports N1.N2\n\nNamespace N1.N2\n    Class A\n    End Class\nEnd Namespace \n\nNamespace N3\n    Class B\n        Inherits A\n    End Class\nEnd Namespace\n```\n\nHere, within the source file, the type members of namespace `N1.N2` are directly available, and thus class `N3.B` derives from class `N1.N2.A`.\n\n`Imports` statements must appear after any `Option` statements but before any type declarations. The compilation environment may also define implicit `Imports` statements.\n\n`Imports` statements make names available in a source file, but do not declare anything in the global namespace's declaration space. The scope of the names imported by an `Imports` statement extends over the namespace member declarations contained in the source file. The scope of an `Imports` statement specifically does not include other `Imports` statements, nor does it include other source files. `Imports` statements may not refer to one another.\n\nIn this example, the last `Imports` statement is in error because it is not affected by the first import alias.\n\n```vb\nImports R1 = N1 ' OK.\nImports R2 = N1.N2 ' OK.\nImports R3 = R1.N2 ' Error: Can't refer to R1.\n\nNamespace N1.N2\nEnd Namespace\n```\n\n__Note.__ The namespace or type names that appear in `Imports` statements are always treated as if they are fully qualified. That is, the leftmost identifier in a namespace or type name always resolves in the global namespace and the rest of the resolution proceeds according to normal name resolution rules. This is the only place in the language that applies such a rule; the rule ensures that a name cannot be completely hidden from qualification. Without the rule, if a name in the global namespace were hidden in a particular source file, it would be impossible to specify any names from that namespace in a qualified way.\n\nIn this example, the `Imports` statement always refers to the global `System` namespace, and not the class in the source file.\n\n```vb\nImports System   ' Imports the namespace, not the class.\n\nClass System\nEnd Class\n```\n\n\n### Import Aliases\n\nAn *import alias* defines an alias for a namespace or type.\n\n```antlr\nAliasImportsClause\n    : Identifier Equals TypeName\n    ;\n```\n\n```vb\nImports A = N1.N2.A\n\nNamespace N1.N2\n    Class A\n    End Class\nEnd Namespace\n\nNamespace N3\n    Class B\n        Inherits A\n    End Class\nEnd Namespace\n```\n\nHere, within the source file, `A` is an alias for `N1.N2.A`, and thus class `N3.B` derives from class `N1.N2.A`. The same effect can be obtained by creating an alias `R` for `N1.N2` and then referencing `R.A`:\n\n```vb\nImports R = N1.N2\n\nNamespace N3\n    Class B\n        Inherits R.A\n    End Class\nEnd Namespace\n```\n\nThe identifier of an import alias must be unique within the declaration space of the global namespace (not just the global namespace declaration in the source file in which the import alias is defined), even though it does not declare a name in the global namespace's declaration space.\n\n__Note.__ Declarations in a module do not introduce names into the containing declaration space. Thus, it is valid for a declaration in a module to have the same name as an import alias, even though the declaration's name will be accessible in the containing declaration space.\n\n```vb\n' Error: Alias A conflicts with typename A\nImports A = N3.A\n\nClass A\nEnd Class\n\nNamespace N3\n    Class A\n    End Class\nEnd Namespace\n```\n\nHere, the global namespace already contains a member `A`, so it is an error for an import alias to use that identifier. It is likewise an error for two or more import aliases in the same source file to declare aliases by the same name.\n\nAn import alias can create an alias for any namespace or type. Accessing a namespace or type through an alias yields exactly the same result as accessing the namespace or type through its declared name.\n\n```vb\nImports R1 = N1\nImports R2 = N1.N2\n\nNamespace N1.N2\n    Class A\n    End Class\nEnd Namespace\n\nNamespace N3\n    Class B\n        Private a As N1.N2.A\n        Private b As R1.N2.A\n        Private c As R2.A\n    End Class\nEnd Namespace\n```\n\nHere, the names `N1.N2.A`, `R1.N2.A`, and `R2.A` are equivalent, and all refer to the class whose fully qualified name is `N1.N2.A`.\n\nThe import specifies the exact name of the namespace or type to which it is creating an alias. This must be the exact fully qualified name of that namespace or type: it does not use the normal rules for qualified name resolution (which for instance allow access to the members of a base class through a derived class).\n\nIf an import alias points to a type or namespace which cannot be resolved by these rules, then the import statement is ignored (and the compiler gives a warning).\n\nAlso, the reference cannot be to an open generic type -- all generic types must have valid type arguments supplied, and all type arguments must be resolvable by the rules above. Any incorrect binding of a generic type is an error.\n\n```vb\nImports A = G              ' error: since G is an open generic type\nImports B = G(Of Integer)  ' okay\nImports C = Derived.Nested ' warning: Derived.Nested isn't itself a type\nImports D = G(Of Derived.Nested) ' error: Derived.Nested isn't found\n\nClass G(Of T) : End Class\n\nClass Base\n    Class Nested : End Class\nEnd Class\n\nClass Derived : Inherits Base\nEnd Class\n\nModule Module1\n    Sub Main()\n        Dim x As C               ' error: \"C\" wasn't succesfully defined\n        Dim y As Derived.Nested  ' okay\n    End Sub\nEnd Module\n```\n\nDeclarations in the source file may shadow the import alias name.\n\n```vb\nImports R = N1.N2\n\nNamespace N1.N2\n    Class A\n    End Class\nEnd Namespace\n\nNamespace N3\n    Class R\n    End Class\n\n    Class B\n        Inherits R.A  ' Error, R has no member A\n    End Class\nEnd Namespace\n```\n\nIn the preceding example the reference to `R.A` in the declaration of `B` causes an error because `R` refers to `N3.R`, not `N1.N2`.\n\nAn import alias makes an alias available within a particular source file, but it does not contribute any new members to the underlying declaration space. In other words, an import alias is not transitive, but rather affects only the source file in which it occurs.\n\nFile1.vb:\n\n```vb\nImports R = N1.N2\n\nNamespace N1.N2\n    Class A\n    End Class\nEnd Namespace\n```\n\nFile2.vb:\n\n```vb\nClass B\n    Inherits R.A ' Error, R unknown.\nEnd Class\n```\n\nIn the above example, because the scope of the import alias that introduces `R` only extends to declarations in the source file in which it is contained, `R` is unknown in the second source file.\n\n\n### Namespace Imports\n\nA *namespace import* imports all of the members of a namespace or type, allowing the identifier of each member of the namespace or type to be used without qualification. In the case of types, a namespace import only allows access to the shared members of the type without requiring qualification of the class name. In particular, it allows the members of enumerated types to be used without qualification.\n\n```antlr\nMembersImportsClause\n    : TypeName\n    ;\n```\n\nFor example:\n\n```vb\nImports Colors\n\nEnum Colors\n    Red\n    Green\n    Blue\nEnd Enum\n\nModule M1\n    Sub Main()\n        Dim c As Colors = Red\n    End Sub\nEnd Module\n```\n\nUnlike an import alias, a namespace import has no restrictions on the names it imports and may import namespaces and types whose identifiers are already declared within the global namespace. The names imported by a regular import are shadowed by import aliases and declarations in the source file.\n\nIn the following example, `A` refers to `N3.A` rather than `N1.N2.A` within member declarations in the `N3` namespace.\n\n```vb\nImports N1.N2\n\nNamespace N1.N2\n    Class A\n    End Class\nEnd Namespace\n\nNamespace N3\n    Class A\n    End Class\n\n    Class B\n        Inherits A\n    End Class\nEnd Namespace\n```\n\nWhen more than one imported namespace contains members by the same name (and that name is not otherwise shadowed by an import alias or declaration), a reference to that name is ambiguous and causes a compile-time error.\n\n```vb\nImports N1\nImports N2\n\nNamespace N1\n    Class A\n    End Class\nEnd Namespace \n\nNamespace N2\n    Class A\n    End Class\nEnd Namespace \n\nNamespace N3\n    Class B\n        Inherits A ' Error, A is ambiguous.\n    End Class\nEnd Namespace\n```\n\nIn the above example, both `N1` and `N2` contain a member `A`. Because `N3` imports both, referencing `A` in `N3` causes a compile-time error. In this situation, the conflict can be resolved either through qualification of references to `A`, or by introducing an import alias that picks a particular `A`, as in the following example:\n\n```vb\nImports N1\nImports N2\nImports A = N1.A\n\nNamespace N3\n    Class B\n        Inherits A ' A means N1.A.\n    End Class\nEnd Namespace\n```\n\nOnly namespaces, classes, structures, enumerated types, and standard modules may be imported.\n\n\n### XML Namespace Imports\n\nAn *XML namespace import* defines a namespace or the default namespace for unqualified XML expressions contained within the compilation unit.\n\n```antlr\nXMLNamespaceImportsClause\n    : '<' XMLNamespaceAttributeName XMLWhitespace? Equals XMLWhitespace?\n      XMLNamespaceValue '>'\n    ;\n\nXMLNamespaceValue\n    : DoubleQuoteCharacter XMLAttributeDoubleQuoteValueCharacter* DoubleQuoteCharacter\n    | SingleQuoteCharacter XMLAttributeSingleQuoteValueCharacter* SingleQuoteCharacter\n    ;\n```\n\nFor example:\n\n```vb\nImports <xmlns:db=\"http://example.org/database\">\n\nModule Test\n    Sub Main()\n        ' db namespace is \"http://example.org/database\"\n        Dim x = <db:customer><db:Name>Bob</></>\n\n        Console.WriteLine(x.<db:Name>)\n    End Sub\nEnd Module\n```\n\nAn XML namespace, including the default namespace, can only be defined once for a particular set of imports. For example:\n\n```vb\nImports <xmlns:db=\"http://example.org/database-one\">\n' Error: namespace db is already defined\nImports <xmlns:db=\"http://example.org/database-two\">\n```\n\n\n## Namespaces\n\nVisual Basic programs are organized using namespaces. Namespaces both internally organize a program as well as organize the way program elements are exposed to other programs.\n\nUnlike other entities, namespaces are open-ended, and may be declared multiple times within the same program and across many programs, with each declaration contributing members to the same namespace. In the following example, the two namespace declarations contribute to the same declaration space, declaring two classes with the fully qualified names `N1.N2.A` and `N1.N2.B`.\n\n```vb\nNamespace N1.N2\n    Class A\n    End Class\nEnd Namespace\n\nNamespace N1.N2\n    Class B\n    End Class\nEnd Namespace\n```\n\nBecause the two declarations contribute to the same declaration space, it would be an error if each contained a declaration of a member with the same name.\n\nThere is a global namespace that has no name and whose nested namespaces and types can always be accessed without qualification. The scope of a namespace member declared in the global namespace is the entire program text. Otherwise, the scope of a type or namespace declared in a namespace whose fully qualified name is `N` is the program text of each namespace whose corresponding namespace's fully qualified name begins with `N` or is `N` itself. (Note that a compiler can choose to put declarations in a particular namespace by default. This does not alter the fact that there is still a global, unnamed namespace.)\n\nIn this example, the class `B` can see the class `A` because `B`'s namespace `N1.N2.N3` is conceptually nested within the namespace `N1.N2`.\n\n```vb\nNamespace N1.N2\n    Class A\n    End Class\nEnd Namespace\n\nNamespace N1.N2.N3\n    Class B\n        Inherits A\n    End Class\nEnd Namespace\n```\n\n### Namespace Declarations\n\nThere are three forms of namespace declaration.\n\n```antlr\nNamespaceDeclaration\n    : 'Namespace' NamespaceName StatementTerminator\n      NamespaceMemberDeclaration*\n      'End' 'Namespace' StatementTerminator\n    ;\n\nNamespaceName\n    : RelativeNamespaceName\n    | 'Global'\n    | 'Global' '.' RelativeNamespaceName\n    ;\n\nRelativeNamespaceName\n    : Identifier ( Period IdentifierOrKeyword )*\n    ;\n```\n\nThe first form starts with the keyword `Namespace` followed by a relative namespace name. If the relative namespace name is qualified, the namespace declaration is treated as if it is lexically nested within namespace declarations corresponding to each name in the qualified name. For example, the following two namespaces are semantically equivalent:\n\n```vb\nNamespace N1.N2\n    Class A\n    End Class\n\n    Class B\n    End Class\nEnd Namespace \n\nNamespace N1\n    Namespace N2\n        Class A\n        End Class\n\n        Class B\n        End Class\n    End Namespace\nEnd Namespace\n```\n\nThe second form starts with the keywords `Namespace Global`. It is treated as if all its member declarations were lexically placed in the global unnamed namespace -- regardless of any defaults provided by the compilation environment. This form of namespace declaration may not be lexically nested within any other namespace declaration.\n\nThe third form starts with the keywords `Namespace Global` followed by a qualified identifier `N`. It is treated as if it were a namespace declaration of the first form \"`Namespace N`\" that was lexically placed in the global unnamed namespace -- regardless of any defaults provided by the compilation environment. This form of namespace declaration may not be lexically nested within any other namespace declaration.\n\n```vb\nNamespace Global       ' Puts N1.A in the global namespace\n    Namespace N1\n        Class A\n        End Class\n    End Namespace\nEnd Namespace\n\nNamespace Global.N1    ' Equivalent to the above\n    Class A\n    End Class\nEnd Namespace\n\nNamespace N1           ' May or may not be equivalent to the above,\n    Class A            ' depending on defaults provided by the\n    End Class          ' compilation environment\nEnd Namespace\n```\n\nWhen dealing with the members of a namespace, it is not important where a particular member is declared. If two programs define an entity with the same name in the same namespace, attempting to resolve the name in the namespace causes an ambiguity error.\n\nNamespaces are by definition `Public`, so a namespace declaration cannot include any access modifiers.\n\n\n### Namespace Members\n\nNamespace members can only be namespace declarations and type declarations. Type declarations may have `Public` or `Friend` access. The default access for types is `Friend` access.\n\n```antlr\nNamespaceMemberDeclaration\n    : NamespaceDeclaration\n    | TypeDeclaration\n    ;\n\nTypeDeclaration\n    : ModuleDeclaration\n    | NonModuleDeclaration\n    ;\n\nNonModuleDeclaration\n    : EnumDeclaration\n    | StructureDeclaration\n    | InterfaceDeclaration\n    | ClassDeclaration\n    | DelegateDeclaration\n    ;\n```\n"
  },
  {
    "path": "spec/statements.md",
    "content": "# Statements - Visual Basic\n\nStatements represent executable code.\n\n```antlr\nStatement\n    : LabelDeclarationStatement\n    | LocalDeclarationStatement\n    | WithStatement\n    | SyncLockStatement\n    | EventStatement\n    | AssignmentStatement\n    | InvocationStatement\n    | ConditionalStatement\n    | LoopStatement\n    | ErrorHandlingStatement\n    | BranchStatement\n    | ArrayHandlingStatement\n    | UsingStatement\n\t| AwaitStatement\n\t| YieldStatement\n    ;\n```\n\n__Note.__ The Microsoft Visual Basic Compiler only allows statements which start with a keyword or an identifier. Thus, for instance, the invocation statement \"`Call (Console).WriteLine`\" is allowed, but the invocation statement \"`(Console).WriteLine`\" is not.\n\n## Control Flow\n\n*Control flow* is the sequence in which statements and expressions are executed. The order of execution depends on the particular statement or expression.\n\nFor example, when evaluating an addition operator (Section [Addition Operator](expressions.md#addition-operator)), first the left operand is evaluated, then the right operand, and then the operator itself. Blocks are executed (Section [Blocks and Labels](statements.md#blocks-and-labels)) by first executing their first substatement, and then proceeding one by one through the statements of the block.\n\nImplicit in this ordering is the concept of a *control point*, which is the next operation to be executed. When a method is invoked (or \"called\"), we say it creates an *instance* of the method. A method instance consists of its own copy of the method's parameters and local variables, and its own control point.\n\n### Regular Methods\n\nHere is an example of a regular method\n\n```vb\nFunction Test() As Integer\n    Console.WriteLine(\"hello\")\n    Return 1\nEnd Function\n\nDim x = Test()    ' invokes the function, prints \"hello\", assigns 1 to x\n```\n\nWhen a regular method is invoked,\n\n1. First an instance of the method is created specific to that invocation. This instance includes a copy of all parameters and local variables of the method.\n2. Then all of its parameters are initialized to the supplied values, and all of its local variables to the default values of their types.\n3. In the case of a `Function`, an implicit local variable is also initialized called the *function return variable* whose name is the function's name, whose type is the return type of the function and whose initial value is the default of its type.\n4. The method instance's control point is then set at the first statement of the method body, and the method body immediately starts to execute from there (Section [Blocks and Labels](statements.md#blocks-and-labels)).\n\nWhen control flow exits the method body normally - through reaching the `End Function` or `End Sub` that mark its end, or through an explicit `Return` or `Exit` statement - control flow returns to the caller of the method instance. If there is a function return variable, the result of the invocation is the final value of this variable.\n\nWhen control flow exits the method body through an unhandled exception, that exception is propagated to the caller.\n\nAfter control flow has exited, there are no longer any live references to the method instance. If the method instance held the only references to its copy of local variables or parameters, then they may be garbage collected.\n\n### Iterator Methods\n\nIterator methods are used as a convenient way to generate a sequence, one which can be consumed by the `For Each` statement. Iterator methods use the `Yield` statement (Section [Yield Statement](statements.md#yield-statement)) to provide elements of the sequence. (An iterator method with no `Yield` statements will produce an empty sequence). Here is an example of an iterator method:\n\n```vb\nIterator Function Test() As IEnumerable(Of Integer)\n    Console.WriteLine(\"hello\")\n    Yield 1\n    Yield 2\nEnd Function\n\nDim en = Test()\nFor Each x In en          ' prints \"hello\" before the first x\n    Console.WriteLine(x)  ' prints \"1\" and then \"2\"\nNext\n```\n\nWhen an iterator method is invoked whose return type is `IEnumerator(Of T)`,\n\n1. First an instance of the iterator method is created specific to that invocation. This instance includes a copy of all parameters and local variables of the method.\n2. Then all of its parameters are initialized to the supplied values, and all of its local variables to the default values of their types.\n3. An implicit local variable is also initialized called the *iterator current variable*, whose type is `T` and whose initial value is the default of its type.\n4. The method instance's control point is then set at the first statement of the method body.\n5. An *iterator object* is then created, associated with this method instance. The iterator object implements the declared return type and has behavior as described below.\n6. Control flow is then resumed *immediately* in the caller, and the result of the invocation is the iterator object. Note that this transfer is done without exiting the iterator method instance, and does not cause finally handlers to execute. The method instance is still referenced by the iterator object, and will not be garbage collected so long as there exists a live reference to the iterator object.\n\nWhen the iterator object's `Current` property is accessed, the *current variable* of the invocation is returned.\n\nWhen the iterator object's `MoveNext` method is invoked, the invocation does not create a new method instance. Instead the existing method instance is used (and its control point and local variables and parameters) - the instance that was created when the iterator method was first invoked. Control flow resumes execution at the control point of that method instance, and proceeds through the body of the iterator method as normal.\n\nWhen the iterator object's `Dispose` method is invoked, again the existing method instance is used. Control flow resumes at the control point of that method instance, but then immediately behaves as if an `Exit Function` statement were the next operation.\n\nThe above descriptions of behavior for invocation of `MoveNext` or `Dispose` on an iterator object only apply if all previous invocations of `MoveNext` or `Dispose` on that iterator object have already returned to their callers. If they haven't, then the behavior is undefined.\n\nWhen control flow exits the iterator method body normally -- through reaching the `End Function` that mark its end, or through an explicit `Return` or `Exit` statement -- it must have done so in the context of an invocation of `MoveNext` or `Dispose` function on an iterator object to resume the iterator method instance, and it will have been using the method instance that was created when the iterator method was first invoked. The control point of that instance is left at the `End Function` statement, and control flow resumes in the caller; and if it had been resumed by a call to `MoveNext` then the value `False` is returned to the caller.\n\nWhen control flow exits the iterator method body through an unhandled exception, then the exception is propagated to the caller, which again will be either an invocation of `MoveNext` or of `Dispose`.\n\nAs for the other possible return types of an iterator function,\n\n* When an iterator method is invoked whose return type is `IEnumerable(Of T)` for some `T`, an instance is first created -- specific to that invocation of the iterator method -- of all parameters in the method, and they are initialized with the supplied values. The result of the invocation is an object which implements the return type. Should this object's `GetEnumerator` method be called, it creates an instance -- specific to that invocation of `GetEnumerator` -- of all parameters and local variables in the method. It initializes the parameters to the values already saved, and proceeds as for the iterator method above.\n* When an iterator method is invoked whose return type is the non-generic interface `IEnumerator`, the behavior is exactly as for `IEnumerator(Of Object)`.\n* When an iterator method is invoked whose return type is the non-generic interface `IEnumerable`, the behavior is exactly as for `IEnumerable(Of Object)`.\n\n### Async Methods\n\nAsync methods are a convenient way to do long-running work without for example blocking the UI of an application. Async is short for *Asynchronous* - it means that the caller of the async method will resume its execution promptly, but the eventual completion of the async method's instance may happen at some later time in the future. By convention async methods are named with the suffix \"Async\".\n\n```vb\nAsync Function TestAsync() As Task(Of String)\n    Console.WriteLine(\"hello\")\n    Await Task.Delay(100)\n    Return \"world\"\nEnd Function\n\nDim t = TestAsync()         ' prints \"hello\"\nConsole.WriteLine(Await t)  ' prints \"world\"\n```\n\n__Note.__ Async methods are *not* run on a background thread. Instead they allow a method to suspend itself through the `Await` operator, and schedule itself to be resumed in response to some event.\n\nWhen an async method is invoked\n\n1. First an instance of the async method is created specific to that invocation. This instance includes a copy of all parameters and local variables of the method.\n2. Then all of its parameters are initialized to the supplied values, and all of its local variables to the default values of their types.\n3. In the case of an async method with return type `Task(Of T)` for some `T`, an implicit local variable is also initialized called the *task return variable*, whose type is `T` and whose initial value is the default of `T`.\n4. If the async method is a `Function` with return type `Task` or `Task(Of T)` for some `T`, then an object of that type implicitly created, associated with the current invocation. This is called an *async object* and represents the future work that will be done by executing the instance of the async method. When control resumes in the caller of this async method instance, the caller will receive this async object as the result of its invocation.\n5. The instance's control point is then set at the first statement of the async method body, and immediately starts to execute the method body from there (Section [Blocks and Labels](statements.md#blocks-and-labels)).\n\n__Resumption Delegate and Current Caller__\n\nAs detailed in Section [Await Operator](expressions.md#await-operator), execution of an `Await` expression has the ability to suspend the method instance's control point leaving control flow to go elsewhere. Control flow can later resume at the same instance's control point through invocation of a *resumption delegate*. Note that this suspension is done without exiting the async method, and does not cause finally handlers to execute. The method instance is still referenced by both the resumption delegate and the `Task` or `Task(Of T)` result (if any), and will not be garbage collected so long as there exists a live reference to either delegate or result.\n\nIt is helpful to imagine the statement `Dim x = Await WorkAsync()` approximately as syntactic shorthand for the following:\n\n```vb\nDim temp = WorkAsync().GetAwaiter()\nIf Not temp.IsCompleted Then\n       temp.OnCompleted(resumptionDelegate)\n       Return [task]\n       CONT:   ' invocation of 'resumptionDelegate' will resume here\nEnd If\nDim x = temp.GetResult()\n```\n\nIn the following, the *current caller* of the method instance is defined as either the original caller, or the caller of the resumption delegate, whichever is more recent.\n\nWhen control flow exits the async method body -- through reaching the `End Sub` or `End Function` that mark its end, or through an explicit `Return` or `Exit` statement, or through an unhandled exception -- the instance's control point is set to the end of the method. Behavior then depends on the return type of the async method.\n\n* In the case of an `Async Function` with return type `Task`:\n  1. If control flow exits through an unhandled exception, then the async object's status is set to `TaskStatus.Faulted` and its `Exception.InnerException` property is set to the exception (except: certain implementation-defined exceptions such as `OperationCanceledException` change it to `TaskStatus.Canceled`). Control flow resumes in the current caller.\n  2. Otherwise, the async object's status is set to `TaskStatus.Completed`. Control flow resumes in the current caller.\n\n     (__Note.__ The whole point of Task, and what makes async methods interesting, is that when a task becomes Completed then any methods that were awaiting it will presently have their resumption delegates executed, i.e. they will become unblocked.)\n\n* In the case of an `Async Function` with return type `Task(Of T)` for some `T`: the behavior is as above, except that in non-exception cases the async object's `Result` property is also set to the final value of the task return variable.\n\n* In the case of an `Async Sub`:\n  1. If control flow exits through an unhandled exception, then that exception is propagated to the environment in some implementation-specific manner. Control flow resumes in the current caller.\n  2. Otherwise, control flow simply resumes in the current caller.\n\n#### Async Sub\n\nThere is some Microsoft-specific behavior of an `Async Sub`.\n\nIf `SynchronizationContext.Current` is `Nothing` at the start of the invocation, then any unhandled exceptions from an Async Sub will be posted to the Threadpool.\n\nIf `SynchronizationContext.Current` is not `Nothing` at the start of the invocation, then `OperationStarted()` is invoked on that context before the start of the method and `OperationCompleted()` after the end. Additionally, any unhandled exceptions will be posted to be rethrown on the synchronization context.\n\nThis means that in UI applications, for an `Async Sub` that is invoked on the UI thread, any exceptions it fails to handle will be reposted the UI thread.\n\n#### Mutable structures in async and iterator methods\n\nMutable structures in general are considered bad practice, and they are not supported by async or iterator methods. In particular, each invocation of an async or iterator method in a structure will implicitly operate on a *copy* of that structure that is copied at its moment of invocation. Thus, for example,\n\n```vb\nStructure S\n       Dim x As Integer\n       Async Sub Mutate()\n           x = 2\n       End Sub\nEnd Structure\n\nDim s As New S With {.x = 1}\ns.Mutate()\nConsole.WriteLine(s.x)   ' prints \"1\"\n```\n\n### Blocks and Labels\n\nA group of executable statements is called a statement block. Execution of a statement block begins with the first statement in the block. Once a statement has been executed, the next statement in lexical order is executed, unless a statement transfers execution elsewhere or an exception occurs.\n\nWithin a statement block, the division of statements on logical lines is not significant with the exception of label declaration statements. A label is an identifier that identifies a particular position within the statement block that can be used as the target of a branch statement such as `GoTo`.\n\n```antlr\nBlock\n    : Statements*\n    ;\n\nLabelDeclarationStatement\n    : LabelName ':'\n    ;\n\nLabelName\n    : Identifier\n    | IntLiteral\n    ;\n\nStatements\n    : Statement? ( ':' Statement? )*\n    ;\n```\n\n\nLabel declaration statements must appear at the beginning of a logical line and labels may be either an identifier or an integer literal. Because both label declaration statements and invocation statements can consist of a single identifier, a single identifier at the beginning of a local line is always considered a label declaration statement. Label declaration statements must always be followed by a colon, even if no statements follow on the same logical line.\n\nLabels have their own declaration space and do not interfere with other identifiers. The following example is valid and uses the name variable `x` both as a parameter and as a label.\n\n```vb\nFunction F(x As Integer) As Integer\n    If x >= 0 Then\n        GoTo x\n    End If\n    x = -x\nx: \n    Return x\nEnd Function\n```\n\nThe scope of a label is the body of the method containing it.\n\nFor the sake of readability, statement productions that involve multiple substatements are treated as a single production in this specification, even though the substatements may each be by themselves on a labeled line.\n\n\n### Local Variables and Parameters\n\nThe preceding sections detail how and when method instances are created, and with them the copies of a method's local variables and parameters. In addition, each time the body of a loop is entered, a new copy is made of each local variable declared inside that loop as described in Section [Loop Statements](statements.md#loop-statements), and the method instance now contains this copy of its local variable rather than the previous copy.\n\nAll locals are initialized to their type's default value. Local variables and parameters are always publicly accessible. It is an error to refer to a local variable in a textual position that precedes its declaration, as the following example illustrates:\n\n```vb\nClass A\n    Private i As Integer = 0\n\n    Sub F()\n        i = 1\n        Dim i As Integer       ' Error, use precedes declaration.\n        i = 2\n    End Sub\n\n    Sub G()\n        Dim a As Integer = 1\n        Dim b As Integer = a   ' This is valid.\n    End Sub\nEnd Class\n```\n\nIn the `F` method above, the first assignment to `i` specifically does not refer to the field declared in the outer scope. Rather, it refers to the local variable, and it is in error because it textually precedes the declaration of the variable. In the `G` method, a subsequent variable declaration refers to a local variable declared in an earlier variable declaration within the same local variable declaration.\n\nEach block in a method creates a declaration space for local variables. Names are introduced into this declaration space through local variable declarations in the method body and through the parameter list of the method, which introduces names into the outermost block's declaration space. Blocks do not allow shadowing of names through nesting: once a name has been declared in a block, the name may not be redeclared in any nested blocks.\n\nThus, in the following example, the `F` and `G` methods are in error because the name `i` is declared in the outer block and cannot be redeclared in the inner block. However, the `H` and `I` methods are valid because the two `i`'s are declared in separate non-nested blocks.\n\n```vb\nClass A\n    Sub F()\n        Dim i As Integer = 0\n        If True Then\n               Dim i As Integer = 1\n        End If\n    End Sub\n\n    Sub G()\n        If True Then\n            Dim i As Integer = 0\n        End If\n        Dim i As Integer = 1\n    End Sub \n\n    Sub H()\n        If True Then\n            Dim i As Integer = 0\n        End If\n        If True Then\n            Dim i As Integer = 1\n        End If\n    End Sub\n\n    Sub I() \n        For i As Integer = 0 To 9\n            H()\n        Next i\n\n        For i As Integer = 0 To 9\n            H()\n        Next i\n    End Sub \nEnd Class\n```\n\nWhen the method is a function, a special local variable is implicitly declared in the method body's declaration space with the same name as the method representing the return value of the function. The local variable has special name resolution semantics when used in expressions. If the local variable is used in a context that expects an expression classified as a method group, such as an invocation expression, then the name resolves to the function rather than to the local variable. For example:\n\n```vb\nFunction F(i As Integer) As Integer\n    If i = 0 Then\n        F = 1        ' Sets the return value.\n    Else\n        F = F(i - 1) ' Recursive call.\n    End If\nEnd Function\n```\n\nThe use of parentheses can cause ambiguous situations (such as `F(1)`, where `F` is a function whose return type is a one-dimensional array); in all ambiguous situations, the name resolves to the function rather than the local variable. For example:\n\n```vb\nFunction F(i As Integer) As Integer()\n    If i = 0 Then\n        F = new Integer(2) { 1, 2, 3 }\n    Else\n        F = F(i - 1) ' Recursive call, not an index.\n    End If\nEnd Function\n```\n\nWhen control flow leaves the method body, the value of the local variable is passed back to the invocation expression. If the method is a subroutine, there is no such implicit local variable, and control simply returns to the invocation expression.\n\n## Local Declaration Statements\n\nA local declaration statement declares a new local variable, local constant, or static variable. *Local variables* and *local constants* are equivalent to instance variables and constants scoped to the method and are declared in the same way. *Static variables* are similar to `Shared` variables and are declared using the `Static` modifier.\n\n```antlr\nLocalDeclarationStatement\n    : LocalModifier VariableDeclarators StatementTerminator\n    ;\n\nLocalModifier\n    : 'Static' | 'Dim' | 'Const'\n    ;\n```\n\nStatic variables are locals that retain their value across invocations of the method. Static variables declared within non-shared methods are per instance: each instance of the type that contains the method has its own copy of the static variable. Static variables declared within `Shared` methods are per type; there is only one copy of the static variable for all instances. While local variables are initialized to their type's default value upon each entry into the method, static variables are only initialized to their type's default value when the type or type instance is initialized. Static variables may not be declared in structures or generic methods.\n\nLocal variables, local constants, and static variables always have public accessibility and may not specify accessibility modifiers. If no type is specified on a local declaration statement, then the following steps determine the type of the local declaration:\n\n1. If the declaration has a type character, the type of the type character is the type of the local declaration.\n\n2. If the local declaration is a local constant, or if the local declaration is a local variable with an initializer and local variable type inference is being used, the type of the local declaration is inferred from the type of the initializer. If the initializer refers to the local declaration, a compile-time error occurs. (Local constants are required to have initializers.)\n\n3. If strict semantics are not being used, the type of the local declaration statement is implicitly `Object`.\n\n4. Otherwise, a compile-time error occurs.\n\nIf no type is specified on a local declaration statement that has an array size or array type modifier, then the type of the local declaration is an array with the specified rank and the previous steps are used to determine the element type of the array. If local variable type inference is used, the type of the initializer must be an array type with the same array shape (i.e. array type modifiers) as the local declaration statement. Note that it is possible that the inferred element type may still be an array type. For example:\n\n```vb\nOption Infer On\n\nModule Test\n    Sub Main()\n        ' Error: initializer is not an array type\n        Dim x() = 1\n\n        ' Type is Integer()\n        Dim y() = New Integer() {}\n\n        ' Type is Integer()()\n        Dim z() = New Integer()() {}\n\n        ' Type is Integer()()()\n\n        Dim a()() = New Integer()()() {}\n\n        ' Error: initializer does not have same array shape\n        Dim b()() = New Integer(,)() {}\n    End Sub\nEnd Module\n```\n\nIf no type is specified on a local declaration statement that has a nullable type modifier, then the type of the local declaration is the nullable version of the inferred type or the inferred type itself if it a nullable value type already.  If the inferred type is not a value type that can be made nullable, a compile-time error occurs. If both a nullable type modifier and an array size or array type modifier are placed on a local declaration statement with no type, then the nullable type modifier is considered to apply to the element type of the array and the previous steps are used to determine the element type.\n\nVariable initializers on local declaration statements are equivalent to assignment statements placed at the textual location of the declaration. Thus, if execution branches over the local declaration statement, the variable initializer is not executed. If the local declaration statement is executed more than once, the variable initializer is executed an equal number of times. Static variables only execute their initializer the first time. If an exception occurs while initializing a static variable, the static variable is considered initialized with the default value of the static variable's type.\n\nThe following example shows the use of initializers:\n\n```vb\nModule Test\n    Sub F()\n        Static x As Integer = 5\n\n        Console.WriteLine(\"Static variable x = \" & x)\n        x += 1\n    End Sub\n\n    Sub Main()\n        Dim i As Integer\n\n        For i = 1 to 3\n            F()\n        Next i\n\n        i = 3\nlabel:\n        Dim y As Integer = 8\n\n        If i > 0 Then\n            Console.WriteLine(\"Local variable y = \" & y)\n            y -= 1\n            i -= 1\n            GoTo label\n        End If\n    End Sub\nEnd Module\n```\n\nThis program prints:\n\n```console\nStatic variable x = 5\nStatic variable x = 6\nStatic variable x = 7\nLocal variable y = 8\nLocal variable y = 8\nLocal variable y = 8\n```\n\nInitializers on static locals are thread-safe and protected against exceptions during initialization. If an exception occurs during a static local initializer, the static local will have its default value and not be initialized. A static local initializer\n\n```vb\nModule Test\n    Sub F()\n        Static x As Integer = 5\n    End Sub\nEnd Module\n```\n\nis equivalent to\n\n```vb\nImports System.Threading\nImports Microsoft.VisualBasic.CompilerServices\n\nModule Test\n    Class InitFlag\n        Public State As Short\n    End Class\n\n    Private xInitFlag As InitFlag = New InitFlag()\n\n    Sub F()\n        Dim x As Integer\n\n        If xInitFlag.State <> 1 Then\n            Monitor.Enter(xInitFlag)\n            Try\n                If xInitFlag.State = 0 Then\n                    xInitFlag.State = 2\n                    x = 5\n                Else If xInitFlag.State = 2 Then\n                    Throw New IncompleteInitialization()\n                End If\n            Finally\n                xInitFlag.State = 1\n                Monitor.Exit(xInitFlag)\n            End Try\n        End If\n    End Sub\nEnd Module\n```\n\nLocal variables, local constants, and static variables are scoped to the statement block in which they are declared. Static variables are special in that their names may only be used once throughout the entire method. For example, it is not valid to specify two static variable declarations with the same name even if they are in different blocks.\n\n\n### Implicit Local Declarations\n\nIn addition to local declaration statements, local variables can also be declared implicitly through use. A simple name expression that uses a name that does not resolve to something else declares a local variable by that name. For example:\n\n```vb\nOption Explicit Off\n\nModule Test\n    Sub Main()\n        x = 10\n        y = 20\n        Console.WriteLine(x + y)\n    End Sub\nEnd Module\n```\n\nImplicit local declaration only occurs in expression contexts that can accept an expression classified as a variable. The exception to this rule is that a local variable may not be implicitly declared when it is the target of a function invocation expression, indexing expression, or a member access expression.\n\nImplicit locals are treated as if they are declared at the beginning of the containing method. Thus, they are always scoped to the entire method body, even if declared inside of a lambda expression. For example, the following code:\n\n```vb\nOption Explicit Off \n\nModule Test\n    Sub Main()\n        Dim x = Sub()\n                    a = 10\n                End Sub\n        Dim y = Sub()\n                    Console.WriteLine(a)\n                End Sub\n\n        x()\n        y()\n    End Sub\nEnd Module\n```\n\nwill print the value `10`. Implicit locals are typed as `Object` if no type character was attached to the variable name; otherwise the type of the variable is the type of the type character. Local variable type inference is not used for implicit locals.\n\nIf explicit local declaration is specified by the compilation environment or by `Option Explicit`, all local variables must be explicitly declared and implicit variable declaration is disallowed.\n\n## With Statement\n\nA `With` statement allows multiple references to an expression's members without specifying the expression multiple times.\n\n```antlr\nWithStatement\n    : 'With' Expression StatementTerminator\n      Block?\n      'End' 'With' StatementTerminator\n    ;\n```\n\nThe expression must be classified as a value and is evaluated once, upon entry into the block. Within the `With` statement block, a member access expression or dictionary access expression starting with a period or an exclamation point is evaluated as if the `With` expression preceded it. For example:\n\n```vb\nStructure Test\n    Public x As Integer\n\n    Function F() As Integer\n        Return 10\n    End Function\nEnd Structure\n\nModule TestModule\n    Sub Main()\n        Dim y As Test\n\n        With y\n            .x = 10\n            Console.WriteLine(.x)\n            .x = .F()\n        End With\n    End Sub\nEnd Module\n```\n\nIt is invalid to branch into a `With` statement block from outside of the block.\n\n\n## SyncLock Statement\n\nA `SyncLock` statement allows statements to be synchronized on an expression, which ensures that multiple threads of execution do not execute the same statements at the same time.\n\n```antlr\nSyncLockStatement\n    : 'SyncLock' Expression StatementTerminator\n      Block?\n      'End' 'SyncLock' StatementTerminator\n    ;\n```\n\nThe expression must be classified as a value and is evaluated once, upon entry to the block. When entering the `SyncLock` block, the `Shared` method `System.Threading.Monitor.Enter` is called on the specified expression, which blocks until the thread of execution has an exclusive lock on the object returned by the expression. The type of the expression in a `SyncLock` statement must be a reference type. For example:\n\n```vb\nClass Test\n    Private count As Integer = 0\n\n    Public Function Add() As Integer\n        SyncLock Me\n            count += 1\n            Add = count\n        End SyncLock\n    End Function\n\n    Public Function Subtract() As Integer\n        SyncLock Me\n            count -= 1\n            Subtract = count\n        End SyncLock\n    End Function\nEnd Class\n```\n\nThe example above synchronizes on the specific instance of the class `Test` to ensure that no more than one thread of execution can add or subtract from the count variable at a time for a particular instance.\n\nThe `SyncLock` block is implicitly contained by a `Try` statement whose `Finally` block calls the `Shared` method `System.Threading.Monitor.Exit` on the expression. This ensures the lock is freed even when an exception is thrown. As a result, it is invalid to branch into a `SyncLock` block from outside of the block, and a `SyncLock` block is treated as a single statement for the purposes of `Resume` and `Resume Next`. The above example is equivalent to the following code:\n\n```vb\nClass Test\n    Private count As Integer = 0\n\n    Public Function Add() As Integer\n        Try\n            System.Threading.Monitor.Enter(Me)\n\n            count += 1\n            Add = count\n        Finally\n            System.Threading.Monitor.Exit(Me)\n        End Try\n    End Function\n\n    Public Function Subtract() As Integer\n        Try\n            System.Threading.Monitor.Enter(Me)\n\n            count -= 1\n            Subtract = count\n        Finally\n            System.Threading.Monitor.Exit(Me)\n        End Try\n    End Function\nEnd Class\n```\n\n\n## Event Statements\n\nThe `RaiseEvent`, `AddHandler`, and `RemoveHandler` statements raise events and handle events dynamically.\n\n```antlr\nEventStatement\n    : RaiseEventStatement\n    | AddHandlerStatement\n    | RemoveHandlerStatement\n    ;\n```\n\n### RaiseEvent Statement\n\nA `RaiseEvent` statement notifies event handlers that a particular event has occurred.\n\n```antlr\nRaiseEventStatement\n    : 'RaiseEvent' IdentifierOrKeyword\n      ( OpenParenthesis ArgumentList? CloseParenthesis )? StatementTerminator\n    ;\n```\n\nThe simple name expression in a `RaiseEvent` statement is interpreted as a member lookup on `Me`. Thus, `RaiseEvent x` is interpreted as if it were `RaiseEvent Me.x`. The result of the expression must be classified as an event access for an event defined in the class itself; events defined on base types cannot be used in a `RaiseEvent` statement.\n\nThe `RaiseEvent` statement is processed as a call to the `Invoke` method of the event's delegate, using the supplied parameters, if any. If the delegate's value is `Nothing`, no exception is thrown. If there are no arguments, the parentheses may be omitted. For example:\n\n```vb\nClass Raiser\n    Public Event E1(Count As Integer)\n\n    Public Sub Raise()\n        Static RaiseCount As Integer = 0\n\n        RaiseCount += 1\n        RaiseEvent E1(RaiseCount)\n    End Sub\nEnd Class\n\nModule Test\n    Private WithEvents x As Raiser\n\n    Private Sub E1Handler(Count As Integer) Handles x.E1\n        Console.WriteLine(\"Raise #\" & Count)\n    End Sub\n\n    Public Sub Main()\n        x = New Raiser\n        x.Raise()        ' Prints \"Raise #1\".\n        x.Raise()        ' Prints \"Raise #2\".\n        x.Raise()        ' Prints \"Raise #3\".\n    End Sub\nEnd Module\n```\n\nThe class `Raiser` above is equivalent to:\n\n```vb\nClass Raiser\n    Public Event E1(Count As Integer)\n\n    Public Sub Raise()\n        Static RaiseCount As Integer = 0\n        Dim TemporaryDelegate As E1EventHandler\n\n        RaiseCount += 1\n\n        ' Use a temporary to avoid a race condition.\n        TemporaryDelegate = E1Event\n        If Not TemporaryDelegate Is Nothing Then\n            TemporaryDelegate.Invoke(RaiseCount)\n        End If\n    End Sub\nEnd Class\n```\n\n\n### AddHandler and RemoveHandler Statements\n\nAlthough most event handlers are automatically hooked up through `WithEvents` variables, it may be necessary to dynamically add and remove event handlers at run time. `AddHandler` and `RemoveHandler` statements do this.\n\n```antlr\nAddHandlerStatement\n    : 'AddHandler' Expression Comma Expression StatementTerminator\n    ;\n\nRemoveHandlerStatement\n    : 'RemoveHandler' Expression Comma Expression StatementTerminator\n    ;\n```\n\nEach statement takes two arguments: the first argument must be an expression that is classified as an event access and the second argument must be an expression that is classified as a value. The second argument's type must be the delegate type associated with the event access. For example:\n\n```vb\nPublic Class Form1\n    Public Sub New()\n        ' Add Button1_Click as an event handler for Button1's Click event.\n        AddHandler Button1.Click, AddressOf Button1_Click\n    End Sub \n\n    Private Button1 As Button = New Button()\n\n    Sub Button1_Click(sender As Object, e As EventArgs)\n        Console.WriteLine(\"Button1 was clicked!\")\n    End Sub\n\n    Public Sub Disconnect()\n        RemoveHandler Button1.Click, AddressOf Button1_Click\n    End Sub\nEnd Class\n```\n\nGiven an event `E,` the statement calls the relevant `add_E` or `remove_E` method on the instance to add or remove the delegate as a handler for the event. Thus, the above code is equivalent to:\n\n```vb\nPublic Class Form1\n    Public Sub New()\n        Button1.add_Click(AddressOf Button1_Click)\n    End Sub \n\n    Private Button1 As Button = New Button()\n\n    Sub Button1_Click(sender As Object, e As EventArgs)\n        Console.WriteLine(\"Button1 was clicked!\")\n    End Sub\n\n    Public Sub Disconnect()\n        Button1.remove_Click(AddressOf Button1_Click)\n    End Sub\nEnd Class\n```\n\n\n## Assignment Statements\n\nAn assignment statement assigns the value of an expression to a variable. There are several types of assignment.\n\n```antlr\nAssignmentStatement\n    : RegularAssignmentStatement\n    | CompoundAssignmentStatement\n    | MidAssignmentStatement\n    ;\n```\n\n### Regular Assignment Statements\n\nA simple assignment statement stores the result of an expression in a variable.\n\n```antlr\nRegularAssignmentStatement\n    : Expression Equals Expression StatementTerminator\n    ;\n```\n\nThe expression on the left side of the assignment operator must be classified as a variable or a property access, while the expression on the right side of the assignment operator must be classified as a value. The type of the expression must be implicitly convertible to the type of the variable or property access.\n\nIf the variable being assigned into is an array element of a reference type, a run-time check will be performed to ensure that the expression is compatible with the array-element type. In the following example, the last assignment causes a `System.ArrayTypeMismatchException` to be thrown, because an instance of `ArrayList` cannot be stored in an element of a `String` array.\n\n```vb\nDim sa(10) As String\nDim oa As Object() = sa\noa(0) = Nothing         ' This is allowed.\noa(1) = \"Hello\"         ' This is allowed.\noa(2) = New ArrayList() ' System.ArrayTypeMismatchException is thrown.\n```\n\nIf the expression on the left side of the assignment operator is classified as a variable, then the assignment statement stores the value in the variable. If the expression is classified as a property access, then the assignment statement turns the property access into an invocation of the `Set` accessor of the property with the value substituted for the value parameter. For example:\n\n```vb\nModule Test\n    Private PValue As Integer\n\n    Public Property P As Integer\n        Get\n            Return PValue\n        End Get\n\n        Set (Value As Integer)\n            PValue = Value\n        End Set\n    End Property\n\n    Sub Main()\n        ' The following two lines are equivalent.\n        P = 10\n        set_P(10)\n    End Sub\nEnd Module\n```\n\nIf the target of the variable or property access is typed as a value type but not classified as a variable, a compile-time error occurs. For example:\n\n```vb\nStructure S\n    Public F As Integer\nEnd Structure\n\nClass C\n    Private PValue As S\n\n    Public Property P As S\n        Get\n            Return PValue\n        End Get\n\n        Set (Value As S)\n            PValue = Value\n        End Set\n    End Property\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim ct As C = New C()\n        Dim rt As Object = new C()\n\n        ' Compile-time error: ct.P not classified as variable.\n        ct.P.F = 10\n\n        ' Run-time exception.\n        rt.P.F = 10\n    End Sub\nEnd Module\n```\n\nNote that the semantics of the assignment depend on the type of the variable or property to which it is being assigned. If the variable to which it is being assigned is a value type, the assignment copies the value of the expression into the variable. If the variable to which it is being assigned is a reference type, the assignment copies the reference, not the value itself, into the variable. If the type of the variable is `Object`, the assignment semantics are determined by whether the value's type is a value type or a reference type at run time.\n\n\n__Note.__ For intrinsic types such as `Integer` and `Date`, reference and value assignment semantics are the same because the types are immutable. As a result, the language is free to use reference assignment on boxed intrinsic types as an optimization. From a value perspective, the result is the same.\n\nBecause the equals character (`=`) is used both for assignment and for equality, there is an ambiguity between a simple assignment and an invocation statement in situations such as `x = y.ToString()`. In all such cases, the assignment statement takes precedence over the equality operator. This means that the example expression is interpreted as `x = (y.ToString())` rather than `(x = y).ToString()`.\n\n\n### Compound Assignment Statements\n\nA *compound assignment statement* takes the form `V op= E` (where `op` is a valid binary operator).\n\n```antlr\nCompoundAssignmentStatement\n    : Expression CompoundBinaryOperator LineTerminator? Expression StatementTerminator\n    ;\n\nCompoundBinaryOperator\n    : '^' '=' | '*' '=' | '/' '=' | '\\\\' '=' | '+' '=' | '-' '='\n    | '&' '=' | '<' '<' '=' | '>' '>' '='\n    ;\n```\n\nThe expression on the left side of the assignment operator must be classified as a variable or property access, while the expression on the right side of the assignment operator must be classified as a value. The compound assignment statement is equivalent to the statement `V = V op E` with the difference that the variable on the left side of the compound assignment operator is only evaluated once. The following example demonstrates this difference:\n\n```vb\nModule Test\n    Function GetIndex() As Integer\n        Console.WriteLine(\"Getting index\")\n        Return 1\n    End Function\n\n    Sub Main()\n        Dim a(2) As Integer\n\n        Console.WriteLine(\"Simple assignment\")\n        a(GetIndex()) = a(GetIndex()) + 1\n\n        Console.WriteLine(\"Compound assignment\")\n        a(GetIndex()) += 1\n    End Sub\nEnd Module\n```\n\nThe expression `a(GetIndex())` is evaluated twice for simple assignment but only once for compound assignment, so the code prints:\n\n```console\nSimple assignment\nGetting index\nGetting index\nCompound assignment\nGetting index\n```\n\n\n### Mid Assignment Statement\n\nA `Mid` assignment statement assigns a string into another string. The left side of the assignment has the same syntax as a call to the function `Microsoft.VisualBasic.Strings.Mid`.\n\n```antlr\nMidAssignmentStatement\n    : 'Mid' '$'? OpenParenthesis Expression Comma Expression\n      ( Comma Expression )? CloseParenthesis Equals Expression StatementTerminator\n    ;\n```\n\nThe first argument is the target of the assignment and must be classified as a variable or a property access whose type is implicitly convertible to and from `String`. The second parameter is the 1-based start position that corresponds to where the assignment should begin in the target string and must be classified as a value whose type must be implicitly convertible to `Integer`. The optional third parameter is the number of characters from the right-side value to assign into the target string and must be classified as a value whose type is implicitly convertible to `Integer`. The right side is the source string and must be classified as a value whose type is implicitly convertible to `String`. The right side is truncated to the length parameter, if specified, and replaces the characters in the left-side string, starting at the start position. If the right side string contained fewer characters than the third parameter, only the characters from the right side string will be copied.\n\nThe following example displays `ab123fg`:\n\n```vb\nModule Test\n    Sub Main()\n        Dim s1 As String = \"abcdefg\"\n        Dim s2 As String = \"1234567\"\n\n        Mid$(s1, 3, 3) = s2\n        Console.WriteLine(s1)\n    End Sub\nEnd Module\n```\n\n__Note.__ `Mid` is not a reserved word.\n\n\n## Invocation Statements\n\nAn invocation statement invokes a method preceded by the optional keyword `Call`. The invocation statement is processed in the same way as the function invocation expression, with some differences noted below. The invocation expression must be classified as a value or void. Any value resulting from the evaluation of the invocation expression is discarded.\n\nIf the `Call` keyword is omitted, then the invocation expression must start with an identifier or keyword, or with `.` inside a `With` block. Thus, for instance, \"`Call 1.ToString()`\" is a valid statement but \"`1.ToString()`\" is not. (Note that in an expression context, invocation expressions also need not start with an identifier. For example, \"`Dim x = 1.ToString()`\" is a valid statement).\n\nThere is another difference between the invocation statements and invocation expressions: if an invocation statement includes an argument list, then this is always taken as the argument list of the invocation. The following example illustrates the difference:\n\n```vb\nModule Test\n    Sub Main()\n        Call {Function() 15}(0)\n        ' error: (0) is taken as argument list, but array is not invokable\n\n        Call ({Function() 15}(0))\n        ' valid, since the invocation statement has no argument list\n\n        Dim x = {Function() 15}(0)\n        ' valid as an expression, since (0) is taken as an array-indexing\n\n        Call f(\"a\")\n        ' error: (\"a\") is taken as argument list to the invocation of f\n\n        Call f()(\"a\")\n        ' valid, since () is the argument list for the invocation of f\n\n        Dim y = f(\"a\")\n        ' valid as an expression, since f(\"a\") is interpreted as f()(\"a\")\n    End Sub\n\n    Sub f() As Func(Of String,String)\n        Return Function(x) x\n    End Sub\nEnd Module\n```\n\n```antlr\nInvocationStatement\n    : 'Call'? InvocationExpression StatementTerminator\n    ;\n```\n\n## Conditional Statements\n\nConditional statements allow conditional execution of statements based on expressions evaluated at run time.\n\n```antlr\nConditionalStatement\n    : IfStatement\n    | SelectStatement\n    ;\n```\n\n### If...Then...Else Statements\n\nAn `If...Then...Else` statement is the basic conditional statement.\n\n```antlr\nIfStatement\n    : BlockIfStatement\n    | LineIfThenStatement\n    ;\n\nBlockIfStatement\n    : 'If' BooleanExpression 'Then'? StatementTerminator\n      Block?\n      ElseIfStatement*\n      ElseStatement?\n      'End' 'If' StatementTerminator\n    ;\n\nElseIfStatement\n    : ElseIf BooleanExpression 'Then'? StatementTerminator\n      Block?\n    ;\n\nElseStatement\n    : 'Else' StatementTerminator\n      Block?\n    ;\n\nLineIfThenStatement\n    : 'If' BooleanExpression 'Then' Statements ( 'Else' Statements )? StatementTerminator\n    ;\n    \nElseIf\t\t\n\t: 'ElseIf'\t\t\n\t| 'Else' 'If'   \n   ;\n```\n\nEach expression in an `If...Then...Else` statement must be a Boolean expression, as per Section [Boolean Expressions](expressions.md#boolean-expressions). (Note: this does not require the expression to have Boolean type). If the expression in the `If` statement is true, the statements enclosed by the `If` block are executed. If the expression is false, each of the `ElseIf` expressions is evaluated. If one of the `ElseIf` expressions evaluates to true, the corresponding block is executed. If no expression evaluates to true and there is an `Else` block, the `Else` block is executed. Once a block finishes executing, execution passes to the end of the `If...Then...Else` statement.\n\nThe line version of the `If` statement has a single set of statements to be executed if the `If` expression is `True` and an optional set of statements to be executed if the expression is `False`. For example:\n\n```vb\nModule Test\n    Sub Main()\n        Dim a As Integer = 10\n        Dim b As Integer = 20\n\n        ' Block If statement.\n        If a < b Then\n            a = b\n        Else\n            b = a\n        End If\n\n        ' Line If statement\n        If a < b Then a = b Else b = a\n    End Sub\nEnd Module\n```\n\nThe line version of the If statement binds less tightly than \":\", and its `Else` binds to the lexically nearest preceding `If` that is allowed by the syntax. For example, the following two versions are equivalent:\n\n```vb\nIf True Then _\nIf True Then Console.WriteLine(\"a\") Else Console.WriteLine(\"b\") _\nElse Console.WriteLine(\"c\") : Console.WriteLine(\"d\")\n\nIf True Then\n    If True Then\n        Console.WriteLine(\"a\")\n    Else\n        Console.WriteLine(\"b\")\n    End If\n    Console.WriteLine(\"c\") : Console.WriteLine(\"d\")\nEnd If\n```\n\nAll statements other than label declaration statements are allowed inside a line `If` statement, including block statements. However, they may not use LineTerminators as StatementTerminators except inside multi-line lambda expressions. For example:\n\n```vb\n' Allowed, since it uses : instead of LineTerminator to separate statements\nIf b Then With New String(\"a\"(0),5) : Console.WriteLine(.Length) : End With\n\n' Disallowed, since it uses a LineTerminator\nIf b then With New String(\"a\"(0), 5)\n              Console.WriteLine(.Length)\n          End With\n\n' Allowed, since it only uses LineTerminator inside a multi-line lambda\nIf b Then Call Sub()\n                   Console.WriteLine(\"a\")\n               End Sub.Invoke()\n```\n\n### Select Case Statements\n\nA `Select Case` statement executes statements based on the value of an expression.\n\n```antlr\nSelectStatement\n    : 'Select' 'Case'? Expression StatementTerminator\n      CaseStatement*\n      CaseElseStatement?\n      'End' 'Select' StatementTerminator\n    ;\n\nCaseStatement\n    : 'Case' CaseClauses StatementTerminator\n      Block?\n    ;\n\nCaseClauses\n    : CaseClause ( Comma CaseClause )*\n    ;\n\nCaseClause\n    : ( 'Is' LineTerminator? )? ComparisonOperator LineTerminator? Expression\n    | Expression ( 'To' Expression )?\n    ;\n\nComparisonOperator\n    : '=' | '<' '>' | '<' | '>' | '>' '=' | '<' '='\n    ;\n\nCaseElseStatement\n    : 'Case' 'Else' StatementTerminator\n      Block?\n    ;\n```\n\nThe expression must be classified as a value. When a `Select Case` statement is executed, the `Select` expression is evaluated first, and the `Case` statements are then evaluated in order of textual declaration. The first `Case` statement that evaluates to `True` has its block executed. If no `Case` statement evaluates to `True` and there is a `Case Else` statement, that block is executed. Once a block has finished executing, execution passes to the end of the `Select` statement.\n\nExecution of a `Case` block is not permitted to \"fall through\" to the next switch section. This prevents a common class of bugs that occur in other languages when a `Case` terminating statement is accidentally omitted. The following example illustrates this behavior:\n\n```vb\nModule Test\n    Sub Main()\n        Dim x As Integer = 10\n\n        Select Case x\n            Case 5\n                Console.WriteLine(\"x = 5\")\n            Case 10\n                Console.WriteLine(\"x = 10\")\n            Case 20 - 10\n                Console.WriteLine(\"x = 20 - 10\")\n            Case 30\n                Console.WriteLine(\"x = 30\")\n        End Select\n    End Sub\nEnd Module\n```\n\nThe code prints:\n\n```console\nx = 10\n```\n\nAlthough `Case 10` and `Case 20 - 10` select for the same value, `Case 10` is executed because it precedes `Case 20 - 10` textually. When the next `Case` is reached, execution continues after the `Select` statement.\n\nA `Case` clause may take two forms. One form is an optional `Is` keyword, a comparison operator, and an expression. The expression is converted to the type of the `Select` expression; if the expression is not implicitly convertible to the type of the `Select` expression, a compile-time error occurs. If the `Select` expression is *E*, the comparison operator is *Op*, and the `Case` expression is *E1*, the case is evaluated as *E OP E1*. The operator must be valid for the types of the two expressions; otherwise a compile-time error occurs.\n\nThe other form is an expression optionally followed by the keyword `To` and a second expression. Both expressions are converted to the type of the `Select` expression; if either expression is not implicitly convertible to the type of the `Select` expression, a compile-time error occurs. If the `Select` expression is `E`, the first `Case` expression is `E1`, and the second `Case` expression is `E2`, the `Case` is evaluated either as `E = E1` (if no `E2` is specified) or `(E >= E1) And (E <= E2)`. The operators must be valid for the types of the two expressions; otherwise a compile-time error occurs.\n\n\n## Loop Statements\n\nLoop statements allow repeated execution of the statements in their body.\n\n```antlr\nLoopStatement\n    : WhileStatement\n    | DoLoopStatement\n    | ForStatement\n    | ForEachStatement\n    ;\n```\n\nEach time a loop body is entered, a fresh copy is made of all local variables declared in that body, initialized to the previous values of the variables. Any reference to a variable within the loop body will use the most recently made copy. This code shows an example:\n\n```vb\nModule Test\n    Sub Main()\n        Dim lambdas As New List(Of Action)\n        Dim x = 1\n\n        For i = 1 To 3\n            x = i\n            Dim y = x\n            lambdas.Add(Sub() Console.WriteLine(x & y))\n        Next\n\n        For Each lambda In lambdas\n            lambda()\n        Next\n    End Sub\nEnd Module\n```\n\nThe code produces the output:\n\n```console\n31    32    33\n```\n\nWhen the loop body is executed, it uses whichever copy of the variable is current. For example, the statement  `Dim y = x` refers to the latest copy of `y` and the original copy of `x`. And when a lambda is created, it remembers whichever copy of a variable was current at the time it was created. Therefore, each lambda uses the same shared copy of `x`, but a different copy of `y`. At the end of the program, when it executes the lambdas, that shared copy of `x` that they all refer to is now at its final value 3.\n\nNote that if there are no lambdas or LINQ expressions, then it's impossible to know that a fresh copy is made on loop entry. Indeed, compiler optimizations will avoid making copies in this case. Note too that it's illegal to `GoTo` into a loop that contains lambdas or LINQ expressions.\n\n\n### While...End While and Do...Loop Statements\n\nA `While` or `Do` loop statement loops based on a Boolean expression.\n\n```antlr\nWhileStatement\n    : 'While' BooleanExpression StatementTerminator\n      Block?\n      'End' 'While' StatementTerminator\n    ;\n\nDoLoopStatement\n    : DoTopLoopStatement\n    | DoBottomLoopStatement\n    ;\n\nDoTopLoopStatement\n    : 'Do' ( WhileOrUntil BooleanExpression )? StatementTerminator\n      Block?\n      'Loop' StatementTerminator\n    ;\n\nDoBottomLoopStatement\n    : 'Do' StatementTerminator\n      Block?\n      'Loop' WhileOrUntil BooleanExpression StatementTerminator\n    ;\n\nWhileOrUntil\n    : 'While' | 'Until'\n    ;\n```\n\nA `While` loop statement loops as long as the Boolean expression evaluates to true; a `Do` loop statement may contain a more complex condition. An expression may be placed after the `Do` keyword or after the `Loop` keyword, but not after both. The Boolean expression is evaluated as per Section [Boolean Expressions](expressions.md#boolean-expressions). (Note: this does not require the expression to have Boolean type). It is also valid to specify no expression at all; in that case, the loop will never exit. If the expression is placed after `Do`, it will be evaluated before the loop block is executed on each iteration. If the expression is placed after `Loop`, it will be evaluated after the loop block has executed on each iteration. Placing the expression after `Loop` will therefore generate one more loop than placement after `Do`. The following example demonstrates this behavior:\n\n```vb\nModule Test\n    Sub Main()\n        Dim x As Integer\n\n        x = 3\n        Do While x = 1\n            Console.WriteLine(\"First loop\")\n        Loop\n\n        Do\n            Console.WriteLine(\"Second loop\")\n        Loop While x = 1\n    End Sub\nEnd Module\n```\n\nThe code produces the output:\n\n```console\nSecond Loop\n```\n\nIn the case of the first loop, the condition is evaluated before the loop executes. In the case of the second loop, the condition is executed after the loop executes. The conditional expression must be prefixed with either a `While` keyword or an `Until` keyword. The former breaks the loop if the condition evaluates to false, the latter when the condition evaluates to true.\n\n__Note.__ `Until` is not a reserved word.\n\n\n### For...Next Statements\n\nA `For...Next` statement loops based on a set of bounds. A `For` statement specifies a loop control variable, a lower bound expression, an upper bound expression, and an optional step value expression. The loop control variable is specified either through an identifier followed by an optional `As` clause or an expression.\n\n```antlr\nForStatement\n    : 'For' LoopControlVariable Equals Expression 'To' Expression\n      ( 'Step' Expression )? StatementTerminator\n      Block?\n      ( 'Next' NextExpressionList? StatementTerminator )?\n    ;\n\nLoopControlVariable\n    : Identifier ( IdentifierModifiers 'As' TypeName )?\n    | Expression\n    ;\n\nNextExpressionList\n    : Expression ( Comma Expression )*\n    ;\n```\n\nAs per the following rules, the loop control variable refers either to a new local variable specific to this `For...Next` statement, or to a pre-existing variable, or to an expression.\n\n* If the loop control variable is an identifier with an `As` clause, the identifier defines a new local variable of the type specified in the `As` clause, scoped to the entire `For` loop.\n\n* If the loop control variable is an identifier without an `As` clause, then the identifier is first resolved using the simple name resolution rules (see Section [Simple Name Expressions](expressions.md#simple-name-expressions)), excepting that this occurrence of the identifier would not in and of itself cause an implicit local variable to be created (Section [Implicit Local Declarations](statements.md#implicit-local-declarations)).\n\n  * If this resolution succeeds and the result is classified as a variable, then the loop control variable is that pre-existing variable.\n\n  * If resolution fails, or if resolution succeeds and the result is classified as a type, then:\n    * if local variable type inference is being used, the identifier defines a new local variable whose type is inferred from the bound and step expressions, scoped to the entire `For` loop;\n    * if local variable type inference is not being used but implicit local declaration is, then an implicit local variable is created whose scope is the entire method (Section [Implicit Local Declarations](statements.md#implicit-local-declarations)), and the loop control variable refers to this pre-existing variable;\n    * if neither local variable type inference nor implicit local declarations are used, it is an error.\n\n  * If resolution succeeds with something classified as neither a type nor a variable, it is an error.\n\n* If the loop control variable is an expression, the expression must be classified as a variable.\n\nA loop control variable cannot be used by another enclosing `For...Next` statement. The type of the loop control variable of a `For` statement determines the type of the iteration and must be one of:\n\n* `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, `Long`, `Decimal`, `Single`, `Double`\n* An enumerated type\n* `Object`\n* A type `T` that has the following operators, where `B` is a type that can be used in a Boolean expression:\n\n```vb\nPublic Shared Operator >= (op1 As T, op2 As T) As B\nPublic Shared Operator <= (op1 As T, op2 As T) As B\nPublic Shared Operator - (op1 As T, op2 As T) As T\nPublic Shared Operator + (op1 As T, op2 As T) As T\n```\n\nThe bound and step expressions must be implicitly convertible to the type of the loop control variable and must be classified as values. At compile time, the type of the loop control variable is inferred by choosing the widest type among the lower bound, upper bound, and step expression types. If there is no widening conversion between two of the types, then a compile-time error occurs.\n\nAt run time, if the type of the loop control variable is `Object`, then the type of the iteration is inferred the same as at compile time, with two exceptions. First, if the bound and step expressions are all of integral types but have no widest type, then the widest type that encompasses all three types will be inferred. And second, if the type of the loop control variable is inferred to be `String`, `Double` will be inferred instead. If, at run time, no loop control type can be determined or if any of the expressions cannot be converted to the loop control type, a `System.InvalidCastException` will occur. Once a loop control type has been chosen at the beginning of the loop, the same type will be used throughout the iteration, regardless of changes made to the value in the loop control variable.\n\nA `For` statement must be closed by a matching `Next` statement. A `Next` statement without a variable matches the innermost open `For` statement, while a `Next` statement with one or more loop control variables will, from left to right, match the `For` loops that match each variable. If a variable matches a `For` loop that is not the most nested loop at that point, a compile-time error results.\n\nAt the beginning of the loop, the three expressions are evaluated in textual order and the lower bound expression is assigned to the loop control variable. If the step value is omitted, it is implicitly the literal `1`, converted to the type of the loop control variable. The three expressions are only ever evaluated at the beginning of the loop.\n\nAt the beginning of each loop, the control variable is compared to see if it is greater than the end point if the step expression is positive, or less than the end point if the step expression is negative. If it is, the `For` loop terminates; otherwise the loop block executes. If the loop control variable is not a primitive type, the comparison operator is determined by whether the expression `step >= step - step` is true or false. At the `Next` statement, the step value is added to the control variable and execution returns to the top of the loop.\n\nNote that a new copy of the loop control variable is *not* created on each iteration of the loop block. In this respect, the `For` statement differs from `For Each` (Section [For Each...Next Statements](statements.md#for-eachnext-statements)).\n\nIt is not valid to branch into a `For` loop from outside the loop.\n\n\n### For Each...Next Statements\n\nA `For Each...Next` statement loops based on the elements in an expression. A `For Each` statement specifies a loop control variable and an enumerator expression. The loop control variable is specified either through an identifier followed by an optional `As` clause or an expression.\n\n```antlr\nForEachStatement\n    : 'For' 'Each' LoopControlVariable 'In' LineTerminator? Expression StatementTerminator\n      Block?\n      ( 'Next' NextExpressionList? StatementTerminator )?\n    ;\n```\n\nFollowing the same rules as `For...Next` statements (Section [For...Next Statements](statements.md#fornext-statements)), the loop control variable refers either to a new local variable specific to this For Each...Next statement, or to a pre-existing variable, or to an expression.\n\nThe enumerator expression must be classified as a value and its type must be a collection type or `Object`. If the type of the enumerator expression is `Object`, then all processing is deferred until run-time. Otherwise, a conversion must exist from the element type of the collection to the type of the loop control variable.\n\nThe loop control variable cannot be used by another enclosing `For Each` statement. A `For Each` statement must be closed by a matching `Next` statement. A `Next` statement without a loop control variable matches the innermost open `For Each`. A `Next` statement with one or more loop control variables will, from left to right, match the `For Each` loops that have the same loop control variable. If a variable matches a `For Each` loop that is not the most nested loop at that point, a compile-time error occurs.\n\nA type `C` is said to be a *collection type* if one of:\n\n* All of the following are true:\n  * `C` contains an accessible instance, shared or extension method with the signature `GetEnumerator()` that returns a type `E`.\n  * `E` contains an accessible instance, shared or extension method with the signature `MoveNext()` and the return type `Boolean`.\n  * `E` contains an accessible instance or shared property named `Current` that has a getter. The type of this property is the element type of the collection type.\n\n* It implements the interface `System.Collections.Generic.IEnumerable(Of T)`, in which case the element type of the collection is considered to be `T`.\n\n* It implements the interface `System.Collections.IEnumerable`, in which case the element type of the collection is considered to be `Object`.\n\nFollowing is an example of a class that can be enumerated:\n\n```vb\nPublic Class IntegerCollection\n    Private integers(10) As Integer\n\n    Public Class IntegerCollectionEnumerator\n        Private collection As IntegerCollection\n        Private index As Integer = -1\n\n        Friend Sub New(c As IntegerCollection)\n            collection = c\n        End Sub\n\n        Public Function MoveNext() As Boolean\n            index += 1\n\n            Return index <= 10\n        End Function\n\n        Public ReadOnly Property Current As Integer\n            Get\n                If index < 0 OrElse index > 10 Then\n                    Throw New System.InvalidOperationException()\n                End If\n\n                Return collection.integers(index)\n            End Get\n        End Property\n    End Class\n\n    Public Sub New()\n        Dim i As Integer\n\n        For i = 0 To 10\n            integers(i) = I\n        Next i\n    End Sub\n\n    Public Function GetEnumerator() As IntegerCollectionEnumerator\n        Return New IntegerCollectionEnumerator(Me)\n    End Function\nEnd Class\n```\n\nBefore the loop begins, the enumerator expression is evaluated. If the type of the expression does not satisfy the design pattern, then the expression is cast to `System.Collections.IEnumerable` or `System.Collections.Generic.IEnumerable(Of T)`. If the expression type implements the generic interface, the generic interface is preferred at compile-time but the non-generic interface is preferred at run-time. If the expression type implements the generic interface multiple times, the statement is considered ambiguous and a compile-time error occurs.\n\n__Note.__ The non-generic interface is preferred in the late bound case, because picking the generic interface would mean that all the calls to the interface methods would involve type parameters. Since it is not possible to know the matching type arguments at run-time, all such calls would have to be made using late-bound calls. This would be slower than calling the non-generic interface because the non-generic interface could be called using compile-time calls.\n\n`GetEnumerator` is called on the resulting value and the return value of the function is stored in a temporary. Then at the beginning of each iteration, `MoveNext` is called on the temporary. If it returns `False`, the loop terminates. Otherwise, each iteration of the loop is executed as follows:\n\n1. If the loop control variable identified a new local variable (rather than a pre-existing one), then a fresh copy of this local variable is created. For the current iteration, all references within the loop block will refer to this copy.\n2. The `Current` property is retrieved, coerced to the type of the loop control variable (regardless of whether the conversion is implicit or explicit), and assigned to the loop control variable.\n3. The loop block executes.\n\n__Note.__ There is a slight change in behavior between version 10.0 and 11.0 of the language. Prior to 11.0, a fresh iteration variable was *not* created for each iteration of the loop. This difference is observable only if the iteration variable is captured by a lambda or a LINQ expression which is then invoked after the loop:\n\n```vb\nDim lambdas As New List(Of Action)\nFor Each x In {1,2,3}\n   lambdas.Add(Sub() Console.WriteLine(x)\nNext\nlambdas(0).Invoke()\nlambdas(1).Invoke()\nlambdas(2).Invoke()\n```\n\nUp to Visual Basic 10.0, this produced a warning at compile-time and printed \"3\" three times. That was because there was only a single variable \"x\" shared by all iterations of the loop, and all three lambdas captured the same \"x\", and by the time the lambdas were executed it then held the number 3. As of Visual Basic 11.0, it prints \"1, 2, 3\". That is because each lambda captures a different variable \"x\".\n\n\n__Note.__ The current element of the iteration is converted to the type of the loop control variable even if the conversion is explicit because there is no convenient place to introduce a conversion operator in the statement. This became particularly troublesome when working with the now-obsolete type `System.Collections.ArrayList`, because its element type is `Object`. This would have required casts in a great many loops, something we felt was not ideal. Ironically, generics enabled the creation of a strongly-typed collection, `System.Collections.Generic.List(Of T)`, which might have made us rethink this design point, but for compatibility's sake, this cannot be changed now.\n\n\nWhen the `Next` statement is reached, execution returns to the top of the loop. If a variable is specified after the `Next` keyword, it must be the same as the first variable after the `For Each`. For example, consider the following code:\n\n```vb\nModule Test\n    Sub Main()\n        Dim i As Integer\n        Dim c As IntegerCollection = New IntegerCollection()\n\n        For Each i In c\n            Console.WriteLine(i)\n        Next i\n    End Sub\nEnd Module\n```\n\nIt is equivalent to the following code:\n\n```vb\nModule Test\n    Sub Main()\n        Dim i As Integer\n        Dim c As IntegerCollection = New IntegerCollection()\n\n        Dim e As IntegerCollection.IntegerCollectionEnumerator\n\n        e = c.GetEnumerator()\n        While e.MoveNext()\n            i = e.Current\n\n            Console.WriteLine(i)\n        End While\n    End Sub\nEnd Module\n```\n\nIf the type `E` of the enumerator implements `System.IDisposable`, then the enumerator is disposed upon exiting the loop by calling the `Dispose` method. This ensures that resources held by the enumerator are released. If the method containing the `For Each` statement does not use unstructured error handling, then the `For Each` statement is wrapped in a `Try` statement with the `Dispose` method called in the `Finally` to ensure cleanup.\n\n__Note.__ The `System.Array` type is a collection type, and since all array types derive from `System.Array`, any array type expression is permitted in a `For Each` statement. For single-dimensional arrays, the `For Each` statement enumerates the array elements in increasing index order, starting with index 0 and ending with index Length - 1. For multidimensional arrays, the indices of the rightmost dimension are increased first.\n\nFor example, the following code prints `1 2 3 4`:\n\n```vb\nModule Test\n    Sub Main()\n        Dim x(,) As Integer = { { 1, 2 }, { 3, 4 } }\n        Dim i As Integer\n\n        For Each i In x\n            Console.Write(i & \" \")\n        Next i\n    End Sub\nEnd Module\n```\n\nIt is not valid to branch into a `For Each` statement block from outside the block.\n\n\n## Exception-Handling Statements\n\nVisual Basic supports structured exception handling and unstructured exception handling. Only one style of exception handling may be used in a method, but the `Error` statement may be used in structured exception handling. If a method uses both styles of exception handling, a compile-time error results.\n\n```antlr\nErrorHandlingStatement\n    : StructuredErrorStatement\n    | UnstructuredErrorStatement\n    ;\n```\n\n### Structured Exception-Handling Statements\n\nStructured exception handling is a method of handling errors by declaring explicit blocks within which certain exceptions will be handled. Structured exception handling is done through a `Try` statement.\n\n```antlr\nStructuredErrorStatement\n    : ThrowStatement\n    | TryStatement\n    ;\n\nTryStatement\n    : 'Try' StatementTerminator\n      Block?\n      CatchStatement*\n      FinallyStatement?\n      'End' 'Try' StatementTerminator\n    ;\n```\n\n\nFor example:\n\n```vb\nModule Test\n    Sub ThrowException()\n        Throw New Exception()\n    End Sub\n\n    Sub Main()\n        Try\n            ThrowException()\n        Catch e As Exception\n            Console.WriteLine(\"Caught exception!\")\n        Finally\n            Console.WriteLine(\"Exiting try.\")\n        End Try\n    End Sub\nEnd Module\n```\n\nA `Try` statement is made up of three kinds of blocks: try blocks, catch blocks, and finally blocks. A *try block* is a statement block that contains the statements to be executed. A *catch block* is a statement block that handles an exception. A *finally block* is a statement block that contains statements to be run when the `Try` statement is exited, regardless of whether an exception has occurred and been handled. A `Try` statement, which can only contain one try block and one finally block, must contain at least one catch block or finally block. It is invalid to explicitly transfer execution into a try block except from within a catch block in the same statement.\n\n\n#### Finally Blocks\n\nA `Finally` block is always executed when execution leaves any part of the `Try` statement. No explicit action is required to execute the `Finally` block; when execution leaves the `Try` statement, the system will automatically execute the `Finally` block and then transfer execution to its intended destination. The `Finally` block is executed regardless of how execution leaves the `Try` statement: through the end of the `Try` block, through the end of a `Catch` block, through an `Exit Try` statement, through a `GoTo` statement, or by not handling a thrown exception.\n\nNote that the `Await` expression in an async method, and the `Yield` statement in an iterator method, can cause flow of control to suspend in the async or iterator method instance and resume in some other method instance. However, this is merely a suspension of execution and does not involve exiting the respective async method or iterator method instance, and so does not cause `Finally` blocks to be executed.\n\nIt is invalid to explicitly transfer execution into a `Finally` block; it is also invalid to transfer execution out of a `Finally` block except through an exception.\n\n```antlr\nFinallyStatement\n    : 'Finally' StatementTerminator\n      Block?\n    ;\n```\n\n#### Catch Blocks\n\nIf an exception occurs while processing the `Try` block, each `Catch` statement is examined in textual order to determine if it handles the exception.\n\n```antlr\nCatchStatement\n    : 'Catch' ( Identifier ( 'As' NonArrayTypeName )? )?\n\t  ( 'When' BooleanExpression )? StatementTerminator\n      Block?\n    ;\n```\n\nThe identifier specified in a `Catch` clause represents the exception that has been thrown. If the identifier contains an `As` clause, then the identifier is considered to be declared within the `Catch` block's local declaration space. Otherwise, the identifier must be a local variable (not a static variable) that was defined in a containing block.\n\nA `Catch` clause with no identifier will catch all exceptions derived from `System.Exception`. A `Catch` clause with an identifier will only catch exceptions whose types are the same as or derived from the type of the identifier. The type must be `System.Exception`, or a type derived from `System.Exception`. When an exception is caught that derives from `System.Exception`, a reference to the exception object is stored in the object returned by the function `Microsoft.VisualBasic.Information.Err`.\n\nA `Catch` clause with a `When` clause will only catch exceptions when the expression evaluates to `True`; the type of the expression must be a Boolean expression as per Section [Boolean Expressions](expressions.md#boolean-expressions). A `When` clause is only applied after checking the type of the exception, and the expression may refer to the identifier representing the exception, as this example demonstrates:\n\n```vb\nModule Test\n    Sub Main()\n        Dim i As Integer = 5\n\n        Try\n            Throw New ArgumentException()\n        Catch e As OverflowException When i = 5\n            Console.WriteLine(\"First handler\")\n        Catch e As ArgumentException When i = 4\n            Console.WriteLine(\"Second handler\")\n        Catch When i = 5\n            Console.WriteLine(\"Third handler\")\n        End Try\n\n    End Sub\nEnd Module\n```\n\nThis example prints:\n\n```console\nThird handler\n```\n\nIf a `Catch` clause handles the exception, execution transfers to the `Catch` block. At the end of the `Catch` block, execution transfers to the first statement following the `Try` statement. The `Try` statement will not handle any exceptions thrown in a `Catch` block. If no `Catch` clause handles the exception, execution transfers to a location determined by the system.\n\nIt is invalid to explicitly transfer execution into a `Catch` block.\n\nThe filters in When clauses are normally evaluated prior to the exception being thrown. For instance, the following code will print \"Filter, Finally, Catch\".\n\n```vb\nSub Main()\n   Try\n       Foo()\n   Catch ex As Exception When F()\n       Console.WriteLine(\"Catch\")\n   End Try\nEnd Sub\n\nSub Foo()\n    Try\n        Throw New Exception\n    Finally\n        Console.WriteLine(\"Finally\")\n    End Try\nEnd Sub\n\nFunction F() As Boolean\n    Console.WriteLine(\"Filter\")\n    Return True\nEnd Function\n```\n\n However, Async and Iterator methods cause all finally blocks inside them to be executed prior to any filters outside. For instance, if the above code had `Async Sub Foo()`, then the output would be \"Finally, Filter, Catch\".\n\n\n#### Throw Statement\n\nThe `Throw` statement raises an exception, which is represented by an instance of a type derived from `System.Exception`.\n\n```antlr\nThrowStatement\n    : 'Throw' Expression? StatementTerminator\n    ;\n```\n\nIf the expression is not classified as a value or is not a type derived from `System.Exception`, then a compile-time error occurs. If the expression evaluates to a null value at run time, then a `System.NullReferenceException` exception is raised instead.\n\nA `Throw` statement may omit the expression within a catch block of a `Try` statement, as long as there is no intervening finally block. In that case, the statement rethrows the exception currently being handled within the catch block. For example:\n\n```vb\nSub Test(x As Integer)\n    Try\n        Throw New Exception()\n    Catch\n        If x = 0 Then\n            Throw    ' OK, rethrows exception from above.\n        Else\n            Try\n                If x = 1 Then\n                    Throw   ' OK, rethrows exception from above.\n                End If\n            Finally\n                Throw    ' Invalid, inside of a Finally.\n            End Try\n        End If\n    End Try\nEnd Sub\n```\n\n\n### Unstructured Exception-Handling Statements\n\nUnstructured exception handling is a method of handling errors by indicating statements to branch to when an exception occurs. Unstructured exception handling is implemented using three statements: the `Error` statement, the `On Error` statement, and the `Resume` statement.\n\n```antlr\nUnstructuredErrorStatement\n    : ErrorStatement\n    | OnErrorStatement\n    | ResumeStatement\n    ;\n```\n\nFor example:\n\n```vb\nModule Test\n    Sub ThrowException()\n        Error 5\n    End Sub\n\n    Sub Main()\n        On Error GoTo GotException\n\n        ThrowException()\n        Exit Sub\n\nGotException:\n        Console.WriteLine(\"Caught exception!\")\n        Resume Next\n    End Sub\nEnd Module\n```\n\nWhen a method uses unstructured exception handling, a single structured exception handler is established for the entire method that catches all exceptions. (Note that in constructors this handler does not extend over the call to the call to `New` at the beginning of the constructor.) The method then keeps track of the most recent exception-handler location and the most recent exception that has been thrown. At entry to the method, the exception-handler location and the exception are both set to `Nothing`. When an exception is thrown in a method that uses unstructured exception handling, a reference to the exception object is stored in the object returned by the function `Microsoft.VisualBasic.Information.Err`.\n\nUnstructured error handling statements are not allowed in iterator or async methods.\n\n\n#### Error Statement\n\nAn `Error` statement throws a `System.Exception` exception containing a Visual Basic 6 exception number. The expression must be classified as a value and its type must be implicitly convertible to `Integer`.\n\n```antlr\nErrorStatement\n    : 'Error' Expression StatementTerminator\n    ;\n```\n\n#### On Error Statement\n\nAn `On Error` statement modifies the most recent exception-handling state.\n\n```antlr\nOnErrorStatement\n    : 'On' 'Error' ErrorClause StatementTerminator\n    ;\n\nErrorClause\n    : 'GoTo' '-' '1'\n    | 'GoTo' '0'\n    | GoToStatement\n    | 'Resume' 'Next'\n    ;\n```\n\nIt may be used in one of four ways:\n\n* `On Error GoTo -1` resets the most recent exception to `Nothing`.\n\n* `On Error GoTo 0` resets the most recent exception-handler location to `Nothing`.\n\n* `On Error GoTo LabelName` establishes the label as the most recent exception-handler location. This statement cannot be used in a method that contains a lambda or query expression.\n\n* `On Error Resume Next` establishes the `Resume Next` behavior as the most recent exception-handler location.\n\n\n#### Resume Statement\n\nA `Resume` statement returns execution to the statement that caused the most recent exception.\n\n```antlr\nResumeStatement\n    : 'Resume' ResumeClause? StatementTerminator\n    ;\n\nResumeClause\n    : 'Next'\n    | LabelName\n    ;\n```\n\nIf the `Next` modifier is specified, execution returns to the statement that would have been executed after the statement that caused the most recent exception. If a label name is specified, execution returns to the label.\n\nBecause the `SyncLock` statement contains an implicit structured error-handling block, `Resume` and `Resume Next` have special behaviors for exceptions that occur in `SyncLock` statements. `Resume` returns execution to the beginning of the `SyncLock` statement, while `Resume Next` returns execution to the next statement following the `SyncLock` statement. For example, consider the following code:\n\n```vb\nClass LockClass\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim FirstTime As Boolean = True\n        Dim Lock As LockClass = New LockClass()\n\n        On Error GoTo Handler\n\n        SyncLock Lock\n            Console.WriteLine(\"Before exception\")\n            Throw New Exception()\n            Console.WriteLine(\"After exception\")\n        End SyncLock\n\n        Console.WriteLine(\"After SyncLock\")\n        Exit Sub\n\nHandler:\n        If FirstTime Then\n            FirstTime = False\n            Resume\n        Else\n            Resume Next\n        End If\n    End Sub\nEnd Module\n```\n\nIt prints the following result.\n\n```console\nBefore exception\nBefore exception\nAfter SyncLock\n```\n\nThe first time through the `SyncLock` statement, `Resume` returns execution to the beginning of the `SyncLock` statement. The second time through the `SyncLock` statement, `Resume Next` returns execution to the end of the `SyncLock` statement. `Resume` and `Resume Next` are not allowed within a `SyncLock` statement.\n\nIn all cases, when a `Resume` statement is executed, the most recent exception is set to `Nothing`. If a `Resume` statement is executed with no most recent exception, the statement raises a `System.Exception` exception containing the Visual Basic error number `20` (Resume without error).\n\n\n## Branch Statements\n\nBranch statements modify the flow of execution in a method. There are six branch statements:\n\n1. A `GoTo` statement causes execution to transfer to the specified label in the method. It is not allowed to `GoTo` into a `Try`, `Using`, `SyncLock`, `With`, `For` or `For Each` block, nor into any loop block if a local variable of that block is captured in a lambda or LINQ expression.\n2. An `Exit` statement transfers execution to the next statement after the end of the immediately containing block statement of the specified kind. If the block is the method block, then control flow exits the method as described in Section [Control Flow](statements.md#control-flow). If the `Exit` statement is not contained within the kind of block specified in the statement, a compile-time error occurs.\n3. A `Continue` statement transfers execution to the end of the immediately containing block loop statement of the specified kind. If the `Continue` statement is not contained within the kind of block specified in the statement, a compile-time error occurs.\n4. A `Stop` statement causes a debugger exception to occur.\n5. An `End` statement terminates the program. Finalizers are run before shutdown, but the finally blocks of any currently executing `Try` statements are not executed. This statement may not be used in programs that are not executable (for example, DLLs).\n6. A `Return` statement with no expression is equivalent to an `Exit Sub` or `Exit Function` statement. A `Return` statement with an expression is only allowed in a regular method that is a function, or in an async method that is a function with return type `Task(Of T)` for some `T`. The expression must be classified as a value which is implicitly convertible to the *function return variable* (in the case of regular methods) or to the *task return variable* (in the case of async methods). Its behavior is to evaluate its expression, then store it in the return variable, then execute an implicit `Exit Function` statement.\n\n```antlr\nBranchStatement\n    : GoToStatement\n    | ExitStatement\n    | ContinueStatement\n    | StopStatement\n    | EndStatement\n    | ReturnStatement\n    ;\n\nGoToStatement\n    : 'GoTo' LabelName StatementTerminator\n    ;\n\nExitStatement\n    : 'Exit' ExitKind StatementTerminator\n    ;\n\nExitKind\n    : 'Do' | 'For' | 'While' | 'Select' | 'Sub' | 'Function' | 'Property' | 'Try'\n    ;\n\nContinueStatement\n    : 'Continue' ContinueKind StatementTerminator\n    ;\n\nContinueKind\n    : 'Do' | 'For' | 'While'\n    ;\n\nStopStatement\n    : 'Stop' StatementTerminator\n    ;\n\nEndStatement\n    : 'End' StatementTerminator\n    ;\n\nReturnStatement\n    : 'Return' Expression? StatementTerminator\n    ;\n```\n\n## Array-Handling Statements\n\nTwo statements simplify working with arrays: `ReDim` statements and `Erase` statements.\n\n```antlr\nArrayHandlingStatement\n    : RedimStatement\n    | EraseStatement\n    ;\n```\n\n### ReDim Statement\n\nA `ReDim` statement instantiates new arrays.\n\n```antlr\nRedimStatement\n    : 'ReDim' 'Preserve'? RedimClauses StatementTerminator\n    ;\n\nRedimClauses\n    : RedimClause ( Comma RedimClause )*\n    ;\n\nRedimClause\n    : Expression ArraySizeInitializationModifier\n    ;\n```\n\nEach clause in the statement must be classified as a variable or a property access whose type is an array type or `Object`, and be followed by a list of array bounds. The number of the bounds must be consistent with the type of the variable; any number of bounds is allowed for `Object`. At run time, an array is instantiated for each expression from left to right with the specified bounds and then assigned to the variable or property. If the variable type is `Object`, the number of dimensions is the number of dimensions specified, and the array element type is `Object`. If the given number of dimensions is incompatible with the variable or property at run time a compile-time error occurs. For example:\n\n```vb\nModule Test\n    Sub Main()\n        Dim o As Object\n        Dim b() As Byte\n        Dim i(,) As Integer\n\n        ' The next two statements are equivalent.\n        ReDim o(10,30)\n        o = New Object(10, 30) {}\n\n        ' The next two statements are equivalent.\n        ReDim b(10)\n        b = New Byte(10) {}\n\n        ' Error: Incorrect number of dimensions.\n        ReDim i(10, 30, 40)\n    End Sub\nEnd Module\n```\n\nIf the `Preserve` keyword is specified, then the expressions must also be classifiable as a value, and the new size for each dimension except for the rightmost one must be the same as the size of the existing array. The values in the existing array are copied into the new array: if the new array is smaller, the existing values are discarded; if the new array is bigger, the extra elements will be initialized to the default value of the element type of the array. For example, consider the following code:\n\n```vb\nModule Test\n    Sub Main()\n        Dim x(5, 5) As Integer\n\n        x(3, 3) = 3\n\n        ReDim Preserve x(5, 6)\n        Console.WriteLine(x(3, 3) & \", \" & x(3, 6))\n    End Sub\nEnd Module\n```\n\nIt prints the following result:\n\n```console\n3, 0\n```\n\nIf the existing array reference is a null value at run time, no error is given. Other than the rightmost dimension, if the size of a dimension changes, a `System.ArrayTypeMismatchException` will be thrown.\n\n__Note.__ `Preserve` is not a reserved word.\n\n\n### Erase Statement\n\nAn `Erase` statement sets each of the array variables or properties specified in the statement to `Nothing`. Each expression in the statement must be classified as a variable or property access whose type is an array type or `Object`. For example:\n\n```vb\nModule Test\n    Sub Main()\n        Dim x() As Integer = New Integer(5) {}\n\n        ' The following two statements are equivalent.\n        Erase x\n        x = Nothing\n    End Sub\nEnd Module\n```\n\n```antlr\nEraseStatement\n    : 'Erase' EraseExpressions StatementTerminator\n    ;\n\nEraseExpressions\n    : Expression ( Comma Expression )*\n    ;\n```\n\n## Using statement\n\nInstances of types are automatically released by the garbage collector when a collection is run and no live references to the instance are found. If a type holds on a particularly valuable and scarce resource (such as database connections or file handles), it may not be desirable to wait until the next garbage collection to clean up a particular instance of the type that is no longer in use. To provide a lightweight way of releasing resources before a collection, a type may implement the `System.IDisposable` interface. A type that does so exposes a `Dispose` method that can be called to force valuable resources to be released immediately, as such:\n\n```vb\nModule Test\n    Sub Main()\n        Dim x As DBConnection = New DBConnection(\"...\")\n\n        ' Do some work\n        ...\n\n        x.Dispose()        ' Free the connection\n    End Sub\nEnd Module\n```\n\nThe `Using` statement automates the process of acquiring a resource, executing a set of statements, and then disposing of the resource. The statement can take two forms: in one, the resource is a local variable declared as a part of the statement and treated as a regular local variable declaration statement; in the other, the resource is the result of an expression.\n\n```antlr\nUsingStatement\n    : 'Using' UsingResources StatementTerminator\n      Block?\n      'End' 'Using' StatementTerminator\n    ;\n\nUsingResources\n    : VariableDeclarators\n    | Expression\n    ;\n```\n\nIf the resource is a local variable declaration statement then the type of the local variable declaration must be a type that can be implicitly converted to `System.IDisposable`. The declared local variables are read-only, scoped to the `Using` statement block and must include an initializer. If the resource is the result of an expression then the expression must be classified as a value and must be of a type that can be implicitly converted to `System.IDisposable`. The expression is only evaluated once, at the beginning of the statement.\n\nThe `Using` block is implicitly contained by a `Try` statement whose finally block calls the method `IDisposable.Dispose` on the resource. This ensures the resource is disposed even when an exception is thrown. As a result, it is invalid to branch into a `Using` block from outside of the block, and a `Using` block is treated as a single statement for the purposes of `Resume` and `Resume Next`. If the resource is `Nothing`, then no call to `Dispose` is made. Thus, the example:\n\n```vb\nUsing f As C = New C()\n    ...\nEnd Using\n```\n\nis equivalent to:\n\n```vb\nDim f As C = New C()\nTry\n    ...\nFinally\n    If f IsNot Nothing Then\n        f.Dispose()\n    End If\nEnd Try\n```\n\nA `Using` statement that has a local variable declaration statement may acquire multiple resources at a time, which is equivalent to nested `Using` statements.  For example, a `Using` statement of the form:\n\n```vb\nUsing r1 As R = New R(), r2 As R = New R()\n    r1.F()\n    r2.F()\nEnd Using\n```\n\nis equivalent to:\n\n```vb\nUsing r1 As R = New R()\n    Using r2 As R = New R()\n        r1.F()\n        r2.F()\n    End Using\nEnd Using\n```\n\n\n## Await Statement\n\nAn await statement has the same syntax as an await operator expression (Section [Await Operator](expressions.md#await-operator)), is allowed only in methods that also allow await expressions, and has the same behavior as an await operator expression.\n\nHowever, it may be classified as either a value or void. Any value resulting from evaluation of the await operator expression is discarded.\n\n```antlr\nAwaitStatement\n    : AwaitOperatorExpression StatementTerminator\n    ;\n```\n\n## Yield Statement\n\nYield statements are related to iterator methods, which are described in Section [Iterator Methods](statements.md#iterator-methods).\n\n```antlr\nYieldStatement\n    : 'Yield' Expression StatementTerminator\n    ;\n```\n\n`Yield` is a reserved word if the immediately enclosing method or lambda expression in which it appears has an `Iterator` modifier, and if the `Yield` appears after that `Iterator` modifier; it is unreserved elsewhere. It is also unreserved in preprocessor directives. The yield statement is only allowed in the body of a method or lambda expression where it is a reserved word. Within the immediately enclosing method or lambda, the yield statement may not occur inside the body of a `Catch` or `Finally` block, nor inside the body of a `SyncLock` statement.\n\nThe yield statement takes a single expression which must be classified as a value and whose type is implicitly convertible to the type of the *iterator current variable* (Section [Iterator Methods](statements.md#iterator-methods)) of its enclosing iterator method.\n\nControl flow only ever reaches a `Yield` statement when the `MoveNext` method is invoked on an iterator object. (This is because an iterator method instance only ever executes its statements due to the `MoveNext` or `Dispose` methods being called on an iterator object; and the `Dispose` method will only ever execute code in `Finally` blocks, where `Yield` is not allowed).\n\nWhen a `Yield` statement is executed, its expression is evaluated and stored in the *iterator current variable* of the iterator method instance associated with that iterator object. The value `True` is returned to the invoker of `MoveNext`, and the control point of this instance stops advancing until the next invocation of `MoveNext` on the iterator object.\n\n"
  },
  {
    "path": "spec/type-members.md",
    "content": "# Type Members\n\nType members define storage locations and executable code. They can be methods, constructors, events, constants, variables, and properties.\n\n## Interface Method Implementation\n\nMethods, events, and properties can implement interface members. To implement an interface member, a member declaration specifies the `Implements` keyword and lists one or more interface members.\n\n```antlr\nImplementsClause\n    : ( 'Implements' ImplementsList )?\n    ;\n\nImplementsList\n    : InterfaceMemberSpecifier ( Comma InterfaceMemberSpecifier )*\n    ;\n\nInterfaceMemberSpecifier\n    : NonArrayTypeName Period IdentifierOrKeyword\n    ;\n```\n\nMethods and properties that implement interface members are implicitly `NotOverridable` unless declared to be `MustOverride`, `Overridable`, or overriding another member. It is an error for a member implementing an interface member to be `Shared`. A member's accessibility has no effect on its ability to implement interface members.\n\nFor an interface implementation to be valid, the implements list of the containing type must name an interface that contains a compatible member. A compatible member is one whose signature matches the signature of the implementing member. If a generic interface is being implemented, then the type argument supplied in the Implements clause is substituted into the signature when checking compatibility. For example:\n\n```vb\nInterface I1(Of T)\n    Sub F(x As T)\nEnd Interface\n\nClass C1\n    Implements I1(Of Integer)\n\n    Sub F(x As Integer) Implements I1(Of Integer).F\n    End Sub\nEnd Class\n\nClass C2(Of U)\n    Implements I1(Of U)\n\n    Sub F(x As U) Implements I1(Of U).F\n    End Sub\nEnd Class\n```\n\nIf an event declared using a delegate type is implementing an interface event, then a compatible event is one whose underlying delegate type is the same type. Otherwise, the event uses the delegate type from the interface event it is implementing. If such an event implements multiple interface events, all the interface events must have the same underlying delegate type. For example:\n\n```vb\nInterface ClickEvents\n    Event LeftClick(x As Integer, y As Integer)\n    Event RightClick(x As Integer, y As Integer)\nEnd Interface\n\nClass Button\n    Implements ClickEvents\n\n    ' OK. Signatures match, delegate type = ClickEvents.LeftClickHandler.\n    Event LeftClick(x As Integer, y As Integer) _\n        Implements ClickEvents.LeftClick\n\n    ' OK. Signatures match, delegate type = ClickEvents.RightClickHandler.\n    Event RightClick(x As Integer, y As Integer) _\n        Implements ClickEvents.RightClick\nEnd Class\n\nClass Label\n    Implements ClickEvents\n\n    ' Error. Signatures match, but can't be both delegate types.\n    Event Click(x As Integer, y As Integer) _\n        Implements ClickEvents.LeftClick, ClickEvents.RightClick\nEnd Class\n```\n\nAn interface member in the implements list is specified using a type name, a period, and an identifier. The type name must be an interface in the implements list or a base interface of an interface in the implements list, and the identifier must be a member of the specified interface. A single member can implement more than one matching interface member.\n\n```vb\nInterface ILeft\n    Sub F()\nEnd Interface\n\nInterface IRight\n    Sub F()\nEnd Interface\n\nClass Test\n    Implements ILeft, IRight\n\n    Sub F() Implements ILeft.F, IRight.F\n    End Sub\nEnd Class\n```\n\nIf the interface member being implemented is unavailable in all explicitly implemented interfaces because of multiple interface inheritance, the implementing member must explicitly reference a base interface on which the member is available. For example, if `I1` and `I2` contain a member `M`, and `I3` inherits from `I1` and `I2`, a type implementing `I3` will implement `I1.M` and `I2.M`. If an interface shadows multiply inherited members, an implementing type will have to implement the inherited members and the member(s) shadowing them.\n\n```vb\nInterface ILeft\n    Sub F()\nEnd Interface\n\nInterface IRight\n    Sub F()\nEnd Interface\n\nInterface ILeftRight\n    Inherits ILeft, IRight\n\n    Shadows Sub F()\nEnd Interface\n\nClass Test\n    Implements ILeftRight\n\n    Sub LeftF() Implements ILeft.F\n    End Sub\n\n    Sub RightF() Implements IRight.F\n    End Sub\n\n    Sub LeftRightF() Implements ILeftRight.F\n    End Sub\nEnd Class\n```\n\nIf the containing interface of the interface member be implemented is generic, the same type arguments as the interface being implements must be supplied. For example:\n\n```vb\nInterface I1(Of T)\n    Function F() As T\nEnd Interface\n\nClass C1\n    Implements I1(Of Integer)\n    Implements I1(Of Double)\n\n    Function F1() As Integer Implements I1(Of Integer).F\n    End Function\n\n    Function F2() As Double Implements I1(Of Double).F\n    End Function\n\n    ' Error: I1(Of String) is not implemented by C1\n    Function F3() As String Implements I1(Of String).F\n    End Function\nEnd Class\n\nClass C2(Of U)\n    Implements I1(Of U)\n\n    Function F() As U Implements I1(Of U).F\n    End Function\nEnd Class\n```\n\n\n## Methods\n\nMethods contain the executable statements of a program.\n\n```antlr\nMethodMemberDeclaration\n    : MethodDeclaration\n    | ExternalMethodDeclaration\n    ;\n\nInterfaceMethodMemberDeclaration\n    : InterfaceMethodDeclaration\n    ;\n\nMethodDeclaration\n    : SubDeclaration\n    | MustOverrideSubDeclaration\n    | FunctionDeclaration\n    | MustOverrideFunctionDeclaration\n    ;\n\nInterfaceMethodDeclaration\n    : InterfaceSubDeclaration\n    | InterfaceFunctionDeclaration\n    ;\n\nSubSignature\n    : 'Sub' Identifier TypeParameterList?\n      ( OpenParenthesis ParameterList? CloseParenthesis )?\n    ;\n\nFunctionSignature\n    : 'Function' Identifier TypeParameterList?\n      ( OpenParenthesis ParameterList? CloseParenthesis )?\n      ( 'As' Attributes? TypeName )?\n    ;\n\nSubDeclaration\n    : Attributes? ProcedureModifier* SubSignature\n      HandlesOrImplements? LineTerminator\n      Block\n      'End' 'Sub' StatementTerminator\n    ;\n\nMustOverrideSubDeclaration\n    : Attributes? MustOverrideProcedureModifier+ SubSignature\n      HandlesOrImplements? StatementTerminator\n    ;\n\nInterfaceSubDeclaration\n    : Attributes? InterfaceProcedureModifier* SubSignature StatementTerminator\n    ;\n\nFunctionDeclaration\n    : Attributes? ProcedureModifier* FunctionSignature\n      HandlesOrImplements? LineTerminator\n      Block\n      'End' 'Function' StatementTerminator\n    ;\n\nMustOverrideFunctionDeclaration\n    : Attributes? MustOverrideProcedureModifier+ FunctionSignature\n      HandlesOrImplements? StatementTerminator\n    ;\n\nInterfaceFunctionDeclaration\n    : Attributes? InterfaceProcedureModifier* FunctionSignature StatementTerminator\n    ;\n\nProcedureModifier\n    : AccessModifier | 'Shadows' | 'Shared' | 'Overridable' | 'NotOverridable' | 'Overrides'\n    | 'Overloads' | 'Partial' | 'Iterator' | 'Async'\n    ;\n\nMustOverrideProcedureModifier\n    : ProcedureModifier\n    | 'MustOverride'\n    ;\n\nInterfaceProcedureModifier\n    : 'Shadows' | 'Overloads'\n    ;\n\nHandlesOrImplements\n    : HandlesClause\n    | ImplementsClause\n    ;\n```\n\nMethods, which have an optional list of parameters and an optional return value, are either shared or not shared. Shared methods are accessed through the class or instances of the class. Non-shared methods, also called instance methods, are accessed through instances of the class. The following example shows a class `Stack` that has several shared methods (`Clone` and `Flip`), and several instance methods (`Push`, `Pop`, and `ToString`):\n\n```vb\nPublic Class Stack\n    Public Shared Function Clone(s As Stack) As Stack\n        ...\n    End Function\n\n    Public Shared Function Flip(s As Stack) As Stack\n        ...\n    End Function\n\n    Public Function Pop() As Object\n        ...\n    End Function\n\n    Public Sub Push(o As Object)\n        ...\n    End Sub \n\n    Public Overrides Function ToString() As String\n        ...\n    End Function \nEnd Class \n\nModule Test\n    Sub Main()\n        Dim s As Stack = New Stack()\n        Dim i As Integer\n\n        While i < 10\n            s.Push(i)\n        End While\n\n        Dim flipped As Stack = Stack.Flip(s)\n        Dim cloned As Stack = Stack.Clone(s)\n\n        Console.WriteLine(\"Original stack: \" & s.ToString())\n        Console.WriteLine(\"Flipped stack: \" & flipped.ToString())\n        Console.WriteLine(\"Cloned stack: \" & cloned.ToString())\n    End Sub\nEnd Module\n```\n\nMethods can be overloaded, which means that multiple methods may have the same name so long as they have unique signatures. The signature of a method consists of the number and types of its parameters. The signature of a method specifically does not include the return type or parameter modifiers such as Optional, ByRef or ParamArray. The following example shows a class with a number of overloads:\n\n```vb\nModule Test\n    Sub F()\n        Console.WriteLine(\"F()\")\n    End Sub \n\n    Sub F(o As Object)\n        Console.WriteLine(\"F(Object)\")\n    End Sub\n\n    Sub F(value As Integer)\n        Console.WriteLine(\"F(Integer)\")\n    End Sub \n\n    Sub F(a As Integer, b As Integer)\n        Console.WriteLine(\"F(Integer, Integer)\")\n    End Sub \n\n    Sub F(values() As Integer)\n        Console.WriteLine(\"F(Integer())\")\n    End Sub \n\n    Sub G(s As String, Optional s2 As String = 5)\n        Console.WriteLine(\"G(String, Optional String\")\n    End Sub\n\n    Sub G(s As String)\n        Console.WriteLine(\"G(String)\")\n    End Sub\n\n\n    Sub Main()\n        F()\n        F(1)\n        F(CType(1, Object))\n        F(1, 2)\n        F(New Integer() { 1, 2, 3 })\n        G(\"hello\")\n        G(\"hello\", \"world\")\n    End Sub\nEnd Module\n```\n\nThe output of the program is:\n\n```console\nF()\nF(Integer)\nF(Object)\nF(Integer, Integer)\nF(Integer())\nG(String)\nG(String, Optional String)\n```\n\nOverloads that differ only in optional parameters can be used for \"versioning\" of libraries. For instance, v1 of a library might include a function with optional parameters:\n\n```vb\nSub fopen(fileName As String, Optional accessMode as Integer = 0)\n```\n\nThen v2 of the library wants to add another optional parameter \"password\", and it wants to do so without breaking source compatibility (so applications that used to target v1 can be recompiled), and without breaking binary compatibility (so applications that used to reference v1 can now reference v2 without recompilation). This is how v2 will look:\n\n```vb\nSub fopen(file As String, mode as Integer)\nSub fopen(file As String, Optional mode as Integer = 0, Optional pword As String = \"\")\n```\n\nNote that optional parameters in a public API are not CLS-compliant. However, they can be consumed at least by Visual Basic and C#4 and F#.\n\n\n\n### Regular, Async and Iterator Method Declarations\n\nThere are two types of methods: *subroutines*, which do not return values, and *functions*, which do. The body and `End` construct of a method may only be omitted if the method is defined in an interface or has the `MustOverride` modifier. If no return type is specified on a function and strict semantics are being used, a compile-time error occurs; otherwise the type is implicitly `Object` or the type of the method's type character. The accessibility domain of the return type and parameter types of a method must be the same as or a superset of the accessibility domain of the method itself.\n\nA __regular method__ is one with neither `Async` nor `Iterator` modifiers. It may be a subroutine or a function. Section [Regular Methods](statements.md#regular-methods) details what happens when a regular method is invoked.\n\nAn __iterator method__ is one with the `Iterator` modifier and no `Async` modifier. It must be a function, and its return type must be `IEnumerator`, `IEnumerable`, or `IEnumerator(Of T)` or `IEnumerable(Of T)` for some `T`, and it must have no `ByRef` parameters. Section [Iterator Methods](statements.md#iterator-methods) details what happens when an iterator method is invoked.\n\nAn __async method__ is one with the `Async` modifier and no `Iterator` modifier. It must be either a subroutine, or a function with return type `Task` or `Task(Of T)` for some `T`, and must have no `ByRef` parameters. Section [Async Methods](statements.md#async-methods) details what happens when an async method is invoked.\n\nIt is a compile-time error if a method is not one of these three kinds of method.\n\nSubroutine and function declarations are special in that their beginning and end statements must each start at the beginning of a logical line. Additionally, the body of a non-`MustOverride` subroutine or function declaration must start at the beginning of a logical line. For example:\n\n```vb\nModule Test\n    ' Illegal: Subroutine doesn't start the line\n    Public x As Integer : Sub F() : End Sub\n\n    ' Illegal: First statement doesn't start the line\n    Sub G() : Console.WriteLine(\"G\")\n    End Sub\n\n    ' Illegal: End Sub doesn't start the line\n    Sub H() : End Sub\nEnd Module\n```\n\n\n### External Method Declarations\n\nAn external method declaration introduces a new method whose implementation is provided external to the program.\n\n```antlr\nExternalMethodDeclaration\n    : ExternalSubDeclaration\n    | ExternalFunctionDeclaration\n    ;\n\nExternalSubDeclaration\n    : Attributes? ExternalMethodModifier* 'Declare' CharsetModifier? 'Sub'\n      Identifier LibraryClause AliasClause?\n      ( OpenParenthesis ParameterList? CloseParenthesis )? StatementTerminator\n    ;\n\nExternalFunctionDeclaration\n    : Attributes? ExternalMethodModifier* 'Declare' CharsetModifier? 'Function'\n      Identifier LibraryClause AliasClause?\n      ( OpenParenthesis ParameterList? CloseParenthesis )?\n      ( 'As' Attributes? TypeName )?\n      StatementTerminator\n    ;\n\nExternalMethodModifier\n    : AccessModifier\n    | 'Shadows'\n    | 'Overloads'\n    ;\n\nCharsetModifier\n    : 'Ansi' | 'Unicode' | 'Auto'\n    ;\n\nLibraryClause\n    : 'Lib' StringLiteral\n    ;\n\nAliasClause\n    : 'Alias' StringLiteral\n    ;\n```\n\nBecause an external method declaration provides no actual implementation, it has no method body or `End` construct. External methods are implicitly shared, may not have type parameters, and may not handle events or implement interface members. If no return type is specified on a function and strict semantics are being used, a compile-time error occurs. Otherwise the type is implicitly `Object` or the type of the method's type character. The accessibility domain of the return type and parameter types of an external method must be the same as or a superset of the accessibility domain of the external method itself.\n\nThe library clause of an external method declaration specifies the name of the external file that implements the method. The optional alias clause is a string that specifies the numeric ordinal (prefixed by a `#` character) or name of the method in the external file. A single-character set modifier may also be specified, which governs the character set used to marshal strings during a call to the external method. The `Unicode` modifier marshals all strings to Unicode values, the `Ansi` modifier marshals all strings to ANSI values, and the `Auto` modifier marshals the strings according to .NET Framework rules based on the name of the method, or the alias name if specified. If no modifier is specified, the default is `Ansi`.\n\nIf `Ansi` or `Unicode` is specified, then the method name is looked up in the external file with no modification. If `Auto` is specified, then method name lookup depends on the platform. If the platform is considered to be ANSI (for example, Windows 95, Windows 98, Windows ME), then the method name is looked up with no modification. If the lookup fails, an `A` is appended and the lookup tried again. If the platform is considered to be Unicode (for example, Windows NT, Windows 2000, Windows XP), then a `W` is appended and the name is looked up. If the lookup fails, the lookup is tried again without the `W`. For example:\n\n```vb\nModule Test\n    ' All platforms bind to \"ExternSub\".\n    Declare Ansi Sub ExternSub Lib \"ExternDLL\" ()\n\n    ' All platforms bind to \"ExternSub\".\n    Declare Unicode Sub ExternSub Lib \"ExternDLL\" ()\n\n    ' ANSI platforms: bind to \"ExternSub\" then \"ExternSubA\".\n    ' Unicode platforms: bind to \"ExternSubW\" then \"ExternSub\".\n    Declare Auto Sub ExternSub Lib \"ExternDLL\" ()\nEnd Module\n```\n\nData types being passed to external methods are marshaled according to the .NET Framework data marshalling conventions with one exception. String variables that are passed by value (that is, `ByVal x As String`) are marshaled to the OLE Automation BSTR type, and changes made to the BSTR in the external method are reflected back in the string argument. This is because the type `String` in external methods is mutable, and this special marshalling mimics that behavior. String parameters that are passed by reference (i.e. `ByRef x As String`) are marshaled as a pointer to the OLE Automation BSTR type. It is possible to override these special behaviors by specifying the `System.Runtime.InteropServices.MarshalAsAttribute` attribute on the parameter.\n\nThe example demonstrates use of external methods:\n\n```vb\nClass Path\n    Declare Function CreateDirectory Lib \"kernel32\" ( _\n        Name As String, sa As SecurityAttributes) As Boolean\n    Declare Function RemoveDirectory Lib \"kernel32\" ( _\n        Name As String) As Boolean\n    Declare Function GetCurrentDirectory Lib \"kernel32\" ( _\n        BufSize As Integer, Buf As String) As Integer\n    Declare Function SetCurrentDirectory Lib \"kernel32\" ( _\n        Name As String) As Boolean\nEnd Class\n```\n\n\n### Overridable Methods\n\nThe `Overridable` modifier indicates that a method is overridable. The `Overrides` modifier indicates that a method overrides a base-type overridable method that has the same signature. The `NotOverridable` modifier indicates that an overridable method cannot be further overridden. The `MustOverride` modifier indicates that a method must be overridden in derived classes.\n\nCertain combinations of these modifiers are not valid:\n\n* `Overridable` and `NotOverridable` are mutually exclusive and cannot be combined.\n\n* `MustOverride` implies `Overridable` (and so cannot specify it) and cannot be combined with `NotOverridable`.\n\n* `NotOverridable` cannot be combined with `Overridable` or `MustOverride` and must be combined with `Overrides`.\n\n* `Overrides` implies `Overridable` (and so cannot specify it) and cannot be combined with `MustOverride`.\n\nThere are also additional restrictions on overridable methods:\n\n* A `MustOverride` method may not include a method body or an `End` construct, may not override another method, and may only appear in `MustInherit` classes.\n\n* If a method specifies `Overrides` and there is no matching base method to override, a compile-time error occurs. An overriding method may not specify `Shadows`.\n\n* A method may not override another method if the overriding method's accessibility domain is not equal to the accessibility domain of the method being overridden. The one exception is that a method overriding a `Protected Friend` method in another assembly that does not have `Friend` access must specify `Protected` (not `Protected Friend`).\n\n* `Private` methods may not be `Overridable`, `NotOverridable`, or `MustOverride`, nor may they override other methods.\n\n* Methods in `NotInheritable` classes may not be declared `Overridable` or `MustOverride`.\n\nThe following example illustrates the differences between overridable and nonoverridable methods:\n\n```vb\nClass Base\n    Public Sub F()\n        Console.WriteLine(\"Base.F\")\n    End Sub\n\n    Public Overridable Sub G()\n        Console.WriteLine(\"Base.G\")\n    End Sub\nEnd Class\n\nClass Derived\n    Inherits Base\n\n    Public Shadows Sub F()\n        Console.WriteLine(\"Derived.F\")\n    End Sub\n\n    Public Overrides Sub G()\n        Console.WriteLine(\"Derived.G\")\n    End Sub\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim d As Derived = New Derived()\n        Dim b As Base = d\n\n        b.F()\n        d.F()\n        b.G()\n        d.G()\n    End Sub\nEnd Module\n```\n\nIn the example, class `Base` introduces a method `F` and an `Overridable` method `G`. The class `Derived` introduces a new method `F`, thus shadowing the inherited `F`, and also overrides the inherited method `G`. The example produces the following output:\n\n```console\nBase.F\nDerived.F\nDerived.G\nDerived.G\n```\n\nNotice that the statement `b.G()` invokes `Derived.G`, not `Base.G`. This is because the run-time type of the instance (which is `Derived`) rather than the compile-time type of the instance (which is `Base`) determines the actual method implementation to invoke.\n\n### Shared Methods\n\nThe `Shared` modifier indicates a method is a *shared method*. A shared method does not operate on a specific instance of a type and may be invoked directly from a type rather than through a particular instance of a type. It is valid, however, to use an instance to qualify a shared method. It is invalid to refer to `Me`, `MyClass`, or `MyBase` in a shared method. Shared methods may not be `Overridable`, `NotOverridable`, or `MustOverride`, and they may not override methods. Methods defined in standard modules and interfaces may not specify `Shared`, because they are implicitly `Shared` already.\n\nA method declared in a structure or class without a `Shared` modifier is an *instance method*. An instance method operates on a given instance of a type. Instance methods can only be invoked through an instance of a type and may refer to the instance through the `Me` expression.\n\nThe following example illustrates the rules for accessing shared and instance members:\n\n```vb\nClass Test\n    Private x As Integer\n    Private Shared y As Integer\n\n    Sub F()\n        x = 1 ' Ok, same as Me.x = 1.\n        y = 1 ' Ok, same as Test.y = 1.\n    End Sub\n\n    Shared Sub G()\n        x = 1 ' Error, cannot access Me.x.\n        y = 1 ' Ok, same as Test.y = 1.\n    End Sub\n\n    Shared Sub Main()\n        Dim t As Test = New Test()\n\n        t.x = 1 ' Ok.\n        t.y = 1 ' Ok.\n        Test.x = 1 ' Error, cannot access instance member through type.\n        Test.y = 1 ' Ok.\n    End Sub\nEnd Class\n```\n\nMethod `F` shows that in an instance function member, an identifier can be used to access both instance members and shared members. Method `G` shows that in a shared function member, it is an error to access an instance member through an identifier. Method `Main` shows that in a member access expression, instance members must be accessed through instances, but shared members can be accessed through types or instances.\n\n### Method Parameters\n\nA *parameter* is a variable that can be used to pass information into and out of a method. Parameters of a method are declared by the method's parameter list, which consists of one or more parameters separated by commas.\n\n```antlr\nParameterList\n    : Parameter ( Comma Parameter )*\n    ;\n\nParameter\n    : Attributes? ParameterModifier* ParameterIdentifier ( 'As' TypeName )?\n      ( Equals ConstantExpression )?\n    ;\n\nParameterModifier\n    : 'ByVal' | 'ByRef' | 'Optional' | 'ParamArray'\n    ;\n\nParameterIdentifier\n    : Identifier IdentifierModifiers\n    ;\n```\n\nIf no type is specified for a parameter and strict semantics are used, a compile-time error occurs. Otherwise the default type is `Object` or the type of the parameter's type character. Even under permissive semantics, if one parameter includes an `As` clause, all parameters must specify types.\n\nParameters are specified as value, reference, optional, or paramarray parameters by the modifiers `ByVal`, `ByRef`, `Optional`, and `ParamArray`, respectively. A parameter that does not specify `ByRef` or `ByVal` defaults to `ByVal`.\n\nParameter names are scoped to the entire body of the method and are always publicly accessible. A method invocation creates a copy, specific to that invocation, of the parameters, and the argument list of the invocation assigns values or variable references to the newly created parameters. Because external method declarations and delegate declarations have no body, duplicate parameter names are allowed in parameter lists, but discouraged.\n\nThe identifier may be followed by the nullable name modifier `?` to indicate that it is nullable, and also by array name modifiers to indicate that it is an array. They may be combined, e.g. \"`ByVal x?() As Integer`\". It is not allowed to use explicit array bounds; also, if the nullable name modifier is present then an `As` clause must be present.\n\n\n#### Value Parameters\n\nA *value parameter* is declared with an explicit `ByVal` modifier. If the `ByVal` modifier is used, the `ByRef` modifier may not be specified. A value parameter comes into existence with the invocation of the member the parameter belongs to, and is initialized with the value of the argument given in the invocation. A value parameter ceases to exist upon return of the member.\n\nA method is permitted to assign new values to a value parameter. Such assignments only affect the local storage location represented by the value parameter; they have no effect on the actual argument given in the method invocation.\n\nA value parameter is used when the value of an argument is passed into a method, and modifications of the parameter do not impact the original argument. A value parameter refers to its own variable, one that is distinct from the variable of the corresponding argument. This variable is initialized by copying the value of the corresponding argument. The following example shows a method `F` that has a value parameter named `p`:\n\n```vb\nModule Test\n    Sub F(p As Integer)\n        Console.WriteLine(\"p = \" & p)\n        p += 1\n    End Sub \n\n    Sub Main()\n        Dim a As Integer = 1\n\n        Console.WriteLine(\"pre: a = \" & a)\n        F(a)\n        Console.WriteLine(\"post: a = \" & a)\n    End Sub\nEnd Module\n```\n\nThe example produces the following output, even though the value parameter `p` is modified:\n\n```console\npre: a = 1\np = 1\npost: a = 1\n```\n\n#### Reference Parameters\n\nA reference parameter is a parameter declared with a `ByRef` modifier. If the `ByRef` modifier is specified, the `ByVal` modifier may not be used. A reference parameter does not create a new storage location. Instead, a reference parameter represents the variable given as the argument in the method or constructor invocation. Conceptually, the value of a reference parameter is always the same as the underlying variable.\n\nReference parameters act in two modes, either as *aliases* or through *copy-in copy-back.*\n\n__Aliases.__ A reference parameter is used when the parameter acts as an alias for a caller-provided argument. A reference parameter does not itself define a variable, but rather refers to the variable of the corresponding argument. Modifications of a reference parameter directly and immediately impact the corresponding argument. The following example shows a method `Swap` that has two reference parameters:\n\n```vb\nModule Test\n    Sub Swap(ByRef a As Integer, ByRef b As Integer)\n        Dim t As Integer = a\n        a = b\n        b = t\n    End Sub \n\n    Sub Main()\n        Dim x As Integer = 1\n        Dim y As Integer = 2\n\n        Console.WriteLine(\"pre: x = \" & x & \", y = \" & y)\n        Swap(x, y)\n        Console.WriteLine(\"post: x = \" & x & \", y = \" & y)\n    End Sub \nEnd Module\n```\n\nThe output of the program is:\n\n```console\npre: x = 1, y = 2\npost: x = 2, y = 1\n```\n\nFor the invocation of method `Swap` in class `Main`, `a` represents `x,` and `b` represents `y`. Thus, the invocation has the effect of swapping the values of `x` and `y`.\n\nIn a method that takes reference parameters, it is possible for multiple names to represent the same storage location:\n\n```vb\nModule Test\n    Private s As String\n\n    Sub F(ByRef a As String, ByRef b As String)\n        s = \"One\"\n        a = \"Two\"\n        b = \"Three\"\n    End Sub\n\n    Sub G()\n        F(s, s)\n    End Sub\nEnd Module\n```\n\nIn the example the invocation of method `F` in `G` passes a reference to `s` for both `a` and `b`. Thus, for that invocation, the names `s`, `a`, and `b` all refer to the same storage location, and the three assignments all modify the instance variable `s`.\n\n__Copy-in copy-back.__ If the type of the variable being passed to a reference parameter is not compatible with the reference parameter's type, or if a non-variable (e.g. a property) is passed as an argument to a reference parameter, or if the invocation is late-bound, then a temporary variable is allocated and passed to the reference parameter. The value being passed in will be copied into this temporary variable before the method is invoked and will be copied back to the original variable (if there is one and if it's writable) when the method returns. Thus, a reference parameter may not necessarily contain a reference to the exact storage of the variable being passed in, and any changes to the reference parameter may not be reflected in the variable until the method exits. For example:\n\n```vb\nClass Base\nEnd Class\n\nClass Derived\n    Inherits Base\nEnd Class\n\nModule Test\n    Sub F(ByRef b As Base)\n        b = New Base()\n    End Sub\n\n    Property G() As Base\n        Get\n        End Get\n        Set\n        End Set\n    End Property\n\n    Sub Main()\n        Dim d As Derived\n\n        F(G)   ' OK.\n        F(d)   ' Throws System.InvalidCastException after F returns.\n    End Sub\nEnd Module\n```\n\nIn the case of the first invocation of `F`, a temporary variable is created and the value of the property `G` is assigned to it and passed into `F`. Upon return from `F`, the value in the temporary variable is assigned back to the property of `G`. In the second case, another temporary variable is created and the value of `d` is assigned to it and passed into `F`. When returning from `F`, the value in the temporary variable is cast back to the type of the variable, `Derived`, and assigned to `d`. Since the value being passed back cannot be cast to `Derived`, an exception is thrown at run time.\n\n#### Optional Parameters\n\nAn optional parameter is declared with the `Optional` modifier. Parameters that follow an optional parameter in the formal parameter list must be optional as well; failure to specify the `Optional` modifier on the following parameters will trigger a compile-time error. An optional parameter of some type nullable type `T?` or non-nullable type `T` must specify a constant expression `e` to be used as a default value if no argument is specified. If `e` evaluates to `Nothing` of type Object, then the default value of the *parameter type* will be used as the default for the parameter. Otherwise, `CType(e, T)` must be a constant expression and it is taken as the default for the parameter.\n\nOptional parameters are the only situation in which an initializer on a parameter is valid. The initialization is always done as a part of the invocation expression, not within the method body itself.\n\n```vb\nModule Test\n    Sub F(x As Integer, Optional y As Integer = 20)\n        Console.WriteLine(\"x = \" & x & \", y = \" & y)\n    End Sub\n\n    Sub Main()\n        F(10)\n        F(30,40)\n    End Sub\nEnd Module\n```\n\nThe output of the program is:\n\n```console\nx = 10, y = 20\nx = 30, y = 40\n```\n\nOptional parameters may not be specified in delegate or event declarations, nor in lambda expressions.\n\n#### ParamArray Parameters\n\n`ParamArray` parameters are declared with the `ParamArray` modifier. If the `ParamArray` modifier is present, the `ByVal` modifier must be specified, and no other parameter may use the `ParamArray` modifier. The `ParamArray` parameter's type must be a one-dimensional array, and it must be the last parameter in the parameter list.\n\nA `ParamArray` parameter represents an indeterminate number of parameters of the type of the `ParamArray`. Within the method itself, a `ParamArray` parameter is treated as its declared type and has no special semantics. A `ParamArray` parameter is implicitly optional, with a default value of an empty one-dimensional array of the type of the `ParamArray`.\n\nA `ParamArray` permits arguments to be specified in one of two ways in a method invocation:\n\n* The argument given for a `ParamArray` can be a single expression of a type that widens to the `ParamArray` type. In this case, the `ParamArray` acts precisely like a value parameter.\n\n* Alternatively, the invocation can specify zero or more arguments for the `ParamArray`, where each argument is an expression of a type that is implicitly convertible to the element type of the `ParamArray`. In this case, the invocation creates an instance of the `ParamArray` type with a length corresponding to the number of arguments, initializes the elements of the array instance with the given argument values, and uses the newly created array instance as the actual argument.\n\nExcept for allowing a variable number of arguments in an invocation, a `ParamArray` is precisely equivalent to a value parameter of the same type, as the following example illustrates.\n\n```vb\nModule Test\n    Sub F(ParamArray args() As Integer)\n        Dim i As Integer\n\n        Console.Write(\"Array contains \" & args.Length & \" elements:\")\n        For Each i In args\n            Console.Write(\" \" & i)\n        Next i\n        Console.WriteLine()\n    End Sub\n\n    Sub Main()\n        Dim a As Integer() = { 1, 2, 3 }\n\n        F(a)\n        F(10, 20, 30, 40)\n        F()\n    End Sub\nEnd Module\n```\n\nThe example produces the output\n\n```console\nArray contains 3 elements: 1 2 3\nArray contains 4 elements: 10 20 30 40\nArray contains 0 elements:\n```\n\nThe first invocation of `F` simply passes the array `a` as a value parameter. The second invocation of `F` automatically creates a four-element array with the given element values and passes that array instance as a value parameter. Likewise, the third invocation of `F` creates a zero-element array and passes that instance as a value parameter. The second and third invocations are precisely equivalent to writing:\n\n```vb\nF(New Integer() {10, 20, 30, 40})\nF(New Integer() {})\n```\n\n`ParamArray` parameters may not be specified in delegate or event declarations.\n\n### Event Handling\n\nMethods can declaratively handle events raised by objects in instance or shared variables. To handle events, a method declaration specifies the `Handles` keyword and lists one or more events.\n\n```antlr\nHandlesClause\n    : ( 'Handles' EventHandlesList )?\n    ;\n\nEventHandlesList\n    : EventMemberSpecifier ( Comma EventMemberSpecifier )*\n    ;\n\nEventMemberSpecifier\n    : Identifier Period IdentifierOrKeyword\n    | 'MyBase' Period IdentifierOrKeyword\n    | 'MyClass' Period IdentifierOrKeyword\n    | 'Me' Period IdentifierOrKeyword\n    ;\n```\n\nAn event in the `Handles` list is specified by two identifiers separated by a period:\n\n* The first identifier must be an instance or shared variable in the containing type that specifies the `WithEvents` modifier or the `MyBase` or `MyClass` or `Me` keyword; otherwise, a compile-time error occurs. This variable contains the object that will raise the events handled by this method.\n\n* The second identifier must specify a member of the type of the first identifier. The member must be an event, and may be shared. If a shared variable is specified for the first identifier, then the event must be shared, or an error results.\n\nA handler method `M` is considered a valid event handler for an event `E` if the statement `AddHandler E, AddressOf M` would also be valid. Unlike an `AddHandler` statement, however, explicit event handlers allow handling an event with a method with no arguments regardless of whether strict semantics are being used or not:\n\n```vb\nOption Strict On\n\nClass C1\n    Event E(x As Integer)\nEnd Class\n\nClass C2\n    withEvents C1 As New C1()\n\n    ' Valid\n    Sub M1() Handles C1.E\n    End Sub\n\n    Sub M2()\n        ' Invalid\n        AddHandler C1.E, AddressOf M1\n    End Sub\nEnd Class\n```\n\nA single member can handle multiple matching events, and multiple methods may handle a single event. A method's accessibility has no effect on its ability to handle events. The following example shows how a method can handle events:\n\n```vb\nClass Raiser\n    Event E1()\n\n    Sub Raise()\n        RaiseEvent E1\n    End Sub\nEnd Class\n\nModule Test\n    WithEvents x As Raiser\n\n    Sub E1Handler() Handles x.E1\n        Console.WriteLine(\"Raised\")\n    End Sub\n\n    Sub Main()\n        x = New Raiser()\n        x.Raise()\n        x.Raise()\n    End Sub\nEnd Module\n```\n\nThis will print out:\n\n```console\nRaised\nRaised\n```\n\nA type inherits all event handlers provided by its base type. A derived type cannot in any way alter the event mappings it inherits from its base types, but may add additional handlers to the event.\n\n\n### Extension Methods\n\nMethods can be added to types from outside of the type declaration using *extension methods*. Extension methods are methods with the `System.Runtime.CompilerServices.ExtensionAttribute` attribute applied to them. They can only be declared in standard modules and must have at least one parameter, which specifies the type the method extends. For example, the following extension method extends the type `String`:\n\n```vb\nImports System.Runtime.CompilerServices\n\nModule StringExtensions\n    <Extension> _\n    Sub Print(s As String)\n        Console.WriteLine(s)\n    End Sub\nEnd Module\n```\n\n__Note.__ Although Visual Basic requires extension methods to be declared in a standard module, other languages such as C# may allow them to be declared in other kinds of types. As long as the methods follow the other conventions outlined here and the containing type is not an open generic type and cannot be instantiated, Visual Basic will recognize the extension methods.\n\nWhen an extension method is invoked, the instance it is being invoked on is passed to the first parameter. The first parameter cannot be declared `Optional` or `ParamArray`. Any type, including a type parameter, can appear as the first parameter of an extension method. For example, the following methods extend the types `Integer()`, any type that implements `System.Collections.Generic.IEnumerable(Of T)`, and any type at all:\n\n```vb\nImports System.Runtime.CompilerServices\n\nModule Extensions\n    <Extension> _\n    Sub PrintArray(a() As Integer)\n        ...\n    End Sub\n\n    <Extension> _\n    Sub PrintList(Of T)(a As IEnumerable(Of T))\n        ...\n    End Sub\n\n    <Extension> _\n    Sub Print(Of T)(a As T)\n        ...\n    End Sub\nEnd Module\n```\n\nAs the previous example shows, interfaces can be extended. Interface extension methods supply the implementation of the method, so types that implement an interface that has extension methods defined on it still only implement the members originally declared by the interface. For example:\n\n```vb\nImports System.Runtime.CompilerServices\n\nInterface IAction\n  Sub DoAction()\nEnd Interface\n\nModule IActionExtensions \n    <Extension> _\n    Public Sub DoAnotherAction(i As IAction) \n        i.DoAction()\n    End Sub\nEnd Module\n\nClass C\n  Implements IAction\n\n  Sub DoAction() Implements IAction.DoAction\n    ...\n  End Sub\n\n  ' ERROR: Cannot implement extension method IAction.DoAnotherAction\n  Sub DoAnotherAction() Implements IAction.DoAnotherAction\n    ...\n  End Sub\nEnd Class\n```\n\nExtension methods can also have type constraints on their type parameters and, just as with non-extension generic methods, type argument can be inferred:\n\n```vb\nImports System.Runtime.CompilerServices\n\nModule IEnumerableComparableExtensions\n    <Extension> _\n    Public Function Sort(Of T As IComparable(Of T))(i As IEnumerable(Of T)) _\n        As IEnumerable(Of T)\n        ...\n    End Function\nEnd Module\n```\n\nExtension methods can also be accessed through implicit instance expressions within the type being extended:\n\n```vb\nImports System.Runtime.CompilerServices\n\nClass C1\n    Sub M1()\n        Me.M2()\n        M2()\n    End Sub\nEnd Class\n\nModule C1Extensions\n    <Extension>\n    Sub M2(c As C1)\n        ...\n    End Sub\nEnd Module\n```\n\nFor the purposes of accessibility, extension methods are also treated as members of the standard module they are declared in -- they have no extra access to the members of the type they are extending beyond the access they have by virtue of their declaration context.\n\nExtensions methods are only available when the standard module method is in scope. Otherwise, the original type will not appear to have been extended. For example:\n\n```vb\nImports System.Runtime.CompilerServices\n\nClass C1\nEnd Class\n\nNamespace N1\n    Module C1Extensions\n        <Extension> _\n        Sub M1(c As C1)\n            ...\n        End Sub\n    End Module\nEnd Namespace\n\nModule Test\n    Sub Main()\n        Dim c As New C1()\n\n        ' Error: c has no member named \"M1\"\n        c.M1()\n    End Sub\nEnd Module\n```\n\nReferring to a type when only an extension method on the type is available will still produce a compile-time error.\n\nIt is important to note that extension methods are considered to be members of the type in all contexts where members are bound, such as the strongly-typed `For Each` pattern. For example:\n\n```vb\nImports System.Runtime.CompilerServices\n\nClass C1\nEnd Class\n\nClass C1Enumerator\n    ReadOnly Property Current() As C1\n        Get\n            ...\n        End Get\n    End Property\n\n    Function MoveNext() As Boolean\n        ...\n    End Function\nEnd Class\n\nModule C1Extensions\n    <Extension> _\n    Function GetEnumerator(c As C1) As C1Enumerator\n        ...\n    End Function\nEnd Module\n\nModule Test\n    Sub Main()\n        Dim c As New C1()\n\n        ' Valid\n        For Each o As Object In c\n            ...\n        Next o\n    End Sub\nEnd Module\n```\n\nDelegates can also be created that refer to extension methods. Thus, the code:\n\n```vb\nDelegate Sub D1()\n\nModule Test\n    Sub Main()\n        Dim s As String = \"Hello, World!\"\n        Dim d As D1\n\n        d = AddressOf s.Print\n        d()\n    End Sub\nEnd Module\n```\n\nis roughly equivalent to:\n\n```vb\nDelegate Sub D1()\n\nModule Test\n    Sub Main()\n      Dim s As String = \"Hello, World!\"\n      Dim d As D1\n\n      d = CType([Delegate].CreateDelegate(GetType(D1), s, _\n                GetType(StringExtensions).GetMethod(\"Print\")), D1)\n      d()\n    End Sub\nEnd Module\n```\n\n__Note.__ Visual Basic normally inserts a check on an instance method call that causes a `System.NullReferenceException` to occur if the instance the method is being invoked on is `Nothing`. In the case of extension methods, there is no efficient way to insert this check, so extension methods will need to explicitly check for `Nothing`. \n\n__Note.__ A value type will be boxed when being passed as a `ByVal` argument to a parameter typed as an interface.  This implies that side effects of the extension method will operate on a copy of the structure instead of the original. While the language puts no restrictions on the first argument of an extension method, it is recommended that extension methods are not used to extend value types or that when extending value types, the first parameter is passed `ByRef` to ensure that side effects operate on the original value.\n\n### Partial Methods\n\nA *partial method* is a method that specifies a signature but not the body of the method. The body of the method can be supplied by another method declaration with the same name and signature, most likely in another partial declaration of the type. For example:\n\na.vb:\n\n```vb\n' Designer generated code\nPublic Partial Class MyForm\n    Private Partial Sub ValidateControls()\n    End Sub\n\n    Public Sub New()\n        ' Initialize controls\n        ...\n\n        ValidateControls()\n    End Sub    \nEnd Class\n```\n\nb.vb:\n\n```vb\nPublic Partial Class MyForm\n    Public Sub ValidateControls()\n        ' Validation logic goes here\n        ...\n    End Sub\nEnd Class\n```\n\nIn this example, a partial declaration of the class `MyForm` declares a partial method `ValidateControls` with no implementation. The constructor in the partial declaration calls the partial method, even though there is no body supplied in the file. The other partial declaration of `MyForm` then supplies the implementation of the method.\n\nPartial methods can be called regardless of whether a body has been supplied; if no method body is supplied, the call is ignored. For example:\n\n```vb\nPublic Class C1\n    Private Partial Sub M1()\n    End Sub\n\n    Public Sub New()\n        ' Since no implementation is supplied, this call will not be made.\n        M1()\n    End Sub\nEnd Class\n```\n\nAny expressions that are passed in as arguments to a partial method call that is ignored are ignored also and not evaluated. (__Note.__ This means that partial methods are a very efficient way of providing behavior that is defined across two partial types, since the partial methods have no cost if they are not used.)\n\nThe partial method declaration must be declared as `Private` and must always be a subroutine with no statements in its body. Partial methods cannot themselves implement interface methods, although the method that supplies their body can.\n\nOnly one method can supply a body to a partial method. A method supplying a body to a partial method must have the same signature as the partial method, the same constraints on any type parameters, the same declaration modifiers, and the same parameter and type parameter names. Attributes on the partial method and the method that supplies its body are merged, as are any attributes on the methods' parameters. Similarly, the list of events that the methods handle is merged. For example:\n\n```vb\nClass C1\n    Event E1()\n    Event E2()\n\n    Private Partial Sub S() Handles Me.E1\n    End Sub\n\n    ' Handles both E1 and E2\n    Private Sub S() Handles Me.E2\n        ...\n    End Sub\nEnd Class\n```\n\n## Constructors\n\n*Constructors* are special methods that allow control over initialization. They are run after the program begins or when an instance of a type is created. Unlike other members, constructors are not inherited and do not introduce a name into a type's declaration space. Constructors may only be invoked by object-creation expressions or by the .NET Framework; they may never be directly invoked.\n\n__Note.__ Constructors have the same restriction on line placement that subroutines have. The beginning statement, end statement and block must all appear at the beginning of a logical line.\n\n```antlr\nConstructorMemberDeclaration\n    : Attributes? ConstructorModifier* 'Sub' 'New'\n      ( OpenParenthesis ParameterList? CloseParenthesis )? LineTerminator\n      Block?\n      'End' 'Sub' StatementTerminator\n    ;\n\nConstructorModifier\n    : AccessModifier\n    | 'Shared'\n    ;\n```\n\n### Instance Constructors\n\n*Instance constructors* initialize instances of a type and are run by the .NET Framework when an instance is created. The parameter list of a constructor is subject to the same rules as the parameter list of a method. Instance constructors may be overloaded.\n\nAll constructors in reference types must invoke another constructor. If the invocation is explicit, it must be the first statement in the constructor method body. The statement can either invoke another of the type's instance constructors -- for example, `Me.New(...)` or `MyClass.New(...)` -- or if it is not a structure it can invoke an instance constructor of the type's base type -- for example, `MyBase.New(...)`. It is invalid for a constructor to invoke itself. If a constructor omits a call to another constructor, `MyBase.New()` is implicit. If there is no parameterless base type constructor, a compile-time error occurs. Because `Me` is not considered to be constructed until after the call to a base class constructor, the parameters to a constructor invocation statement cannot reference `Me`, `MyClass`, or `MyBase` implicitly or explicitly.\n\nWhen a constructor's first statement is of the form `MyBase.New(...)`, the constructor implicitly performs the initializations specified by the variable initializers of the instance variables declared in the type. This corresponds to a sequence of assignments that are executed immediately after invoking the direct base type constructor. Such ordering ensures that all base instance variables are initialized by their variable initializers before any statements that have access to the instance are executed. For example:\n\n```vb\nClass A\n    Protected x As Integer = 1\nEnd Class\n\nClass B\n    Inherits A\n\n    Private y As Integer = x\n\n    Public Sub New()\n        Console.WriteLine(\"x = \" & x & \", y = \" & y)\n    End Sub\nEnd Class\n```\n\nWhen `New B()` is used to create an instance of `B`, the following output is produced:\n\n```console\nx = 1, y = 1\n```\n\nThe value of `y` is `1` because the variable initializer is executed after the base class constructor is invoked. Variable initializers are executed in the textual order they appear in the type declaration.\n\nWhen a type declares only `Private` constructors, it is not possible in general for other types to derive from the type or create instances of the type; the only exception is types nested within the type. `Private` constructors are commonly used in types that contain only `Shared` members.\n\nIf a type contains no instance constructor declarations, a default constructor is automatically provided. The default constructor simply invokes the parameterless constructor of the direct base type. If the direct base type does not have an accessible parameterless constructor, a compile-time error occurs. The declared access type for the default constructor is `Public` unless the type is `MustInherit`, in which case the default constructor is `Protected`.\n\n__Note.__ The default access for a `MustInherit` type's default constructor is `Protected` because `MustInherit` classes cannot be created directly. So there is no point in making the default constructor `Public`.\n\nIn the following example a default constructor is provided because the class contains no constructor declarations:\n\n```vb\nClass Message\n    Dim sender As Object\n    Dim text As String\nEnd Class\n```\n\nThus, the example is precisely equivalent to the following:\n\n```vb\nClass Message\n    Dim sender As Object\n    Dim text As String\n\n    Sub New()\n    End Sub\nEnd Class\n```\n\nDefault constructors that are emitted into a designer generated class marked with the attribute `Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute` will call the method `Sub InitializeComponent()`, if it exists, after the call to the base constructor. (__Note.__ This allows designer generated files, such as those created by the WinForms designer, to omit the constructor in the designer file. This enables the programmer to specify it themselves, if they so choose.)\n\n### Shared Constructors\n\n*Shared constructors* initialize a type's shared variables; they are run after the program begins executing, but before any references to a member of the type. A shared constructor specifies the `Shared` modifier, unless it is in a standard module in which case the `Shared` modifier is implied.\n\nUnlike instance constructors, shared constructors have implicit public access, have no parameters, and may not call other constructors. Before the first statement in a shared constructor, the shared constructor implicitly performs the initializations specified by the variable initializers of the shared variables declared in the type. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor. The variable initializers are executed in the textual order they appear in the type declaration.\n\nThe following example shows an `Employee` class with a shared constructor that initializes a shared variable:\n\n```vb\nImports System.Data\n\nClass Employee\n    Private Shared ds As DataSet\n\n    Shared Sub New()\n        ds = New DataSet()\n    End Sub\n\n    Public Name As String\n    Public Salary As Decimal\nEnd Class\n```\n\nA separate shared constructor exists for each closed generic type. Because the shared constructor is executed exactly once for each closed type, it is a convenient place to enforce run-time checks on the type parameter that cannot be checked at compile-time via constraints. For example, the following type uses a shared constructor to enforce that the type parameter is `Integer` or `Double`:\n\n```vb\nClass EnumHolder(Of T)\n    Shared Sub New() \n        If Not GetType(T).IsEnum() Then\n            Throw New ArgumentException(\"T must be an enumerated type.\")\n        End If\n    End Sub\nEnd Class\n```\n\nExactly when shared constructors are run is mostly implementation dependent, though several guarantees are provided if a shared constructor is explicitly defined:\n\n* Shared constructors are run before the first access to any static field of the type.\n\n* Shared constructors are run before the first invocation of any static method of the type.\n\n* Shared constructors are run before the first invocation of any constructor for the type.\n\nThe above guarantees do not apply in the situation where a shared constructor is implicitly created for shared initializers. The output from the following example is uncertain, because the exact ordering of loading and therefore of shared constructor execution is not defined:\n\n```vb\nModule Test\n    Sub Main()\n        A.F()\n        B.F()\n    End Sub\nEnd Module\n\nClass A\n    Shared Sub New()\n        Console.WriteLine(\"Init A\")\n    End Sub\n\n    Public Shared Sub F()\n        Console.WriteLine(\"A.F\")\n    End Sub\nEnd Class\n\nClass B\n    Shared Sub New()\n        Console.WriteLine(\"Init B\")\n    End Sub\n\n    Public Shared Sub F()\n        Console.WriteLine(\"B.F\")\n    End Sub\nEnd Class\n```\n\nThe output could be either of the following:\n\n```console\nInit A\nA.F\nInit B\nB.F\n```\n\nor\n\n```console\nInit B\nInit A\nA.F\nB.F\n```\n\nBy contrast, the following example produces predictable output. Note that the `Shared` constructor for the class `A` never executes, even though class `B` derives from it:\n\n```vb\nModule Test\n    Sub Main()\n        B.G()\n    End Sub\nEnd Module\n\nClass A\n    Shared Sub New()\n        Console.WriteLine(\"Init A\")\n    End Sub\nEnd Class\n\nClass B\n    Inherits A\n\n    Shared Sub New()\n        Console.WriteLine(\"Init B\")\n    End Sub\n\n    Public Shared Sub G()\n        Console.WriteLine(\"B.G\")\n    End Sub\nEnd Class\n```\n\nThe output is:\n\n```console\nInit B\nB.G\n```\n\nIt is also possible to construct circular dependencies that allow `Shared` variables with variable initializers to be observed in their default value state, as in the following example:\n\n```vb\nClass A\n    Public Shared X As Integer = B.Y + 1\nEnd Class\n\nClass B\n    Public Shared Y As Integer = A.X + 1\n\n    Shared Sub Main()\n        Console.WriteLine(\"X = \" & A.X & \", Y = \" & B.Y)\n    End Sub\nEnd Class\n```\n\nThis produces the output:\n\n```console\nX = 1, Y = 2\n```\n\nTo execute the `Main` method, the system first loads class `B`. The `Shared` constructor of class `B` proceeds to compute the initial value of `Y`, which recursively causes class `A` to be loaded because the value of `A.X` is referenced. The `Shared` constructor of class `A` in turn proceeds to compute the initial value of `X`, and in doing so fetches the *default* value of `Y`, which is zero. `A.X` is thus initialized to `1`. The process of loading `A` then completes, returning to the calculation of the initial value of `Y`, the result of which becomes `2`.\n\nHad the `Main` method instead been located in class `A`, the example would have produced the following output:\n\n```console\nX = 2, Y = 1\n```\n\nAvoid circular references in `Shared` variable initializers since it is generally impossible to determine the order in which classes containing such references are loaded.\n\n## Events\n\nEvents are used to notify code of a particular occurrence. An event declaration consists of an identifier, either a delegate type or a parameter list, and an optional `Implements` clause.\n\n```antlr\nEventMemberDeclaration\n    : RegularEventMemberDeclaration\n    | CustomEventMemberDeclaration\n    ;\n\nRegularEventMemberDeclaration\n    : Attributes? EventModifiers* 'Event'\n      Identifier ParametersOrType ImplementsClause? StatementTerminator\n    ;\n\nInterfaceEventMemberDeclaration\n    : Attributes? InterfaceEventModifiers* 'Event'\n      Identifier ParametersOrType StatementTerminator\n    ;\n\nParametersOrType\n    : ( OpenParenthesis ParameterList? CloseParenthesis )?\n    | 'As' NonArrayTypeName\n    ;\n\nEventModifiers\n    : AccessModifier\n    | 'Shadows'\n    | 'Shared'\n    ;\n\nInterfaceEventModifiers\n    : 'Shadows'\n    ;\n```\n\nIf a delegate type is specified, the delegate type may not have a return type. If a parameter list is specified, it may not contain `Optional` or `ParamArray` parameters. The accessibility domain of the parameter types and/or delegate type must be the same as, or a superset of, the accessibility domain of the event itself. Events may be shared by specifying the `Shared` modifier.\n\nIn addition to the member name added to the type's declaration space, an event declaration implicitly declares several other members. Given an event named `X`, the following members are added to the declaration space:\n\n* If the form of the declaration is a method declaration, a nested delegate class named `XEventHandler` is introduced. The nested delegate class matches the method declaration and has the same accessibility as the event. The attributes in the parameter list apply to the parameters of the delegate class.\n\n* A `Private` instance variable typed as the delegate, named `XEvent`.\n\n* Two methods named `add_X` and `remove_X` which cannot be invoked, overridden or overloaded.\n\nIf a type attempts to declare a name that matches one of the above names, a compile-time error will result, and the implicit `add_X` and `remove_X` declarations are ignored for the purposes of name binding. It is not possible to override or overload any of the introduced members, although it is possible to shadow them in derived types. For example, the class declaration\n\n```vb\nClass Raiser\n    Public Event Constructed(i As Integer)\nEnd Class\n```\n\nis equivalent to the following declaration\n\n```vb\nClass Raiser\n    Public Delegate Sub ConstructedEventHandler(i As Integer)\n\n    Protected ConstructedEvent As ConstructedEventHandler\n\n    Public Sub add_Constructed(d As ConstructedEventHandler)\n        ConstructedEvent = _\n            CType( _\n                [Delegate].Combine(ConstructedEvent, d), _\n                    Raiser.ConstructedEventHandler)\n    End Sub\n\n    Public Sub remove_Constructed(d As ConstructedEventHandler)\n        ConstructedEvent = _\n            CType( _\n                [Delegate].Remove(ConstructedEvent, d), _\n                    Raiser.ConstructedEventHandler)\n    End Sub\nEnd Class\n```\n\nDeclaring an event without specifying a delegate type is the simplest and most compact syntax, but has the disadvantage of declaring a new delegate type for each event. For example, in the following example, three hidden delegate types are created, even though all three events have the same parameter list:\n\n```vb\nPublic Class Button\n    Public Event Click(sender As Object, e As EventArgs)\n    Public Event DoubleClick(sender As Object, e As EventArgs)\n    Public Event RightClick(sender As Object, e As EventArgs)\nEnd Class\n```\n\nIn the following example, the events simply use the same delegate, `EventHandler`:\n\n```vb\nPublic Delegate Sub EventHandler(sender As Object, e As EventArgs)\n\nPublic Class Button\n    Public Event Click As EventHandler\n    Public Event DoubleClick As EventHandler\n    Public Event RightClick As EventHandler\nEnd Class\n```\n\nEvents can be handled in one of two ways: statically or dynamically. Statically handling events is simpler and only requires a `WithEvents` variable and a `Handles` clause. In the following example, class `Form1` statically handles the event `Click` of object `Button`:\n\n```vb\nPublic Class Form1\n    Public WithEvents Button1 As New Button()\n\n    Public Sub Button1_Click(sender As Object, e As EventArgs) _\n           Handles Button1.Click\n        Console.WriteLine(\"Button1 was clicked!\")\n    End Sub\nEnd Class\n```\n\nDynamically handling events is more complex because the event must be explicitly connected and disconnected to in code. The statement `AddHandler` adds a handler for an event, and the statement `RemoveHandler` removes a handler for an event. The next example shows a class `Form1` that adds `Button1_Click` as an event handler for `Button1`'s `Click` event:\n\n```vb\nPublic Class Form1\n    Public Sub New()\n        ' Add Button1_Click as an event handler for Button1's Click event.\n        AddHandler Button1.Click, AddressOf Button1_Click\n    End Sub \n\n    Private Button1 As Button = New Button()\n\n    Sub Button1_Click(sender As Object, e As EventArgs)\n        Console.WriteLine(\"Button1 was clicked!\")\n    End Sub\n\n    Public Sub Disconnect()\n        RemoveHandler Button1.Click, AddressOf Button1_Click\n    End Sub \nEnd Class\n```\n\nIn method `Disconnect`, the event handler is removed.\n\n\n### Custom Events\n\nAs discussed in the previous section, event declarations implicitly define a field, an `add_` method, and a `remove_` method that are used to keep track of event handlers. In some situations, however, it may be desirable to provide custom code for tracking event handlers. For example, if a class defines forty events of which only a few will ever be handled, using a hash table instead of forty fields to track the handlers for each event may be more efficient. *Custom events* allow the `add_X` and `remove_X` methods to be defined explicitly, which enables custom storage for event handlers.\n\nCustom events are declared in the same way that events that specify a delegate type are declared, with the exception that the keyword `Custom` must precede the `Event` keyword. A custom event declaration contains three declarations: an `AddHandler` declaration, a `RemoveHandler` declaration and a `RaiseEvent` declaration. None of the declarations can have any modifiers, although they can have attributes.\n\n```antlr\nCustomEventMemberDeclaration\n    : Attributes? EventModifiers* 'Custom' 'Event'\n      Identifier 'As' TypeName ImplementsClause? StatementTerminator\n      EventAccessorDeclaration+\n      'End' 'Event' StatementTerminator\n    ;\n\nEventAccessorDeclaration\n    : AddHandlerDeclaration\n    | RemoveHandlerDeclaration\n    | RaiseEventDeclaration\n    ;\n\nAddHandlerDeclaration\n    : Attributes? 'AddHandler'\n      OpenParenthesis ParameterList CloseParenthesis LineTerminator\n      Block?\n      'End' 'AddHandler' StatementTerminator\n    ;\n\nRemoveHandlerDeclaration\n    : Attributes? 'RemoveHandler'\n      OpenParenthesis ParameterList CloseParenthesis LineTerminator\n      Block?\n      'End' 'RemoveHandler' StatementTerminator\n    ;\n\nRaiseEventDeclaration\n    : Attributes? 'RaiseEvent'\n      OpenParenthesis ParameterList CloseParenthesis LineTerminator\n      Block?\n      'End' 'RaiseEvent' StatementTerminator\n    ;\n```\n\nFor example:\n\n```vb\nClass Test\n    Private Handlers As EventHandler\n\n    Public Custom Event TestEvent As EventHandler\n        AddHandler(value As EventHandler)\n            Handlers = CType([Delegate].Combine(Handlers, value), _\n                EventHandler)\n        End AddHandler\n\n        RemoveHandler(value as EventHandler)\n            Handlers = CType([Delegate].Remove(Handlers, value), _\n                EventHandler)\n        End RemoveHandler\n\n        RaiseEvent(sender As Object, e As EventArgs)\n            Dim TempHandlers As EventHandler = Handlers\n\n            If TempHandlers IsNot Nothing Then\n                TempHandlers(sender, e)\n            End If\n        End RaiseEvent\n    End Event\nEnd Class\n```\n\nThe `AddHandler` and `RemoveHandler` declaration take one `ByVal` parameter, which must be of the delegate type of the event. When an `AddHandler` or `RemoveHandler` statement is executed (or a `Handles` clause automatically handles an event), the corresponding declaration will be called. The `RaiseEvent` declaration takes the same parameters as the event delegate and will be called when a `RaiseEvent` statement is executed. All of the declarations must be provided and are considered to be subroutines.\n\nNote that `AddHandler`, `RemoveHandler` and `RaiseEvent` declarations have the same restriction on line placement that subroutines have. The beginning statement, end statement and block must all appear at the beginning of a logical line.\n\nIn addition to the member name added to the type's declaration space, a custom event declaration implicitly declares several other members. Given an event named `X`, the following members are added to the declaration space:\n\n* A method named `add_X`, corresponding to the `AddHandler` declaration.\n\n* A method named `remove_X`, corresponding to the `RemoveHandler` declaration.\n\n* A method named `fire_X`, corresponding to the `RaiseEvent` declaration.\n\nIf a type attempts to declare a name that matches one of the above names, a compile-time error will result, and the implicit declarations are all ignored for the purposes of name binding. It is not possible to override or overload any of the introduced members, although it is possible to shadow them in derived types.\n\n__Note.__ `Custom` is not a reserved word.\n\n#### Custom events in WinRT assemblies\n\nAs of Microsoft Visual Basic 11.0, events declared in a file compiled with `/target:winmdobj`, or declared in an interface in such a file and then implemented elsewhere, are treated a little differently.\n\n* External tools used to build the winmd will typically allow only certain delegate types such as `System.EventHandler(Of T)` or `System.TypedEventHandle(Of T, U)`, and will disallow others.\n\n* The `XEvent` field has type `System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of T)` where `T` is the delegate type.\n\n* The AddHandler accessor returns a `System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken`, and the RemoveHandler accessor takes a single parameter of the same type.\n\nHere is an example of such a custom event.\n\n```vb\nImports System.Runtime.InteropServices.WindowsRuntime\n\nPublic NotInheritable Class ClassInWinMD\n    Private XEvent As EventRegistrationTokenTable(Of EventHandler(Of Integer))\n\n    Public Custom Event X As EventHandler(Of Integer)\n        AddHandler(handler As EventHandler(Of Integer))\n            Return EventRegistrationTokenTable(Of EventHandler(Of Integer)).\n                   GetOrCreateEventRegistrationTokenTable(XEvent).\n                   AddEventHandler(handler)\n        End AddHandler\n\n        RemoveHandler(token As EventRegistrationToken)\n            EventRegistrationTokenTable(Of EventHandler(Of Integer)).\n                GetOrCreateEventRegistrationTokenTable(XEvent).\n                RemoveEventHandler(token)\n        End RemoveHandler\n\n        RaiseEvent(sender As Object, i As Integer)\n            Dim table = EventRegistrationTokenTable(Of EventHandler(Of Integer)).\n                GetOrCreateEventRegistrationTokenTable(XEvent).\n                InvocationList\n            If table IsNot Nothing Then table(sender, i)\n        End RaiseEvent\n    End Event\nEnd Class\n```\n\n\n## Constants\n\nA *constant* is a constant value that is a member of a type.\n\n```antlr\nConstantMemberDeclaration\n    : Attributes? ConstantModifier* 'Const' ConstantDeclarators StatementTerminator\n    ;\n\nConstantModifier\n    : AccessModifier\n    | 'Shadows'\n    ;\n\nConstantDeclarators\n    : ConstantDeclarator ( Comma ConstantDeclarator )*\n    ;\n\nConstantDeclarator\n    : Identifier ( 'As' TypeName )? Equals ConstantExpression StatementTerminator\n    ;\n```\n\nConstants are implicitly shared. If the declaration contains an `As` clause, the clause specifies the type of the member introduced by the declaration. If the type is omitted then the type of the constant is inferred. The type of a constant may only be a primitive type or `Object`. If a constant is typed as `Object` and there is no type character, the real type of the constant will be the type of the constant expression. Otherwise, the type of the constant is the type of the constant's type character.\n\nThe following example shows a class named `Constants` that has two public constants:\n\n```vb\nClass Constants\n    Public Const A As Integer = 1\n    Public Const B As Integer = A + 1\nEnd Class\n```\n\nConstants can be accessed through the class, as in the following example, which prints out the values of `Constants.A` and `Constants.B`.\n\n```vb\nModule Test\n    Sub Main()\n        Console.WriteLine(Constants.A & \", \" & Constants.B)\n    End Sub \nEnd Module\n```\n\nA constant declaration that declares multiple constants is equivalent to multiple declarations of single constants. The following example declares three constants in one declaration statement.\n\n```vb\nClass A\n    Protected Const x As Integer = 1, y As Long = 2, z As Short = 3\nEnd Class\n```\n\nThis declaration is equivalent to the following:\n\n```vb\nClass A\n    Protected Const x As Integer = 1\n    Protected Const y As Long = 2\n    Protected Const z As Short = 3\nEnd Class\n```\n\nThe accessibility domain of the type of the constant must be the same as or a superset of the accessibility domain of the constant itself. The constant expression must yield a value of the constant's type or of a type that is implicitly convertible to the constant's type. The constant expression may not be circular; that is, a constant may not be defined in terms of itself.\n\nThe compiler automatically evaluates the constant declarations in the appropriate order. In the following example, the compiler first evaluates `Y`, then `Z`, and finally `X`, producing the values 10, 11, and 12, respectively.\n\n```vb\nClass A\n    Public Const X As Integer = B.Z + 1\n    Public Const Y As Integer = 10\nEnd Class\n\nClass B\n    Public Const Z As Integer = A.Y + 1\nEnd Class\n```\n\nWhen a symbolic name for a constant value is desired, but the type of the value is not permitted in a constant declaration or when the value cannot be computed at compile time by a constant expression, a read-only variable may be used instead.\n\n\n## Instance and Shared Variables\n\nAn instance or shared variable is a member of a type that can store information.\n\n```antlr\nVariableMemberDeclaration\n    : Attributes? VariableModifier+ VariableDeclarators StatementTerminator\n    ;\n\nVariableModifier\n    : AccessModifier\n    | 'Shadows'\n    | 'Shared'\n    | 'ReadOnly'\n    | 'WithEvents'\n    | 'Dim'\n    ;\n\nVariableDeclarators\n    : VariableDeclarator ( Comma VariableDeclarator )*\n    ;\n\nVariableDeclarator\n    : VariableIdentifiers 'As' ObjectCreationExpression\n    | VariableIdentifiers ( 'As' TypeName )? ( Equals Expression )?\n    ;\n\nVariableIdentifiers\n    : VariableIdentifier ( Comma VariableIdentifier )*\n    ;\n\nVariableIdentifier\n    : Identifier IdentifierModifiers\n    ;\n```\n\nThe `Dim` modifier must be specified if no modifiers are specified, but may be omitted otherwise. A single variable declaration may include multiple variable declarators; each variable declarator introduces a new instance or shared member.\n\nIf an initializer is specified, only one instance or shared variable may be declared by the variable declarator:\n\n```vb\nClass Test\n    Dim a, b, c, d As Integer = 10  ' Invalid: multiple initialization\nEnd Class\n```\n\nThis restriction does not apply to object initializers:\n\n```vb\nClass Test\n    Dim a, b, c, d As New Collection() ' OK\nEnd Class\n```\n\nA variable declared with the `Shared` modifier is a *shared variable*. A shared variable identifies exactly one storage location regardless of the number of instances of the type that are created. A shared variable comes into existence when a program begins executing, and ceases to exist when the program terminates.\n\nA shared variable is shared only among instances of a particular closed generic type. For example, the program:\n\n```vb\nClass C(Of V) \n    Shared InstanceCount As Integer = 0\n\n    Public Sub New()  \n        InstanceCount += 1 \n    End Sub\n\n    Public Shared ReadOnly Property Count() As Integer \n        Get\n            Return InstanceCount\n        End Get\n    End Property\nEnd Class\n\nClass Application \n    Shared Sub Main() \n        Dim x1 As New C(Of Integer)()\n        Console.WriteLine(C(Of Integer).Count)\n\n        Dim x2 As New C(Of Double)() \n        Console.WriteLine(C(Of Integer).Count)\n\n        Dim x3 As New C(Of Integer)() \n        Console.WriteLine(C(Of Integer).Count)\n    End Sub\nEnd Class\n```\n\nPrints out:\n\n```console\n1\n1\n2\n```\n\nA variable declared without the `Shared` modifier is called an *instance variable*. Every instance of a class contains a separate copy of all instance variables of the class. An instance variable of a reference type comes into existence when a new instance of that type is created, and ceases to exist when there are no references to that instance and the `Finalize` method has executed. An instance variable of a value type has exactly the same lifetime as the variable to which it belongs. In other words, when a variable of a value type comes into existence or ceases to exist, so does the instance variable of the value type.\n\nIf the declarator contains an `As` clause, the clause specifies the type of the members introduced by the declaration. If the type is omitted and strict semantics are being used, a compile-time error occurs. Otherwise the type of the members is implicitly `Object` or the type of the members' type character.\n\n__Note.__ There is no ambiguity in the syntax: if a declarator omits a type, it will always use the type of a following declarator.\n\nThe accessibility domain of an instance or shared variable's type or array element type must be the same as or a superset of the accessibility domain of the instance or shared variable itself.\n\nThe following example shows a `Color` class that has internal instance variables named `redPart`, `greenPart`, and `bluePart`:\n\n```vb\nClass Color\n    Friend redPart As Short\n    Friend bluePart As Short\n    Friend greenPart As Short\n\n    Public Sub New(red As Short, blue As Short, green As Short)\n        redPart = red\n        bluePart = blue\n        greenPart = green\n    End Sub\nEnd Class\n```\n\n\n### Read-Only Variables\n\nWhen an instance or shared variable declaration includes a `ReadOnly` modifier, assignments to the variables introduced by the declaration may only occur as part of the declaration or in a constructor in the same class. Specifically, assignments to a read-only instance or shared variable are permitted only in the following situations:\n\n* In the variable declaration that introduces the instance or shared variable (by including a variable initializer in the declaration).\n\n* For an instance variable, in the instance constructors of the class that contains the variable declaration. The instance variable can only be accessed in an unqualified manner or through `Me` or `MyClass`.\n\n* For a shared variable, in the shared constructor of the class that contains the shared variable declaration.\n\nA shared read-only variable is useful when a symbolic name for a constant value is desired, but when the type of the value is not permitted in a constant declaration, or when the value cannot be computed at compile time by a constant expression.\n\nAn example of the first such application follows, in which color shared variables are declared `ReadOnly` to prevent them from being changed by other programs:\n\n```vb\nClass Color\n    Friend redPart As Short\n    Friend bluePart As Short\n    Friend greenPart As Short\n\n    Public Sub New(red As Short, blue As Short, green As Short)\n        redPart = red\n        bluePart = blue\n        greenPart = green\n    End Sub \n\n    Public Shared ReadOnly Red As Color = New Color(&HFF, 0, 0)\n    Public Shared ReadOnly Blue As Color = New Color(0, &HFF, 0)\n    Public Shared ReadOnly Green As Color = New Color(0, 0, &HFF)\n    Public Shared ReadOnly White As Color = New Color(&HFF, &HFF, &HFF)\nEnd Class\n```\n\nConstants and read-only shared variables have different semantics. When an expression references a constant, the value of the constant is obtained at compile time, but when an expression references a read-only shared variable, the value of the shared variable is not obtained until run time. Consider the following application, which consists of two separate programs.\n\nfile1.vb:\n\n```vb\nNamespace Program1\n    Public Class Utils\n        Public Shared ReadOnly X As Integer = 1\n    End Class\nEnd Namespace\n```\n\nfile2.vb:\n\n```vb\nNamespace Program2\n    Module Test\n        Sub Main()\n            Console.WriteLine(Program1.Utils.X)\n        End Sub\n    End Module\nEnd Namespace\n```\n\nThe namespaces `Program1` and `Program2` denote two programs that are compiled separately. Because variable `Program1.Utils.X` is declared as `Shared ReadOnly`, the value output by the `Console.WriteLine` statement is not known at compile time, but rather is obtained at run time. Thus, if the value of `X` is changed and `Program1` is recompiled, the `Console.WriteLine` statement will output the new value even if `Program2` is not recompiled. However, if `X` had been a constant, the value of `X` would have been obtained at the time `Program2` was compiled, and would have remained unaffected by changes in `Program1` until `Program2` was recompiled.\n\n### WithEvents Variables\n\nA type can declare that it handles some set of events raised by one of its instance or shared variables by declaring the instance or shared variable that raises the events with the `WithEvents` modifier. For example:\n\n```vb\nClass Raiser\n    Public Event E1()\n\n    Public Sub Raise()\n        RaiseEvent E1\n    End Sub\nEnd Class\n\nModule Test\n    Private WithEvents x As Raiser\n\n    Private Sub E1Handler() Handles x.E1\n        Console.WriteLine(\"Raised\")\n    End Sub\n\n    Public Sub Main()\n        x = New Raiser()\n    End Sub\nEnd Module\n```\n\nIn this example, the method `E1Handler` handles the event `E1` that is raised by the instance of the type `Raiser` stored in the instance variable `x`.\n\nThe `WithEvents` modifier causes the variable to be renamed with a leading underscore and replaced with a property of the same name that does the event hookup. For example, if the variable's name is `F`, it is renamed to `_F` and a property `F` is implicitly declared. If there is a collision between the variable's new name and another declaration, a compile-time error will be reported. Any attributes applied to the variable are carried over to the renamed variable.\n\nThe implicit property created by a `WithEvents` declaration takes care of hooking and unhooking the relevant event handlers. When a value is assigned to the variable, the property first calls the `remove` method for the event on the instance currently in the variable (unhooking the existing event handler, if any). Next the assignment is made, and the property calls the `add` method for the event on the new instance in the variable (hooking up the new event handler). The following code is equivalent to the code above for the standard module `Test`:\n\n```vb\nModule Test\n    Private _x As Raiser\n\n    Public Property x() As Raiser\n        Get\n            Return _x\n        End Get\n\n        Set (Value As Raiser)\n            ' Unhook any existing handlers.\n            If _x IsNot Nothing Then\n                RemoveHandler _x.E1, AddressOf E1Handler\n            End If\n\n            ' Change value.\n            _x = Value\n\n            ' Hook-up new handlers.\n            If _x IsNot Nothing Then\n                AddHandler _x.E1, AddressOf E1Handler\n            End If\n        End Set\n    End Property\n\n    Sub E1Handler()\n        Console.WriteLine(\"Raised\")\n    End Sub\n\n    Sub Main()\n        x = New Raiser()\n    End Sub\nEnd Module\n```\n\nIt is not valid to declare an instance or shared variable as `WithEvents` if the variable is typed as a structure. In addition, `WithEvents` may not be specified in a structure, and `WithEvents` and `ReadOnly` cannot be combined.\n\n### Variable Initializers\n\nInstance and shared variable declarations in classes and instance variable declarations (but not shared variable declarations) in structures may include variable initializers. For `Shared` variables, variable initializers correspond to assignment statements that are executed after the program begins, but before the `Shared` variable is first referenced. For instance variables, variable initializers correspond to assignment statements that are executed when an instance of the class is created. Structures cannot have instance variable initializers because their parameterless constructors cannot be modified.\n\nConsider the following example:\n\n```vb\nClass Test\n    Public Shared x As Double = Math.Sqrt(2.0)\n    Public i As Integer = 100\n    Public s As String = \"Hello\"\nEnd Class\n\nModule TestModule\n    Sub Main()\n        Dim a As New Test()\n\n        Console.WriteLine(\"x = \" & Test.x & \", i = \" & a.i & \", s = \" & a.s)\n    End Sub\nEnd Module\n```\n\nThe example produces the following output:\n\n```console\nx = 1.4142135623731, i = 100, s = Hello\n```\n\nAn assignment to `x` occurs when the class is loaded, and assignments to `i` and `s` occur when a new instance of the class is created.\n\nIt is useful to think of variable initializers as assignment statements that are automatically inserted in the block of the type's constructor. The following example contains several instance variable initializers.\n\n```vb\nClass A\n    Private x As Integer = 1\n    Private y As Integer = -1\n    Private count As Integer\n\n    Public Sub New()\n        count = 0\n    End Sub\n\n    Public Sub New(n As Integer)\n        count = n\n    End Sub\nEnd Class\n\nClass B\n    Inherits A\n\n    Private sqrt2 As Double = Math.Sqrt(2.0)\n    Private items As ArrayList = New ArrayList(100)\n    Private max As Integer\n\n    Public Sub New()\n        Me.New(100)\n        items.Add(\"default\")\n    End Sub\n\n    Public Sub New(n As Integer)\n        MyBase.New(n - 1)\n        max = n\n    End Sub\nEnd Class\n```\n\nThe example corresponds to the code shown below, where each comment indicates an automatically inserted statement.\n\n```vb\nClass A\n    Private x, y, count As Integer\n\n    Public Sub New()\n        MyBase.New ' Invoke object() constructor.\n        x = 1 ' This is a variable initializer.\n        y = -1 ' This is a variable initializer.\n        count = 0\n    End Sub\n\n    Public Sub New(n As Integer)\n        MyBase.New ' Invoke object() constructor. \n        x = 1 ' This is a variable initializer.\n        y = - 1 ' This is a variable initializer.\n        count = n\n    End Sub\nEnd Class\n\nClass B\n    Inherits A\n\n    Private sqrt2 As Double\n    Private items As ArrayList\n    Private max As Integer\n\n    Public Sub New()\n        Me.New(100) \n        items.Add(\"default\")\n    End Sub\n\n    Public Sub New(n As Integer)\n        MyBase.New(n - 1) \n        sqrt2 = Math.Sqrt(2.0) ' This is a variable initializer.\n        items = New ArrayList(100) ' This is a variable initializer.\n        max = n\n    End Sub\nEnd Class\n```\n\nAll variables are initialized to the default value of their type before any variable initializers are executed. For example:\n\n```vb\nClass Test\n    Public Shared b As Boolean\n    Public i As Integer\nEnd Class\n\nModule TestModule\n    Sub Main()\n        Dim t As New Test()\n        Console.WriteLine(\"b = \" & Test.b & \", i = \" & t.i)\n    End Sub\nEnd Module\n```\n\nBecause `b` is automatically initialized to its default value when the class is loaded and `i` is automatically initialized to its default value when an instance of the class is created, the preceding code produces the following output:\n\n```console\nb = False, i = 0\n```\n\nEach variable initializer must yield a value of the variable's type or of a type that is implicitly convertible to the variable's type. A variable initializer may be circular or refer to a variable that will be initialized after it, in which case the value of the referenced variable is its default value for the purposes of the initializer. Such an initializer is of dubious value.\n\nThere are three forms of variable initializers: regular initializers, array-size initializers, and object initializers. The first two forms appear after an equal sign that follows the type name, the latter two are part of the declaration itself. Only one form of initializer may be used on any particular declaration.\n\n#### Regular Initializers\n\nA *regular initializer* is an expression that is implicitly convertible to the type of the variable. It appears after an equal sign that follows the type name and must be classified as a value. For example:\n\n```vb\nModule Test\n    Dim x As Integer = 10\n    Dim y As Integer = 20\n\n    Sub Main()\n        Console.WriteLine(\"x = \" & x & \", y = \" & y)\n    End Sub\nEnd Module\n```\n\nThis program produces the output:\n\n```console\nx = 10, y = 20\n```\n\nIf a variable declaration has a regular initializer, then only a single variable can be declared at a time. For example:\n\n```vb\nModule Test\n    Sub Main()\n        ' OK, only one variable declared at a time.\n        Dim x As Integer = 10, y As Integer = 20\n\n        ' Error: Can't initialize multiple variables at once.\n        Dim a, b As Integer = 10\n    End Sub\nEnd Module\n```\n\n#### Object Initializers\n\nAn *object initializer* is specified using an object creation expression in the place of the type name. An object initializer is equivalent to a regular initializer assigning the result of the object creation expression to the variable. So\n\n```vb\nModule TestModule\n    Sub Main()\n        Dim x As New Test(10)\n    End Sub\nEnd Module\n```\n\nis equivalent to\n\n```vb\nModule TestModule\n    Sub Main()\n        Dim x As Test = New Test(10)\n    End Sub\nEnd Module\n```\n\nThe parenthesis in an object initializer is always interpreted as the argument list for the constructor and never as array type modifiers. A variable name with an object initializer cannot have an array type modifier or a nullable type modifier.\n\n#### Array-Size Initializers\n\nAn *array-size initializer* is a modifier on the name of the variable that gives a set of dimension upper bounds denoted by expressions.\n\n```antlr\nArraySizeInitializationModifier\n    : OpenParenthesis BoundList CloseParenthesis ArrayTypeModifiers?\n    ;\n\nBoundList\n    : Bound ( Comma Bound )*\n    ;\n\nBound\n    : Expression\n    | '0' 'To' Expression\n    ;\n```\n\nThe upper bound expressions must be classified as values and must be implicitly convertible to `Integer`. The set of upper bounds is equivalent to a variable initializer of an array-creation expression with the given upper bounds. The number of dimensions of the array type is inferred from the array size initializer. So\n\n```vb\nModule Test\n    Sub Main()\n        Dim x(5, 10) As Integer\n    End Sub\nEnd Module\n```\n\nis equivalent to\n\n```vb\nModule Test\n    Sub Main()\n        Dim x As Integer(,) = New Integer(5, 10) {}\n    End Sub\nEnd Module\n```\n\nAll upper bounds must be equal to or greater than -1, and all dimensions must have an upper bound specified. If the element type of the array being initialized is itself an array type, the array-type modifiers go to the right of the array-size initializer. For example\n\n```vb\nModule Test\n    Sub Main()\n        Dim x(5,10)(,,) As Integer\n    End Sub\nEnd Module\n```\n\ndeclares a local variable `x` whose type is a two-dimensional array of three-dimensional arrays of `Integer`, initialized to an array with bounds of `0..5` in the first dimension and `0..10` in the second dimension. It is not possible to use an array size initializer to initialize the elements of a variable whose type is an array of arrays.\n\nA variable declaration with an array-size initializer cannot have an array type modifier on its type or a regular initializer.\n\n\n### System.MarshalByRefObject Classes\n\nClasses that derive from the class `System.MarshalByRefObject` are marshaled across context boundaries using proxies (that is, by reference) rather than through copying (that is, by value). This means that an instance of such a class may not be a true instance but instead may just be a stub that marshals variable accesses and method calls across a context boundary.\n\nAs a result, it is not possible to create a reference to the storage location of variables defined on such classes. This means that variables typed as classes derived from `System.MarshalByRefObject` cannot be passed to reference parameters, and methods and variables of variables typed as value types may not be accessed. Instead, Visual Basic treats variables defined on such classes as if they were properties (since the restrictions are the same on properties).\n\nThere is one exception to this rule: a member implicitly or explicitly qualified with `Me` is exempt from the above restrictions, because `Me` is always guaranteed to be an actual object, not a proxy.\n\n## Properties\n\n*Properties* are a natural extension of variables; both are named members with associated types, and the syntax for accessing variables and properties is the same. Unlike variables, however, properties do not denote storage locations. Instead, properties have *accessors*, which specify the statements to execute in order to read or write their values.\n\nProperties are defined with property declarations. The first part of a property declaration resembles a field declaration. The second part includes a `Get` accessor and/or a `Set` accessor.\n\n```antlr\nPropertyMemberDeclaration\n    : RegularPropertyMemberDeclaration\n    | MustOverridePropertyMemberDeclaration\n    | AutoPropertyMemberDeclaration\n    ;\n\nPropertySignature\n    : 'Property'\n      Identifier ( OpenParenthesis ParameterList? CloseParenthesis )?\n      ( 'As' Attributes? TypeName )?\n    ;\n\nRegularPropertyMemberDeclaration\n    : Attributes? PropertyModifier* PropertySignature\n      ImplementsClause? LineTerminator\n      PropertyAccessorDeclaration+\n      'End' 'Property' StatementTerminator\n    ;\n\nMustOverridePropertyMemberDeclaration\n    : Attributes? MustOverridePropertyModifier+ PropertySignature\n      ImplementsClause? StatementTerminator\n    ;\n\nAutoPropertyMemberDeclaration\n    : Attributes? AutoPropertyModifier* 'Property' Identifier\n      ( OpenParenthesis ParameterList? CloseParenthesis )?\n      ( 'As' Attributes? TypeName )? ( Equals Expression )?\n      ImplementsClause? LineTerminator\n    | Attributes? AutoPropertyModifier* 'Property' Identifier\n      ( OpenParenthesis ParameterList? CloseParenthesis )?\n      'As' Attributes? 'New'\n      ( NonArrayTypeName ( OpenParenthesis ArgumentList? CloseParenthesis )? )?\n      ObjectCreationExpressionInitializer?\n      ImplementsClause? LineTerminator\n    ;\n\nInterfacePropertyMemberDeclaration\n    : Attributes? InterfacePropertyModifier* PropertySignature StatementTerminator\n    ;\n\nAutoPropertyModifier\n    : AccessModifier\n    | 'Shadows'\n    | 'Shared'\n    | 'Overridable'\n    | 'NotOverridable'\n    | 'Overrides'\n    | 'Overloads'\n    ;\n\nPropertyModifier\n    : AutoPropertyModifier\n    | 'Default'\n    | 'ReadOnly'\n    | 'WriteOnly'\n    | 'Iterator'\n    ;\n\nMustOverridePropertyModifier\n    : PropertyModifier\n    | 'MustOverride'\n    ;\n\nInterfacePropertyModifier\n    : 'Shadows'\n    | 'Overloads'\n    | 'Default'\n    | 'ReadOnly'\n    | 'WriteOnly'\n    ;\n\nPropertyAccessorDeclaration\n    : PropertyGetDeclaration\n    | PropertySetDeclaration\n    ;\n```\n\nIn the example below, the `Button` class defines a `Caption` property.\n\n```vb\nPublic Class Button\n    Private captionValue As String\n\n    Public Property Caption() As String\n        Get\n            Return captionValue\n        End Get\n\n        Set (Value As String)\n            captionValue = value\n            Repaint()\n        End Set\n    End Property\n\n    ...\nEnd Class\n```\n\nBased on the `Button` class above, the following is an example of use of the `Caption` property:\n\n```vb\nDim okButton As Button = New Button()\n\nokButton.Caption = \"OK\" ' Invokes Set accessor.\nDim s As String = okButton.Caption ' Invokes Get accessor.\n```\n\nHere, the `Set` accessor is invoked by assigning a value to the property, and the `Get` accessor is invoked by referencing the property in an expression.\n\nIf no type is specified for a property and strict semantics are being used, a compile-time error occurs; otherwise the type of the property is implicitly `Object` or the type of the property's type character. A property declaration may contain either a `Get` accessor, which retrieves the value of the property, a `Set` accessor, which stores the value of the property, or both. Because a property implicitly declares methods, a property may be declared with the same modifiers as a method. If the property is defined in an interface or defined with the `MustOverride` modifier, the property body and the `End` construct must be omitted; otherwise, a compile-time error occurs.\n\nThe index parameter list makes up the signature of the property, so properties may be overloaded on index parameters but not on the type of the property. The index parameter list is the same as for a regular method. However, none of the parameters may be modified with the `ByRef` modifier and none of them may be named `Value` (which is reserved for the implicit value parameter in the `Set` accessor).\n\nA property may be declared as follows:\n\n* If the property specifies no property type modifier, the property must have both a `Get` accessor and a `Set` accessor. The property is said to be a read-write property.\n\n* If the property specifies the `ReadOnly` modifier, the property must have a `Get` accessor and may not have a `Set` accessor. The property is said to be read-only property. It is a compile-time error for a read-only property to be the target of an assignment.\n\n* If the property specifies the `WriteOnly` modifier, the property must have a `Set` accessor and may not have a `Get` accessor. The property is said to be write-only property. It is a compile-time error to reference a write-only property in an expression except as the target of an assignment or as an argument to a method.\n\nThe `Get` and `Set` accessors of a property are not distinct members, and it is not possible to declare the accessors of a property separately. The following example does not declare a single read-write property. Rather, it declares two properties with the same name, one read-only and one write-only:\n\n```vb\nClass A\n    Private nameValue As String\n\n    ' Error, contains a duplicate member name.\n    Public ReadOnly Property Name() As String \n        Get\n            Return nameValue\n        End Get\n    End Property\n\n    ' Error, contains a duplicate member name.\n    Public WriteOnly Property Name() As String \n        Set (Value As String)\n            nameValue = value\n        End Set\n    End Property\nEnd Class\n```\n\nSince two members declared in the same class cannot have the same name, the example causes a compile-time error.\n\nBy default, the accessibility of a property's `Get` and `Set` accessors is the same as the accessibility of the property itself. However, the `Get` and `Set` accessors can also specify accessibility separately from the property. In that case, the accessibility of an accessor must be more restrictive than the accessibility of the property and only one accessor can have a different accessibility level from the property. Access types are considered more or less restrictive as follows:\n\n* `Private` is more restrictive than `Public`, `Protected Friend`, `Protected`, or `Friend`.\n\n* `Friend` is more restrictive than `Protected Friend` or `Public`.\n\n* `Protected` is more restrictive than `Protected Friend` or `Public`.\n\n* `Protected Friend` is more restrictive than `Public`.\n\nWhen one of a property's accessors is accessible but the other one is not, the property is treated as if it was read-only or write-only. For example:\n\n```vb\nClass A\n    Public Property P() As Integer\n        Get\n            ...\n        End Get\n\n        Private Set (Value As Integer)\n            ...\n        End Set\n    End Property\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim a As A = New A()\n\n        ' Error: A.P is read-only in this context.\n        a.P = 10\n    End Sub\nEnd Module\n```\n\nWhen a derived type shadows a property, the derived property hides the shadowed property with respect to both reading and writing. In the following example, the `P` property in `B` hides the `P` property in `A` with respect to both reading and writing:\n\n```vb\nClass A\n    Public WriteOnly Property P() As Integer\n        Set (Value As Integer)\n        End Set\n    End Property\nEnd Class\n\nClass B\n    Inherits A\n\n    Public Shadows ReadOnly Property P() As Integer\n       Get\n       End Get\n    End Property\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim x As B = New B\n\n        B.P = 10     ' Error, B.P is read-only.\n    End Sub\nEnd Module\n```\n\nThe accessibility domain of the return type or parameter types must be the same as or a superset of the accessibility domain of the property itself. A property may only have one `Set` accessor and one `Get` accessor.\n\nExcept for differences in declaration and invocation syntax, `Overridable`, `NotOverridable`, `Overrides`, `MustOverride`, and `MustInherit` properties behave exactly like `Overridable`, `NotOverridable`, `Overrides`, `MustOverride`, and `MustInherit` methods. When a property is overridden, the overriding property must be of the same type (read-write, read-only, write-only). An `Overridable` property cannot contain a `Private` accessor.\n\nIn the following example `X` is an `Overridable` read-only property, `Y` is an `Overridable` read-write property, and `Z` is a `MustOverride` read-write property.\n\n```vb\nMustInherit Class A\n    Private _y As Integer\n\n    Public Overridable ReadOnly Property X() As Integer\n        Get\n            Return 0\n        End Get\n    End Property\n\n    Public Overridable Property Y() As Integer\n        Get\n            Return _y\n         End Get\n        Set (Value As Integer)\n            _y = value\n        End Set\n    End Property\n\n    Public MustOverride Property Z() As Integer\nEnd Class\n```\n\nBecause `Z` is `MustOverride`, the containing class `A` must be declared `MustInherit`.\n\nBy contrast, a class that derives from class `A` is shown below:\n\n```vb\nClass B\n    Inherits A\n\n    Private _z As Integer\n\n    Public Overrides ReadOnly Property X() As Integer\n        Get\n            Return MyBase.X + 1\n        End Get\n    End Property\n\n    Public Overrides Property Y() As Integer\n        Get\n            Return MyBase.Y\n        End Get\n        Set (Value As Integer)\n            If value < 0 Then\n                MyBase.Y = 0\n            Else\n                MyBase.Y = Value\n            End If\n        End Set\n    End Property\n\n    Public Overrides Property Z() As Integer\n        Get\n            Return _z\n        End Get\n        Set (Value As Integer)\n            _z = Value\n        End Set\n    End Property\nEnd Class\n```\n\nHere, the declarations of properties `X`,`Y`, and `Z` override the base properties. Each property declaration exactly matches the accessibility modifiers, type, and name of the corresponding inherited property. The `Get` accessor of property `X` and the `Set` accessor of property `Y` use the `MyBase` keyword to access the inherited properties. The declaration of property `Z` overrides the `MustOverride` property -- thus, there are no outstanding `MustOverride` members in class `B`, and `B` is permitted to be a regular class.\n\nProperties can be used to delay initialization of a resource until the moment it is first referenced. For example:\n\n```vb\nImports System.IO\n\nPublic Class ConsoleStreams\n    Private Shared reader As TextReader\n    Private Shared writer As TextWriter\n    Private Shared errors As TextWriter\n\n    Public Shared ReadOnly Property [In]() As TextReader\n        Get\n            If reader Is Nothing Then\n                reader = Console.In\n            End If\n            Return reader\n        End Get\n    End Property\n\n    Public Shared ReadOnly Property Out() As TextWriter\n        Get\n            If writer Is Nothing Then\n                writer = Console.Out\n            End If\n            Return writer\n        End Get\n    End Property\n\n    Public Shared ReadOnly Property [Error]() As TextWriter\n        Get\n            If errors Is Nothing Then\n                errors = Console.Error\n            End If\n            Return errors\n        End Get\n    End Property\nEnd Class\n```\n\nThe `ConsoleStreams` class contains three properties, `In`, `Out`, and `Error`, that represent the standard input, output, and error devices, respectively. By exposing these members as properties, the `ConsoleStreams` class can delay their initialization until they are actually used. For example, upon first referencing the `Out` property, as in `ConsoleStreams.Out.WriteLine(\"hello, world\")`, the underlying `TextWriter` for the output device is initialized. But if the application makes no reference to the `In` and `Error` properties, then no objects are created for those devices.\n\n\n### Get Accessor Declarations\n\nA `Get` accessor (getter) is declared by using a property `Get` declaration. A property `Get` declaration consists of the keyword `Get` followed by a statement block. Given a property named `P`, a `Get` accessor declaration implicitly declares a method with the name `get_P` with the same modifiers, type, and parameter list as the property. If the type contains a declaration with that name, a compile-time error results, but the implicit declaration is ignored for the purposes of name binding.\n\nA special local variable, which is implicitly declared in the `Get` accessor body's declaration space with the same name as the property, represents the return value of the property. The local variable has special name resolution semantics when used in expressions. If the local variable is used in a context that expects an expression that is classified as a method group, such as an invocation expression, then the name resolves to the function rather than to the local variable. For example:\n\n```vb\nReadOnly Property F(i As Integer) As Integer\n    Get\n        If i = 0 Then\n            F = 1    ' Sets the return value.\n        Else\n            F = F(i - 1) ' Recursive call.\n        End If\n    End Get\nEnd Property\n```\n\nThe use of parentheses can cause ambiguous situations (such as `F(1)` where `F` is a property whose type is a one-dimensional array). In all ambiguous situations, the name resolves to the property rather than the local variable. For example:\n\n```vb\nReadOnly Property F(i As Integer) As Integer()\n    Get\n        If i = 0 Then\n            F = new Integer(2) { 1, 2, 3 }\n        Else\n            F = F(i - 1) ' Recursive call, not index.\n        End If\n    End Get\nEnd Property\n```\n\nWhen control flow leaves the `Get` accessor body, the value of the local variable is passed back to the invocation expression. Because invoking a `Get` accessor is conceptually equivalent to reading the value of a variable, it is considered bad programming style for `Get` accessors to have observable side effects, as illustrated in the following example:\n\n```vb\nClass Counter\n    Private Value As Integer\n\n    Public ReadOnly Property NextValue() As Integer\n        Get\n            Value += 1\n            Return Value\n        End Get\n    End Property\nEnd Class\n```\n\nThe value of the `NextValue` property depends on the number of times the property has previously been accessed. Thus, accessing the property produces an observable side effect, and the property should instead be implemented as a method.\n\nThe \"no side effects\" convention for `Get` accessors does not mean that `Get` accessors should always be written to simply return values stored in variables. Indeed, `Get` accessors often compute the value of a property by accessing multiple variables or invoking methods. However, a properly designed `Get` accessor performs no actions that cause observable changes in the state of the object.\n\n__Note.__ `Get` accessors have the same restriction on line placement that subroutines have. The beginning statement, end statement and block must all appear at the beginning of a logical line.\n\n```antlr\nPropertyGetDeclaration\n    : Attributes? AccessModifier? 'Get' LineTerminator\n      Block?\n      'End' 'Get' StatementTerminator\n    ;\n```\n\n### Set Accessor Declarations\n\nA `Set` accessor (setter) is declared by using a property set declaration. A property set declaration consists of the keyword `Set`, an optional parameter list, and a statement block. Given a property named `P`, a setter declaration implicitly declares a method with the name `set_P` with the same modifiers and parameter list as the property. If the type contains a declaration with that name, a compile-time error results, but the implicit declaration is ignored for the purposes of name binding.\n\nIf a parameter list is specified, it must have one member, that member must have no modifiers except `ByVal`, and its type must be the same as the type of the property. The parameter represents the property value being set. If the parameter is omitted, a parameter named `Value` is implicitly declared.\n\n__Note.__ `Set` accessors have the same restriction on line placement that subroutines have. The beginning statement, end statement and block must all appear at the beginning of a logical line.\n\n```antlr\nPropertySetDeclaration\n    : Attributes? AccessModifier? 'Set'\n      ( OpenParenthesis ParameterList? CloseParenthesis )? LineTerminator\n      Block?\n      'End' 'Set' StatementTerminator\n    ;\n```\n\n### Default Properties\n\nA property that specifies the modifier `Default` is called a *default property*. Any type that allows properties may have a default property, including interfaces. The default property may be referenced without having to qualify the instance with the name of the property. Thus, given a class\n\n```vb\nClass Test\n    Public Default ReadOnly Property Item(i As Integer) As Integer\n        Get\n            Return i\n        End Get\n    End Property\nEnd Class\n```\n\nthe code\n\n```vb\nModule TestModule\n    Sub Main()\n        Dim x As Test = New Test()\n        Dim y As Integer\n\n        y = x(10)\n    End Sub\nEnd Module\n```\n\nis equivalent to\n\n```vb\nModule TestModule\n    Sub Main()\n        Dim x As Test = New Test()\n        Dim y As Integer\n\n        y = x.Item(10)\n    End Sub\nEnd Module\n```\n\nOnce a property is declared `Default`, all of the properties overloaded on that name in the inheritance hierarchy become the default property, whether they have been declared `Default` or not. Declaring a property `Default` in a derived class when the base class declared a default property by another name does not require any other modifiers such as `Shadows` or `Overrides`. This is because the default property has no identity or signature and so cannot be shadowed or overloaded. For example:\n\n```vb\nClass Base\n    Public ReadOnly Default Property Item(i As Integer) As Integer\n        Get\n            Console.WriteLine(\"Base = \" & i)\n        End Get\n    End Property\nEnd Class\n\nClass Derived\n    Inherits Base\n\n    ' This hides Item, but does not change the default property.\n    Public Shadows ReadOnly Property Item(i As Integer) As Integer\n        Get\n            Console.WriteLine(\"Derived = \" & i)\n        End Get\n    End Property\nEnd Class\n\nClass MoreDerived\n    Inherits Derived\n\n    ' This declares a new default property, but not Item.\n    ' This does not need to be declared Shadows\n    Public ReadOnly Default Property Value(i As Integer) As Integer\n        Get\n            Console.WriteLine(\"MoreDerived = \" & i)\n        End Get\n    End Property\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim x As MoreDerived = New MoreDerived()\n        Dim y As Integer\n        Dim z As Derived = x\n\n        y = x(10)        ' Calls MoreDerived.Value.\n        y = x.Item(10)   ' Calls Derived.Item\n        y = z(10)        ' Calls Base.Item\n    End Sub\nEnd Module\n```\n\nThis program will produce the output:\n\n```console\nMoreDerived = 10\nDerived = 10\nBase = 10\n```\n\nAll default properties declared within a type must have the same name and, for clarity, must specify the `Default` modifier. Because a default property with no index parameters would cause an ambiguous situation when assigning instances of the containing class, default properties must have index parameters. Furthermore, if one property overloaded on a particular name includes the `Default` modifier, all properties overloaded on that name must specify it. Default properties may not be `Shared`, and at least one accessor of the property must not be `Private`.\n\n### Automatically Implemented Properties\n\nIf a property omits declaration of any accessors, an implementation of the property will be automatically supplied unless the property is declared in an interface or is declared `MustOverride`. Only read/write properties with no arguments can be automatically implemented; otherwise, a compile-time error occurs.\n\nAn automatically implemented property `x`, even one overriding another property, introduces a private local variable `_x` with the same type as the property. If there is a collision between the local variable's name and another declaration, a compile-time error will be reported. The automatically implemented property's `Get` accessor returns the value of the local and the property's `Set` accessor that sets the value of the local. For example, the declaration:\n\n```vb\nPublic Property x() As Integer\n```\n\nis roughly equivalent to:\n\n```vb\nPrivate _x As Integer\nPublic Property x() As Integer\n    Get\n        Return _x\n    End Get\n    Set (value As Integer)\n        _x = value\n    End Set\nEnd Property\n```\n\nAs with variable declarations, an automatically implemented property can include an initializer. For example:\n\n```vb\nPublic Property x() As Integer = 10\nPublic Shared Property y() As New Customer() With { .Name = \"Bob\" }\n```\n\n__Note.__ When an automatically implemented property is initialized, it is initialized through the property, not the underlying field. This is so overriding properties can intercept the initialization if they need to.\n\nArray initializers are allowed on automatically implemented properties, except that there is no way to specify the array bounds explicitly.  For example:\n\n```vb\n' Valid\nProperty x As Integer() = {1, 2, 3}\nProperty y As Integer(,) = {{1, 2, 3}, {12, 13, 14}, {11, 10, 9}}\n\n' Invalid\nProperty x4(5) As Short\n```\n\n### Iterator Properties\n\nAn *iterator property* is a property with the `Iterator` modifier. It is used for the same reason an iterator method (Section [Iterator Methods](statements.md#iterator-methods)) is used -- as a convenient way to generate a sequence, one which can be consumed by the `For Each` statement. The `Get` accessor of an iterator property is interpreted in the same way as an iterator method.\n\nAn iterator property must have an explicit `Get` accessor, and its type must be `IEnumerator`, or `IEnumerable`, or `IEnumerator(Of T)` or `IEnumerable(Of T)` for some `T`.\n\nHere is an example of an iterator property:\n\n```vb\nClass Family\n    Property Daughters As New List(Of String) From {\"Beth\", \"Diane\"}\n    Property Sons As New List(Of String) From {\"Abe\", \"Carl\"}\n\n    ReadOnly Iterator Property Children As IEnumerable(Of String)\n        Get\n            For Each name In Daughters : Yield name : Next\n            For Each name In Sons : Yield name : Next\n        End Get\n    End Property\nEnd Class\n\nModule Module1\n    Sub Main()\n        Dim x As New Family\n        For Each c In x.Children\n            Console.WriteLine(c) ' prints Beth, Diane, Abe, Carl\n        Next\n    End Sub\nEnd Module\n```\n\n## Operators\n\n*Operators* are methods that define the meaning of an existing Visual Basic operator for the containing class. When the operator is applied to the class in an expression, the operator is compiled into a call to the operator method defined in the class. Defining an operator for a class is also known as *overloading* the operator.\n\n```antlr\nOperatorDeclaration\n    : Attributes? OperatorModifier* 'Operator' OverloadableOperator\n      OpenParenthesis ParameterList CloseParenthesis\n      ( 'As' Attributes? TypeName )? LineTerminator\n      Block?\n      'End' 'Operator' StatementTerminator\n    ;\n\nOperatorModifier\n    : 'Public' | 'Shared' | 'Overloads' | 'Shadows' | 'Widening' | 'Narrowing'\n    ;\n\nOverloadableOperator\n    : '+' | '-' | '*' | '/' | '\\\\' | '&' | 'Like' | 'Mod' | 'And' | 'Or' | 'Xor'\n    | '^' | '<' '<' | '>' '>' | '=' | '<' '>' | '>' | '<' | '>' '=' | '<' '='\n    | 'Not' | 'IsTrue' | 'IsFalse' | 'CType'\n    ;\n```\n\nIt is not possible to overload an operator that already exists; in practice, this primarily applies to conversion operators. For example, it is not possible to overload the conversion from a derived class to a base class:\n\n```vb\nClass Base\nEnd Class\n\nClass Derived\n    ' Cannot redefine conversion from Derived to Base,\n    ' conversion will be ignored.\n    Public Shared Widening Operator CType(s As Derived) As Base\n        ...\n    End Operator\nEnd Class\n```\n\nOperators can also be overloaded in the common sense of the word:\n\n```vb\nClass Base\n    Public Shared Widening Operator CType(b As Base) As Integer\n        ...\n    End Operator\n\n    Public Shared Narrowing Operator CType(i As Integer) As Base\n        ...\n    End Operator\nEnd Class\n```\n\nOperator declarations do not explicitly add names to the containing type's declaration space; however they do implicitly declare a corresponding method starting with the characters \"op_\". The following sections list the corresponding method names with each operator.\n\nThere are three classes of operators that can be defined: unary operators, binary operators and conversion operators. All operator declarations share certain restrictions:\n\n* Operator declarations must always be `Public` and `Shared`. The `Public` modifier can be omitted in contexts where the modifier will be assumed.\n\n* The parameters of an operator cannot be declared `ByRef`, `Optional` or `ParamArray`.\n\n* The type of at least one of the operands or the return value must be the type that contains the operator.\n\n* There is no function return variable defined for operators. Therefore, the `Return` statement must be used to return values from an operator body.\n\nThe only exception to these restrictions applies to nullable value types. Since nullable value types do not have an actual type definition, a value type can declare user-defined operators for the nullable version of the type. When determining whether a type can declare a particular user-defined operator, the `?` modifiers are first dropped off of all of the types involved in the declaration for the purposes of validity checking. This relaxation does not apply to the return type of the `IsTrue` and `IsFalse` operators; they must still return `Boolean`, not `Boolean?`.\n\nThe precedence and associativity of an operator cannot be modified by an operator declaration.\n\n__Note.__ Operators have the same restriction on line placement that subroutines have. The beginning statement, end statement and block must all appear at the beginning of a logical line.\n\n\n### Unary Operators\n\nThe following unary operators can be overloaded:\n\n* The unary plus operator `+` (corresponding method: `op_UnaryPlus`)\n\n* The unary minus operator `-` (corresponding method: `op_UnaryNegation`)\n\n* The logical `Not` operator (corresponding method: `op_OnesComplement`)\n\n* The `IsTrue` and `IsFalse` operators (corresponding methods: `op_True`, `op_False`)\n\nAll overloaded unary operators must take a single parameter of the containing type and may return any type, except for `IsTrue` and `IsFalse`, which must return `Boolean`. If the containing type is a generic type, the type parameters must match the containing type's type parameters. For example,\n\n```vb\nStructure Complex\n    ...\n\n    Public Shared Operator +(v As Complex) As Complex\n        Return v\n    End Operator\nEnd Structure\n```\n\nIf a type overloads one of `IsTrue` or `IsFalse`, then it must overload the other as well. If only one is overloaded, a compile-time error results.\n\n__Note.__ `IsTrue` and `IsFalse` are not reserved words.\n\n### Binary Operators\n\nThe following binary operators can be overloaded:\n\n* The addition `+`, subtraction `-`, multiplication `*`, division `/`, integral division `\\`, modulo `Mod` and exponentiation `^` operators (corresponding method: `op_Addition`, `op_Subtraction`, `op_Multiply`, `op_Division`, `op_IntegerDivision`, `op_Modulus`, `op_Exponent`)\n\n* The relational operators `=`, `<>`, `<`, `>`, `<=`, `>=` (corresponding methods: `op_Equality`, `op_Inequality`, `op_LessThan`, `op_GreaterThan`, `op_LessThanOrEqual`, `op_GreaterThanOrEqual`). __Note.__ While the equality operator can be overloaded, the assignment operator (used only in assignment statements) cannot be overloaded.\n\n* The `Like` operator (corresponding method: `op_Like`)\n\n* The concatenation operator `&` (corresponding method: `op_Concatenate`)\n\n* The logical `And`, `Or` and `Xor` operators (corresponding methods: `op_BitwiseAnd`, `op_BitwiseOr`, `op_ExclusiveOr`)\n\n* The shift operators `<<` and `>>` (corresponding methods: `op_LeftShift`, `op_RightShift`)\n\nAll overloaded binary operators must take the containing type as one of the parameters. If the containing type is a generic type, the type parameters must match the containing type's type parameters. The shift operators further restrict this rule to require the first parameter to be of the containing type; the second parameter must always be of type `Integer`.\n\nThe following binary operators must be declared in pairs:\n\n* Operator `=` and operator `<>`\n\n* Operator `>` and operator `<`\n\n* Operator `>=` and operator `<=`\n\nIf one of the pair is declared, then the other must also be declared with matching parameter and return types, or a compile-time error will result. (__Note.__ The purpose of requiring paired declarations of relational operators is to try and ensure at least a minimum level of logical consistency in overloaded operators.)\n\nIn contrast to the relational operators, overloading both the division and integral division operators is strongly discouraged, although not an error. (__Note.__ In general, the two types of division should be entirely distinct: a type that supports division is either integral (in which case it should support `\\`) or not (in which case it should support `/`). We considered making it an error to define both operators, but because their languages do not generally distinguish between two types of division the way Visual Basic does, we felt it was safest to allow the practice but strongly discourage it.)\n\nCompound assignment operators cannot be overloaded directly. Instead, when the corresponding binary operator is overloaded, the compound assignment operator will use the overloaded operator. For example:\n\n```vb\nStructure Complex\n    ...\n\n    Public Shared Operator +(x As Complex, y As Complex) _\n        As Complex\n        ...\n    End Operator\nEnd Structure\n\nModule Test\n    Sub Main()\n        Dim c1, c2 As Complex\n        ' Calls the overloaded + operator\n        c1 += c2\n    End Sub\nEnd Module\n```\n\n### Conversion Operators\n\nConversion operators define new conversions between types. These new conversions are called *user-defined conversions*. A conversion operator converts from a source type, indicated by the parameter type of the conversion operator, to a target type, indicated by the return type of the conversion operator. Conversions must be classified as either widening or narrowing. A conversion operator declaration that includes the `Widening` keyword introduces a user-defined widening conversion (corresponding method: `op_Implicit`). A conversion operator declaration that includes the `Narrowing` keyword introduces a user-defined narrowing conversion (corresponding method: `op_Explicit`).\n\nIn general, user-defined widening conversions should be designed to never throw exceptions and never lose information. If a user-defined conversion can cause exceptions (for example, because the source argument is out of range) or loss of information (such as discarding high-order bits), then that conversion should be defined as a narrowing conversion. In the example:\n\n```vb\nStructure Digit\n    Dim value As Byte\n\n    Public Sub New(value As Byte)\n        if value < 0 OrElse value > 9 Then Throw New ArgumentException()\n        Me.value = value\n    End Sub\n\n    Public Shared Widening Operator CType(d As Digit) As Byte\n        Return d.value\n    End Operator\n\n    Public Shared Narrowing Operator CType(b As Byte) As Digit\n        Return New Digit(b)\n    End Operator\nEnd Structure\n```\n\nthe conversion from `Digit` to `Byte` is a widening conversion because it never throws exceptions or loses information, but the conversion from `Byte` to `Digit` is a narrowing conversion since `Digit` can only represent a subset of the possible values of a `Byte`.\n\nUnlike all other type members that can be overloaded, the signature of a conversion operator includes the target type of the conversion. This is the only type member for which the return type participates in the signature. The widening or narrowing classification of a conversion operator, however, is not part of the operator's signature. Thus, a class or structure cannot declare both a widening conversion operator and a narrowing conversion operator with the same source and target types.\n\nA user-defined conversion operator must convert either to or from the containing type -- for example, it is possible for a class `C` to define a conversion from `C` to `Integer` and from `Integer` to `C`, but not from `Integer` to `Boolean`. If the containing type is a generic type, the type parameters must match the containing type's type parameters. Also, it is not possible to redefine an intrinsic (i.e. non-user-defined) conversion. As a result, a type cannot declare a conversion where:\n\n* The source type and the destination type are the same.\n\n* Both the source type and the destination type are not the type that defines the conversion operator.\n\n* The source type or the destination type is an interface type.\n\n* The source type and destination types are related by inheritance (including `Object`).\n\nThe only exception to these rules applies to nullable value types. Since nullable value types do not have an actual type definition, a value type can declare user-defined conversions for the nullable version of the type. When determining whether a type can declare a particular user-defined conversion, the `?` modifiers are first dropped off of all of the types involved in the declaration for the purposes of validity checking. Thus, the following declaration is valid because `S` can define a conversion from `S` to `T`:\n\n```vb\nStructure T\n    ...\nEnd Structure\n\nStructure S\n    Public Shared Widening Operator CType(ByVal v As S?) As T\n    ...\n    End Operator\nEnd Structure\n```\n\nThe following declaration is not valid, however, because structure `S` cannot define a conversion from `S` to `S`:\n\n```vb\nStructure S\n    Public Shared Widening Operator CType(ByVal v As S) As S?\n        ...\n    End Operator\nEnd Structure\n```\n\n### Operator Mapping\n\nBecause the set of operators that Visual Basic supports may not exactly match the set of operators that other languages on the .NET Framework, some operators are mapped specially onto other operators when being defined or used. Specifically:\n\n* Defining an integral division operator will automatically define a regular division operator (usable only from other languages) that will call the integral division operator.\n\n* Overloading the `Not`, `And`, and `Or` operators will overload only the bitwise operator from the perspective of other languages that distinguish between logical and bitwise operators.\n\n* A class that overloads only the logical operators in a language that distinguishes between logical and bitwise operators (i.e. a languages that uses `op_LogicalNot`, `op_LogicalAnd`, and `op_LogicalOr` for `Not`, `And`, and `Or`, respectively) will have their logical operators mapped onto the Visual Basic logical operators. If both the logical and bitwise operators are overloaded, only the bitwise operators will be used.\n\n* Overloading the `<<` and `>>` operators will overload only the signed operators from the perspective of other languages that distinguish between signed and unsigned shift operators.\n\n* A class that overloads only an unsigned shift operator will have the unsigned shift operator mapped onto the corresponding Visual Basic shift operator. If both an unsigned and signed shift operator is overloaded, only the signed shift operator will be used.\n"
  },
  {
    "path": "spec/types.md",
    "content": "# Types in Visual Basic\n\nThe two fundamental categories of types in Visual Basic are *value types* and *reference types*. Primitive types (except strings), enumerations, and structures are value types. Classes, strings, standard modules, interfaces, arrays, and delegates are reference types.\n\nEvery type has a *default value*, which is the value that is assigned to variables of that type upon initialization.\n\n```antlr\nTypeName\n    : ArrayTypeName\n    | NonArrayTypeName\n    ;\n\nNonArrayTypeName\n    : SimpleTypeName\n    | NullableTypeName\n    ;\n\nSimpleTypeName\n    : QualifiedTypeName\n    | BuiltInTypeName\n    ;\n\nQualifiedTypeName\n    : Identifier TypeArguments? (Period IdentifierOrKeyword TypeArguments?)*\n    | 'Global' Period IdentifierOrKeyword TypeArguments?\n      (Period IdentifierOrKeyword TypeArguments?)*\n    ;\n\nTypeArguments\n    : OpenParenthesis 'Of' TypeArgumentList CloseParenthesis\n    ;\n\nTypeArgumentList\n    : TypeName ( Comma TypeName )*\n    ;\n\nBuiltInTypeName\n    : 'Object'\n    | PrimitiveTypeName\n    ;\n\nTypeModifier\n    : AccessModifier\n    | 'Shadows'\n    ;\n\nIdentifierModifiers\n    : NullableNameModifier? ArrayNameModifier?\n    ;\n```\n\n## Value Types and Reference Types\n\nAlthough value types and reference types can be similar in terms of declaration syntax and usage, their semantics are distinct.\n\nReference types are stored on the run-time heap; they may only be accessed through a reference to that storage. Because reference types are always accessed through references, their lifetime is managed by the .NET Framework. Outstanding references to a particular instance are tracked and the instance is destroyed only when no more references remain. A variable of reference type contains a reference to a value of that type, a value of a more derived type, or a null value. A *null value* refers to nothing; it is not possible to do anything with a null value except assign it. Assignment to a variable of a reference type creates a copy of the reference rather than a copy of the referenced value. For a variable of a reference type, the default value is a null value.\n\nValue types are stored directly on the stack, either within an array or within another type; their storage can only be accessed directly. Because value types are stored directly within variables, their lifetime is determined by the lifetime of the variable that contains them. When the location containing a value type instance is destroyed, the value type instance is also destroyed. Value types are always accessed directly; it is not possible to create a reference to a value type. Prohibiting such a reference makes it impossible to refer to a value class instance that has been destroyed. Because value types are always `NotInheritable`, a variable of a value type always contains a value of that type. Because of this, the value of a value type cannot be a null value, nor can it reference an object of a more derived type. Assignment to a variable of a value type creates a copy of the value being assigned. For a variable of a value type, the default value is the result of initializing each variable member of the type to its default value.\n\nThe following example shows the difference between reference types and value types:\n\n```vb\nClass Class1\n    Public Value As Integer = 0\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim val1 As Integer = 0\n        Dim val2 As Integer = val1\n        val2 = 123\n        Dim ref1 As Class1 = New Class1()\n        Dim ref2 As Class1 = ref1\n        ref2.Value = 123\n        Console.WriteLine(\"Values: \" & val1 & \", \" & val2)\n        Console.WriteLine(\"Refs: \" & ref1.Value & \", \" & ref2.Value)\n    End Sub\nEnd Module\n```\n\nThe output of the program is:\n\n```console\nValues: 0, 123\nRefs: 123, 123\n```\n\nThe assignment to the local variable `val2` does not impact the local variable `val1` because both local variables are of a value type (the type `Integer`) and each local variable of a value type has its own storage. In contrast, the assignment `ref2.Value = 123;` affects the object that both `ref1` and `ref2` reference.\n\nOne thing to note about the .NET Framework type system is that even though structures, enumerations and primitive types (except for `String`) are value types, they all inherit from reference types. Structures and the primitive types inherit from the reference type `System.ValueType`, which inherits from `Object`. Enumerated types inherit from the reference type `System.Enum`, which inherits from `System.ValueType`.\n\n### Nullable Value Types\n\nFor value types, a `?` modifier can be added to a type name to represent the *nullable* version of that type.\n\n```antlr\nNullableTypeName\n    : NonArrayTypeName '?'\n    ;\n\nNullableNameModifier\n    : '?'\n    ;\n```\n\nA nullable value type can contain the same values as the non-nullable version of the type as well as the null value. Thus, for a nullable value type, assigning `Nothing` to a variable of the type sets the value of the variable to the null value, not the zero value of the value type. For example:\n\n```vb\nDim x As Integer = Nothing\nDim y As Integer? = Nothing\n\n' Prints zero\nConsole.WriteLine(x)\n' Prints nothing (because the value of y is the null value)\nConsole.WriteLine(y)\n```\n\nA variable may also be declared to be of a nullable value type by putting a nullable type modifier on the variable name. For clarity, it is not valid to have a nullable type modifier on both a variable name and a type name in the same declaration. Since nullable types are implemented using the type `System.Nullable(Of T)`, the type `T?` is synonymous to the type `System.Nullable(Of T)`, and the two names can be used interchangeably. The `?` modifier cannot be placed on a type that is already nullable; thus, it is not possible to declare the type `Integer??` or `System.Nullable(Of Integer)?`.\n\nA nullable value type `T?` has the members of `System.Nullable(Of T)` as well as any operators or conversions *lifted* from the underlying type `T` into the type `T?`. Lifting copies operators and conversions from the underlying type, in most cases substituting nullable value types for non-nullable value types. This allows many of the same conversions and operations that apply to `T` to apply to `T?` as well.\n\n\n## Interface Implementation\n\nStructure and class declarations may declare that they implement a set of interface types through one or more `Implements` clauses.\n\n```antlr\nTypeImplementsClause\n    : 'Implements' TypeImplements StatementTerminator\n    ;\n\nTypeImplements\n    : NonArrayTypeName ( Comma NonArrayTypeName )*\n    ;\n```\n\nAll the types specified in the `Implements` clause must be interfaces, and the type must implement all members of the interfaces. For example:\n\n```vb\nInterface ICloneable\n    Function Clone() As Object\nEnd Interface \n\nInterface IComparable\n    Function CompareTo(other As Object) As Integer\nEnd Interface \n\nStructure ListEntry\n    Implements ICloneable, IComparable\n\n    ...\n\n    Public Function Clone() As Object Implements ICloneable.Clone\n        ...\n    End Function \n\n    Public Function CompareTo(other As Object) As Integer _\n        Implements IComparable.CompareTo\n        ...\n    End Function \nEnd Structure\n```\n\nA type that implements an interface also implicitly implements all of the interface's base interfaces. This is true even if the type does not explicitly list all base interfaces in the `Implements` clause. In this example, the `TextBox` structure implements both `IControl` and `ITextBox`.\n\n```vb\nInterface IControl\n    Sub Paint()\nEnd Interface \n\nInterface ITextBox\n    Inherits IControl\n\n    Sub SetText(text As String)\nEnd Interface \n\nStructure TextBox\n    Implements ITextBox\n\n    ...\n\n    Public Sub Paint() Implements ITextBox.Paint\n        ...\n    End Sub\n\n    Public Sub SetText(text As String) Implements ITextBox.SetText\n        ...\n    End Sub\nEnd Structure\n```\n\nDeclaring that a type implements an interface in and of itself does not declare anything in the declaration space of the type. Thus, it is valid to implement two interfaces with a method by the same name.\n\nTypes cannot implement a type parameter on its own, although it may involve the type parameters that are in scope.\n\n```vb\nClass C1(Of V)\n    Implements V  ' Error, can't implement type parameter directly\n    Implements IEnumerable(Of V)  ' OK, not directly implementing\n\n    ...\nEnd Class\n```\n\nGeneric interfaces can be implemented multiple times using different type arguments. However, a generic type cannot implement a generic interface using a type parameter if the supplied type parameter (regardless of type constraints) could overlap with another implementation of that interface. For example:\n\n```vb\nInterface I1(Of T)\nEnd Interface\n\nClass C1\n    Implements I1(Of Integer)\n    Implements I1(Of Double)    ' OK, no overlap\nEnd Class\n\nClass C2(Of T)\n    Implements I1(Of Integer)\n    Implements I1(Of T)         ' Error, T could be Integer\nEnd Class\n```\n\n\n## Primitive Types\n\nThe *primitive types* are identified through keywords, which are aliases for predefined types in the `System` namespace. A primitive type is completely indistinguishable from the type it aliases: writing the reserved word `Byte` is exactly the same as writing `System.Byte`. Primitive types are also known as *intrinsic types*.\n\n```antlr\nPrimitiveTypeName\n    : NumericTypeName\n    | 'Boolean'\n    | 'Date'\n    | 'Char'\n    | 'String'\n    ;\n\nNumericTypeName\n    : IntegralTypeName\n    | FloatingPointTypeName\n    | 'Decimal'\n    ;\n\nIntegralTypeName\n    : 'Byte' | 'SByte' | 'UShort' | 'Short' | 'UInteger'\n    | 'Integer' | 'ULong' | 'Long'\n    ;\n\nFloatingPointTypeName\n    : 'Single' | 'Double'\n    ;\n```\n\n\nBecause a primitive type aliases a regular type, every primitive type has members. For example, `Integer` has the members declared in `System.Int32`. Literals can be treated as instances of their corresponding types.\n\n* The primitive types differ from other structure types in that they permit certain additional operations:\n\n* Primitive types permit values to be created by writing literals. For example, `123I` is a literal of type `Integer`.\n\n* It is possible to declare constants of the primitive types.\n\n* When the operands of an expression are all primitive type constants, it is possible for the compiler to evaluate the expression at compile time. Such an expression is known as a constant expression.\n\nVisual Basic defines the following primitive types:\n\n* The integral value types `Byte` (1-byte unsigned integer), `SByte` (1-byte signed integer), `UShort` (2-byte unsigned integer), `Short` (2-byte signed integer), `UInteger` (4-byte unsigned integer), `Integer` (4-byte signed integer), `ULong` (8-byte unsigned integer), and `Long` (8-byte signed integer). These types map to `System.Byte`, `System.SByte`, `System.UInt16`, `System.Int16`, `System.UInt32`, `System.Int32`, `System.UInt64` and `System.Int64`, respectively. The default value of an integral type is equivalent to the literal `0`.\n\n* The floating-point value types `Single` (4-byte floating point) and `Double` (8-byte floating point). These types map to `System.Single` and `System.Double`, respectively. The default value of a floating-point type is equivalent to the literal `0`.\n\n* The `Decimal` type (16-byte decimal value), which maps to `System.Decimal`. The default value of decimal is equivalent to the literal `0D`.\n\n* The `Boolean` value type, which represents a truth value, typically the result of a relational or logical operation. The literal is of type `System.Boolean`. The default value of the `Boolean` type is equivalent to the literal `False`.\n\n* The `Date` value type, which represents a date and/or a time and maps to `System.DateTime`. The default value of the `Date` type is equivalent to the literal `# 01/01/0001 12:00:00AM #`.\n\n* The `Char` value type, which represents a single Unicode character and maps to `System.Char`. The default value of the `Char` type is equivalent to the constant expression `ChrW(0)`.\n\n* The `String` reference type, which represents a sequence of Unicode characters and maps to `System.String`. The default value of the `String` type is a null value.\n\n\n\n## Enumerations\n\n*Enumerations* are value types that inherit from `System.Enum` and symbolically represent a set of values of one of the primitive integral types.\n\n```antlr\nEnumDeclaration\n    : Attributes? TypeModifier* 'Enum' Identifier\n      ( 'As' NonArrayTypeName )? StatementTerminator\n      EnumMemberDeclaration+\n      'End' 'Enum' StatementTerminator\n    ;\n```\n\nFor an enumeration type `E`, the default value is the value produced by the expression `CType(0, E)`.\n\nThe underlying type of an enumeration must be an integral type that can represent all the enumerator values defined in the enumeration. If an underlying type is specified, it must be `Byte`, `SByte`, `UShort`, `Short`, `UInteger`, `Integer`, `ULong`, `Long`, or one of their corresponding types in the `System` namespace. If no underlying type is explicitly specified, the default is `Integer`.\n\nThe following example declares an enumeration with an underlying type of `Long`:\n\n```vb\nEnum Color As Long\n    Red\n    Green\n    Blue\nEnd Enum\n```\n\nA developer might choose to use an underlying type of `Long`, as in the example, to enable the use of values that are in the range of `Long`, but not in the range of `Integer`, or to preserve this option for the future.\n\n\n### Enumeration Members\n\nThe members of an enumeration are the enumerated values declared in the enumeration and the members inherited from class `System.Enum`.\n\nThe scope of an enumeration member is the enumeration declaration body. This means that outside of an enumeration declaration, an enumeration member must always be qualified (unless the type is specifically imported into a namespace through a namespace import).\n\nDeclaration order for enumeration member declarations is significant when constant expression values are omitted. Enumeration members implicitly have `Public` access only; no access modifiers are allowed on enumeration member declarations.\n\n```antlr\nEnumMemberDeclaration\n    : Attributes? Identifier ( Equals ConstantExpression )? StatementTerminator\n    ;\n```\n\n### Enumeration Values\n\nThe enumerated values in an enumeration member list are declared as constants typed as the underlying enumeration type, and they can appear wherever constants are required. An enumeration member definition with `=` gives the associated member the value indicated by the constant expression. The constant expression must evaluate to an integral type that is implicitly convertible to the underlying type and must be within the range of values that can be represented by the underlying type. The following example is in error because the constant values `1.5`, `2.3`, and `3.3` are not implicitly convertible to the underlying integral type `Long` with strict semantics.\n\n```vb\nOption Strict On\n\nEnum Color As Long\n    Red = 1.5\n    Green = 2.3\n    Blue = 3.3\nEnd Enum\n```\n\nMultiple enumeration members may share the same associated value, as shown below:\n\n```vb\nEnum Color\n    Red\n    Green\n    Blue\n    Max = Blue\nEnd Enum\n```\n\nThe example shows an enumeration that has two enumeration members -- `Blue` and `Max` -- that have the same associated value.\n\nIf the first enumerator value definition in the enumeration has no initializer, the value of the corresponding constant is `0`. An enumeration value definition without an initializer gives the enumerator the value obtained by increasing the value of the previous enumeration value by `1`. This increased value must be within the range of values that can be represented by the underlying type.\n\n```vb\nEnum Color\n    Red\n    Green = 10\n    Blue\nEnd Enum \n\nModule Test\n    Sub Main()\n        Console.WriteLine(StringFromColor(Color.Red))\n        Console.WriteLine(StringFromColor(Color.Green))\n        Console.WriteLine(StringFromColor(Color.Blue))\n    End Sub\n\n    Function StringFromColor(c As Color) As String\n        Select Case c\n            Case Color.Red\n                Return String.Format(\"Red = \" & CInt(c))\n\n            Case Color.Green\n                Return String.Format(\"Green = \" & CInt(c))\n\n            Case Color.Blue\n                Return String.Format(\"Blue = \" & CInt(c))\n\n            Case Else\n                Return \"Invalid color\"\n        End Select\n    End Function\nEnd Module\n```\n\nThe example above prints the enumeration values and their associated values. The output is:\n\n```console\nRed = 0\nGreen = 10\nBlue = 11\n```\n\nThe reasons for the values are as follows:\n\n* The enumeration value `Red` is automatically assigned the value `0` (since it has no initializer and is the first enumeration value member).\n\n* The enumeration value `Green` is explicitly given the value `10`.\n\n* The enumeration value `Blue` is automatically assigned the value one greater than the enumeration value that textually precedes it.\n\nThe constant expression may not directly or indirectly use the value of its own associated enumeration value (that is, circularity in the constant expression is not allowed). The following example is invalid because the declarations of `A` and `B` are circular.\n\n```vb\nEnum Circular\n    A = B\n    B\nEnd Enum\n```\n\n`A` depends on `B` explicitly, and `B` depends on `A` implicitly.\n\n## Classes\n\nA *class* is a data structure that may contain data members (constants, variables, and events), function members (methods, properties, indexers, operators, and constructors), and nested types. Classes are reference types.\n\n```antlr\nClassDeclaration\n    : Attributes? ClassModifier* 'Class' Identifier TypeParameterList? StatementTerminator\n      ClassBase?\n      TypeImplementsClause*\n      ClassMemberDeclaration*\n      'End' 'Class' StatementTerminator\n    ;\n\nClassModifier\n    : TypeModifier\n    | 'MustInherit'\n    | 'NotInheritable'\n    | 'Partial'\n    ;\n```\n\nThe following example shows a class that contains each kind of member:\n\n```vb\nClass AClass\n    Public Sub New()\n        Console.WriteLine(\"Constructor\")\n    End Sub\n\n    Public Sub New(value As Integer)\n        MyVariable = value\n        Console.WriteLine(\"Constructor\")\n    End Sub\n\n    Public Const MyConst As Integer = 12\n    Public MyVariable As Integer = 34\n\n    Public Sub MyMethod()\n        Console.WriteLine(\"MyClass.MyMethod\")\n    End Sub\n\n    Public Property MyProperty() As Integer\n        Get\n            Return MyVariable\n        End Get\n\n        Set (value As Integer)\n            MyVariable = value\n        End Set\n    End Property\n\n    Default Public Property Item(index As Integer) As Integer\n        Get\n            Return 0\n        End Get\n\n        Set (value As Integer)\n            Console.WriteLine(\"Item(\" & index & \") = \" & value)\n        End Set\n    End Property\n\n    Public Event MyEvent()\n\n    Friend Class MyNestedClass\n    End Class \nEnd Class\n```\n\nThe following example shows uses of these members:\n\n```vb\nModule Test\n\n    ' Event usage.\n    Dim WithEvents aInstance As AClass\n\n    Sub Main()\n        ' Constructor usage.\n        Dim a As AClass = New AClass()\n        Dim b As AClass = New AClass(123)\n\n        ' Constant usage.\n        Console.WriteLine(\"MyConst = \" & AClass.MyConst)\n\n        ' Variable usage.\n        a.MyVariable += 1\n        Console.WriteLine(\"a.MyVariable = \" & a.MyVariable)\n\n        ' Method usage.\n        a.MyMethod()\n\n        ' Property usage.\n        a.MyProperty += 1\n        Console.WriteLine(\"a.MyProperty = \" & a.MyProperty)\n        a(1) = 1\n\n        ' Event usage.\n        aInstance = a\n    End Sub \n\n    Sub MyHandler() Handles aInstance.MyEvent\n        Console.WriteLine(\"Test.MyHandler\")\n    End Sub \nEnd Module\n```\n\nThere are two class-specific modifiers, `MustInherit` and `NotInheritable`. It is invalid to specify them both.\n\n\n### Class Base Specification\n\nA class declaration may include a base type specification that defines the direct base type of the class.\n\n```antlr\nClassBase\n    : 'Inherits' NonArrayTypeName StatementTerminator\n    ;\n```\n\nIf a class declaration has no explicit base type, the direct base type is implicitly `Object`. For example:\n\n```vb\nClass Base\nEnd Class\n\nClass Derived\n    Inherits Base\nEnd Class\n```\n\nBase types cannot be a type parameter on its own, although it may involve the type parameters that are in scope.\n\n```vb\nClass C1(Of V) \nEnd Class\n\nClass C2(Of V)\n    Inherits V    ' Error, type parameter used as base class \nEnd Class\n\nClass C3(Of V)\n    Inherits C1(Of V)    ' OK: not directly inheriting from V.\nEnd Class\n```\n\nClasses may only derive from `Object` and classes. It is invalid for a class to derive from `System.ValueType`, `System.Enum`, `System.Array`, `System.MulticastDelegate` or `System.Delegate`. A generic class cannot derive from `System.Attribute` or from a class that derives from it.\n\nEvery class has exactly one direct base class, and circularity in derivation is prohibited. It is not possible to derive from a `NotInheritable` class, and the accessibility domain of the base class must be the same as or a superset of the accessibility domain of the class itself.\n\n\n### Class Members\n\nThe members of a class consist of the members introduced by its class member declarations and the members inherited from its direct base class.\n\n```antlr\nClassMemberDeclaration\n    : NonModuleDeclaration\n    | EventMemberDeclaration\n    | VariableMemberDeclaration\n    | ConstantMemberDeclaration\n    | MethodMemberDeclaration\n    | PropertyMemberDeclaration\n    | ConstructorMemberDeclaration\n    | OperatorDeclaration\n    ;\n```\n\nA class member declaration may have `Public`, `Protected`, `Friend`, `Protected Friend`, or `Private` access. When a class member declaration does not include an access modifier, the declaration defaults to `Public` access, unless it is a variable declaration; in that case it defaults to `Private` access.\n\nThe scope of a class member is the class body in which the member declaration occurs, plus the constraint list of that class (if it is generic and has constraints). If the member has `Friend` access, its scope extends to the class body of any derived class in the same program or any assembly that has been given `Friend` access, and if the member has `Public`, `Protected`, or `Protected Friend` access, its scope extends to the class body of any derived class in any program.\n\n\n## Structures\n\n*Structures* are value types that inherit from `System.ValueType`. Structures are similar to classes in that they represent data structures that can contain data members and function members. Unlike classes, however, structures do not require heap allocation.\n\n```antlr\nStructureDeclaration\n    : Attributes? StructureModifier* 'Structure' Identifier\n      TypeParameterList? StatementTerminator\n      TypeImplementsClause*\n      StructMemberDeclaration*\n      'End' 'Structure' StatementTerminator\n    ;\n\nStructureModifier\n    : TypeModifier\n    | 'Partial'\n    ;\n```\n\nIn the case of classes, it is possible for two variables to reference the same object, and thus possible for operations on one variable to affect the object referenced by the other variable. With structures, the variables each have their own copy of the non-`Shared` data, so it is not possible for operations on one to affect the other, as the following example illustrates:\n\n```vb\nStructure Point\n    Public x, y As Integer\n\n    Public Sub New(x As Integer, y As Integer)\n        Me.x = x\n        Me.y = y\n    End Sub\nEnd Structure\n```\n\nGiven the above declaration the following code outputs the value `10`:\n\n```vb\nModule Test\n    Sub Main()\n        Dim a As New Point(10, 10)\n        Dim b As Point = a\n\n        a.x = 100\n        Console.WriteLine(b.x)\n    End Sub\nEnd Module\n```\n\nThe assignment of `a` to `b` creates a copy of the value, and `b` is thus unaffected by the assignment to `a.x`. Had `Point` instead been declared as a class, the output would be `100` because `a` and `b` would reference the same object.\n\n\n### Structure Members\n\nThe members of a structure are the members introduced by its structure member declarations and the members inherited from `System.ValueType`.\n\n```antlr\nStructMemberDeclaration\n    : NonModuleDeclaration\n    | VariableMemberDeclaration\n    | ConstantMemberDeclaration\n    | EventMemberDeclaration\n    | MethodMemberDeclaration\n    | PropertyMemberDeclaration\n    | ConstructorMemberDeclaration\n    | OperatorDeclaration\n    ;\n```\n\nEvery structure implicitly has a `Public` parameterless instance constructor that produces the default value of the structure. As a result, it is not possible for a structure type declaration to declare a parameterless instance constructor. A structure type is, however, permitted to declare *parameterized* instance constructors, as in the following example:\n\n```vb\nStructure Point\n    Private x, y As Integer\n\n    Public Sub New(x As Integer, y As Integer)\n        Me.x = x\n        Me.y = y\n    End Sub\nEnd Structure\n```\n\nGiven the above declaration, the following statements both create a `Point` with `x` and `y` initialized to zero.\n\n```vb\nDim p1 As Point = New Point()\nDim p2 As Point = New Point(0, 0)\n```\n\nBecause structures directly contain their field values (rather than references to those values), structures cannot contain fields that directly or indirectly reference themselves. For example, the following code is not valid:\n\n```vb\nStructure S1\n    Dim f1 As S2\nEnd Structure\n\nStructure S2\n    ' This would require S1 to contain itself.\n    Dim f1 As S1\nEnd Structure\n```\n\nNormally, a structure member declaration may only have `Public`, `Friend`, or `Private` access, but when overriding members inherited from `Object`, `Protected` and `Protected Friend` access may also be used. When a structure member declaration does not include an access modifier, the declaration defaults to `Public` access. The scope of a member declared by a structure is the structure body in which the declaration occurs, plus the constraints of that structure (if it was generic and had constraints).\n\n\n## Standard Modules\n\nA *standard module* is a type whose members are implicitly `Shared` and scoped to the declaration space of the standard module's containing namespace, rather than just to the standard module declaration itself. Standard modules may never be instantiated. It is an error to declare a variable of a standard module type.\n\n```antlr\nModuleDeclaration\n    : Attributes? TypeModifier* 'Module' Identifier StatementTerminator\n      ModuleMemberDeclaration*\n      'End' 'Module' StatementTerminator\n    ;\n```\n\nA member of a standard module has two fully qualified names, one without the standard module name and one with the standard module name. More than one standard module in a namespace may define a member with a particular name; unqualified references to the name outside of either module are ambiguous. For example:\n\n```vb\nNamespace N1\n    Module M1\n        Sub S1()\n        End Sub\n\n        Sub S2()\n        End Sub\n    End Module\n\n    Module M2\n        Sub S2()\n        End Sub\n    End Module\n\n    Module M3\n        Sub Main()\n            S1()       ' Valid: Calls N1.M1.S1.\n            N1.S1()    ' Valid: Calls N1.M1.S1.\n            S2()       ' Not valid: ambiguous.\n            N1.S2()    ' Not valid: ambiguous.\n            N1.M2.S2() ' Valid: Calls N1.M2.S2.\n        End Sub\n    End Module\nEnd Namespace\n```\n\nA module may only be declared in a namespace and may not be nested in another type. Standard modules may not implement interfaces, they implicitly derive from `Object`, and they have only `Shared` constructors.\n\n\n### Standard Module Members\n\nThe members of a standard module are the members introduced by its member declarations and the members inherited from `Object`. Standard modules may have any type of member except instance constructors. All standard module type members are implicitly `Shared`.\n\n```antlr\nModuleMemberDeclaration\n    : NonModuleDeclaration\n    | VariableMemberDeclaration\n    | ConstantMemberDeclaration\n    | EventMemberDeclaration\n    | MethodMemberDeclaration\n    | PropertyMemberDeclaration\n    | ConstructorMemberDeclaration\n    ;\n```\n\nNormally, a standard module member declaration may only have `Public`, `Friend`, or `Private` access, but when overriding members inherited from `Object`, the `Protected` and `Protected Friend` access modifiers may be specified. When a standard module member declaration does not include an access modifier, the declaration defaults to `Public` access, unless it is a variable, which defaults to `Private` access.\n\nAs previously noted, the scope of a standard module member is the declaration containing the standard module declaration. Members inherited from `Object` are not included in this special scoping; those members have no scope and must always be qualified with the name of the module. If the member has `Friend` access, its scope extends only to namespace members declared in the same program or assemblies that have been given `Friend` access.\n\n\n## Interfaces\n\n*Interfaces* are reference types that other types implement to guarantee that they support certain methods. An interface is never directly created and has no actual representation -- other types must be converted to an interface type. An interface defines a contract. A class or structure that implements an interface must adhere to its contract.\n\n```antlr\nInterfaceDeclaration\n    : Attributes? TypeModifier* 'Interface' Identifier\n      TypeParameterList? StatementTerminator\n      InterfaceBase*\n      InterfaceMemberDeclaration*\n      'End' 'Interface' StatementTerminator\n    ;\n```\n\n\nThe following example shows an interface that contains a default property `Item`, an event `E`, a method `F`, and a property `P`:\n\n```vb\nInterface IExample\n    Default Property Item(index As Integer) As String\n\n    Event E()\n\n    Sub F(value As Integer)\n\n    Property P() As String\nEnd Interface\n```\n\nInterfaces may employ multiple inheritance. In the following example, the interface `IComboBox` inherits from both `ITextBox` and `IListBox`:\n\n```vb\nInterface IControl\n    Sub Paint()\nEnd Interface \n\nInterface ITextBox\n    Inherits IControl\n\n    Sub SetText(text As String)\nEnd Interface \n\nInterface IListBox\n    Inherits IControl\n\n    Sub SetItems(items() As String)\nEnd Interface \n\nInterface IComboBox\n    Inherits ITextBox, IListBox \nEnd Interface\n```\n\nClasses and structures can implement multiple interfaces. In the following example, the class `EditBox` derives from the class `Control` and implements both `IControl` and `IDataBound`:\n\n```vb\nInterface IDataBound\n    Sub Bind(b As Binder)\nEnd Interface \n\nPublic Class EditBox\n    Inherits Control\n    Implements IControl, IDataBound\n\n    Public Sub Paint() Implements IControl.Paint\n        ...\n    End Sub\n\n    Public Sub Bind(b As Binder) Implements IDataBound.Bind\n        ...\n    End Sub\nEnd Class\n```\n\n\n### Interface Inheritance\n\nThe base interfaces of an interface are the explicit base interfaces and their base interfaces. In other words, the set of base interfaces is the complete transitive closure of the explicit base interfaces, their explicit base interfaces, and so on. If an interface declaration has no explicit interface base, then there is no base interface for the type -- interfaces do not inherit from `Object` (although they do have a widening conversion to `Object`).\n\n```antlr\nInterfaceBase\n    : 'Inherits' InterfaceBases StatementTerminator\n    ;\n\nInterfaceBases\n    : NonArrayTypeName ( Comma NonArrayTypeName )*\n    ;\n```\n\nIn the following example, the base interfaces of `IComboBox` are `IControl`, `ITextBox`, and `IListBox`.\n\n```vb\nInterface IControl\n    Sub Paint()\nEnd Interface \n\nInterface ITextBox\n    Inherits IControl\n\n    Sub SetText(text As String)\nEnd Interface \n\nInterface IListBox\n    Inherits IControl\n\n    Sub SetItems(items() As String)\nEnd Interface \n\nInterface IComboBox\n    Inherits ITextBox, IListBox \nEnd Interface\n```\n\nAn interface inherits all members of its base interfaces. In other words, the `IComboBox` interface above inherits members `SetText` and `SetItems` as well as `Paint`.\n\nA class or structure that implements an interface also implicitly implements all of the interface's base interfaces.\n\nIf an interface appears more than once in the transitive closure of the base interfaces, it only contributes its members to the derived interface once. A type implementing the derived interface only has to implement the methods of the multiply defined base interface once. In the following example, `Paint` only needs to be implemented once, even though the class implements `IComboBox` and `IControl`.\n\n```vb\nClass ComboBox\n    Implements IControl, IComboBox\n\n    Sub SetText(text As String) Implements IComboBox.SetText\n    End Sub\n\n    Sub SetItems(items() As String) Implements IComboBox.SetItems\n    End Sub\n\n    Sub Print() Implements IComboBox.Paint\n    End Sub\nEnd Class\n```\n\nAn `Inherits` clause has no effect on other `Inherits` clauses. In the following example, `IDerived` must qualify the name of `INested` with `IBase`.\n\n```vb\nInterface IBase\n    Interface INested\n        Sub Nested()\n    End Interface\n\n    Sub Base()\nEnd Interface\n\nInterface IDerived\n    Inherits IBase, INested   ' Error: Must specify IBase.INested.\nEnd Interface\n```\n\nThe accessibility domain of a base interface must be the same as or a superset of the accessibility domain of the interface itself.\n\n\n### Interface Members\n\nThe members of an interface consist of the members introduced by its member declarations and the members inherited from its base interfaces.\n\n```antlr\nInterfaceMemberDeclaration\n    : NonModuleDeclaration\n    | InterfaceEventMemberDeclaration\n    | InterfaceMethodMemberDeclaration\n    | InterfacePropertyMemberDeclaration\n    ;\n```\n\nAlthough interfaces do not inherit members from `Object`, because every class or structure that implements an interface does inherit from `Object`, the members of `Object`, including extension methods, are considered members of an interface and can be called on an interface directly without requiring a cast to `Object`. For example:\n\n```vb\nInterface I1\nEnd Interface\n\nClass C1\n    Implements I1\nEnd Class\n\nModule Test\n    Sub Main()\n        Dim i As I1 = New C1()\n        Dim h As Integer = i.GetHashCode()\n    End Sub\nEnd Module\n```\n\nMembers of an interface with the same name as members of `Object` implicitly shadow `Object` members. Only nested types, methods, properties, and events may be members of an interface. Methods and properties may not have a body. Interface members are implicitly `Public` and may not specify an access modifier. The scope of a member declared in an interface is the interface body in which the declaration occurs, plus the constraint list of that interface (if it is generic and has constraints).\n\n\n## Arrays\n\nAn *array* is a reference type that contains variables accessed through *indices* corresponding in a one-to-one fashion with the order of the variables in the array. The variables contained in an array, also called the *elements* of the array, must all be of the same type, and this type is called the *element type* of the array.\n\n```antlr\nArrayTypeName\n    : NonArrayTypeName ArrayTypeModifiers\n    ;\n\nArrayTypeModifiers\n    : ArrayTypeModifier+\n    ;\n\nArrayTypeModifier\n    : OpenParenthesis RankList? CloseParenthesis\n    ;\n\nRankList\n    : Comma*\n    ;\n\nArrayNameModifier\n    : ArrayTypeModifiers\n    | ArraySizeInitializationModifier\n    ;\n```\n\nThe elements of an array come into existence when an array instance is created, and cease to exist when the array instance is destroyed. Each element of an array is initialized to the default value of its type. The type `System.Array` is the base type of all array types and may not be instantiated. Every array type inherits the members declared by the `System.Array` type and is convertible to it (and `Object`). A one-dimensional array type with element `T` also implements the interfaces `System.Collections.Generic.IList(Of T)` and `IReadOnlyList(Of T)`; if `T` is a reference type, then the array type also implements `IList(Of U)` and `IReadOnlyList(Of U)` for any `U` that has a widening  reference conversion from `T`.\n\nAn array has a *rank* that determines the number of indices associated with each array element. The rank of an array determines the number of *dimensions* of the array. For example, an array with a rank of one is called a single-dimensional array, and an array with a rank greater than one is called a multidimensional array.\n\nThe following example creates a single-dimensional array of integer values, initializes the array elements, and then prints each of them out:\n\n```vb\nModule Test\n    Sub Main()\n        Dim arr(5) As Integer\n        Dim i As Integer\n\n        For i = 0 To arr.Length - 1\n            arr(i) = i * i\n        Next i\n\n        For i = 0 To arr.Length - 1\n            Console.WriteLine(\"arr(\" & i & \") = \" & arr(i))\n        Next i\n    End Sub\nEnd Module\n```\n\nThe program outputs the following:\n\n```console\narr(0) = 0\narr(1) = 1\narr(2) = 4\narr(3) = 9\narr(4) = 16\narr(5) = 25\n```\n\nEach dimension of an array has an associated length. Dimension lengths are not part of the type of the array, but rather are established when an instance of the array type is created at run time. The length of a dimension determines the valid range of indices for that dimension: for a dimension of length `N`, indices can range from zero to `N-1`. If a dimension is of length zero, there are no valid indices for that dimension. The total number of elements in an array is the product of the lengths of each dimension in the array. If any of the dimensions of an array has a length of zero, the array is said to be empty. The element type of an array can be any type.\n\nArray types are specified by adding a modifier to an existing type name. The modifier consists of a left parenthesis, a set of zero or more commas, and a right parenthesis. The type modified is the element type of the array, and the number of dimensions is the number of commas plus one. If more than one modifier is specified, then the element type of the array is an array. The modifiers are read left to right, with the leftmost modifier being the outermost array. In the example\n\n```vb\nModule Test\n    Dim arr As Integer(,)(,,)()\nEnd Module\n```\n\nthe element type of `arr` is a two-dimensional array of three-dimensional arrays of one-dimensional arrays of `Integer`.\n\nA variable may also be declared to be of an array type by putting an array type modifier or an array-size initialization modifier on the variable name. In that case, the array element type is the type given in the declaration, and the array dimensions are determined by the variable name modifier. For clarity, it is not valid to have an array type modifier on both a variable name and a type name in the same declaration.\n\nThe following example shows a variety of local variable declarations that use array types with `Integer` as the element type:\n\n```vb\nModule Test\n    Sub Main()\n        Dim a1() As Integer    ' Declares 1-dimensional array of integers.\n        Dim a2(,) As Integer   ' Declares 2-dimensional array of integers.\n        Dim a3(,,) As Integer  ' Declares 3-dimensional array of integers.\n\n        Dim a4 As Integer()    ' Declares 1-dimensional array of integers.\n        Dim a5 As Integer(,)   ' Declares 2-dimensional array of integers.\n        Dim a6 As Integer(,,)  ' Declares 3-dimensional array of integers.\n\n        ' Declare 1-dimensional array of 2-dimensional arrays of integers \n        Dim a7()(,) As Integer\n        ' Declare 2-dimensional array of 1-dimensional arrays of integers.\n        Dim a8(,)() As Integer\n\n        Dim a9() As Integer() ' Not allowed.\n    End Sub\nEnd Module\n```\n\nAn array type name modifier extends to all sets of parentheses that follow it. This means that in the situations where a set of arguments enclosed in parenthesis is allowed after a type name, it is not possible to specify the arguments for an array type name. For example:\n\n```vb\nModule Test\n    Sub Main()\n        ' This calls the Integer constructor.\n        Dim x As New Integer(3)\n\n        ' This declares a variable of Integer().\n        Dim y As Integer()\n\n        ' This gives an error.\n        ' Array sizes can not be specified in a type name.\n        Dim z As Integer()(3)\n    End Sub\nEnd Module\n```\n\nIn the last case, `(3)` is interpreted as part of the type name rather than as a set of constructor arguments.\n\n\n## Delegates\n\nA *delegate* is a reference type that refers to a `Shared` method of a type or to an instance method of an object.\n\n```antlr\nDelegateDeclaration\n    : Attributes? TypeModifier* 'Delegate' MethodSignature StatementTerminator\n    ;\n\nMethodSignature\n    : SubSignature\n    | FunctionSignature\n    ;\n```\n\n The closest equivalent of a delegate in other languages is a function pointer, but whereas a function pointer can only reference `Shared` functions, a delegate can reference both `Shared` and instance methods. In the latter case, the delegate stores not only a reference to the method's entry point, but also a reference to the object instance with which to invoke the method.\n\nThe delegate declaration may not have  a `Handles` clause, an `Implements` clause, a method body, or an `End` construct. The parameter list of the delegate declaration may not contain `Optional` or `ParamArray` parameters. The accessibility domain of the return type and parameter types must be the same as or a superset of the accessibility domain of the delegate itself.\n\nThe members of a delegate are the members inherited from class `System.Delegate`. A delegate also defines the following methods:\n\n* A constructor that takes two parameters, one of type `Object` and one of type `System.IntPtr`.\n\n* An `Invoke` method that has the same signature as the delegate.\n\n* A `BeginInvoke` method whose signature is the delegate signature, with three differences. First, the return type is changed to `System.IAsyncResult`. Second, two additional parameters are added to the end of the parameter list: the first of type `System.AsyncCallback` and the second of type `Object`. And finally, all `ByRef` parameters are changed to be `ByVal`.\n\n* An `EndInvoke` method whose return type is the same as the delegate. The parameters of the method are only the delegate parameters exactly that are `ByRef` parameters, in the same order they occur in the delegate signature.  In addition to those parameters, there is an additional parameter of type `System.IAsyncResult` at the end of the parameter list.\n\nThere are three steps in defining and using delegates: declaration, instantiation, and invocation.\n\nDelegates are declared using delegate declaration syntax. The following example declares a delegate named `SimpleDelegate` that takes no arguments:\n\n```vb\nDelegate Sub SimpleDelegate()\n```\n\nThe next example creates a `SimpleDelegate` instance and then immediately calls it:\n\n```vb\nModule Test\n    Sub F()\n        System.Console.WriteLine(\"Test.F\")\n    End Sub \n\n    Sub Main()\n        Dim d As SimpleDelegate = AddressOf F\n        d()\n    End Sub \nEnd Module\n```\n\nThere is not much point in instantiating a delegate for a method and then immediately calling via the delegate, as it would be simpler to call the method directly. Delegates show their usefulness when their anonymity is used. The next example shows a `MultiCall` method that repeatedly calls a `SimpleDelegate` instance:\n\n```vb\nSub MultiCall(d As SimpleDelegate, count As Integer)\n    Dim i As Integer\n\n    For i = 0 To count - 1\n        d()\n    Next i\nEnd Sub\n```\n\nIt is unimportant to the `MultiCall` method what the target method for the `SimpleDelegate` is, what accessibility this method has, or whether the method is `Shared` or not. All that matters is that the signature of the target method is compatible with `SimpleDelegate`.\n\n\n## Partial types\n\nClass and structure declarations can be *partial* declarations. A partial declaration may or may not fully describe the declared type within the declaration. Instead, the declaration of the type may be spread across multiple partial declarations within the program; partial types cannot be declared across program boundaries. A partial type declaration specifies the `Partial` modifier on the declaration. Then, any other declarations in the program for a type with the same fully-qualified name will be merged together with the partial declaration at compile-time to form a single type declaration. For example, the following code declares a single class `Test` with members `Test.C1` and `Test.C2`.\n\na.vb:\n\n```vb\nPublic Partial Class Test\n    Public Sub S1()\n    End Sub\nEnd Class\n```\n\nb.vb:\n\n```vb\nPublic Class Test\n    Public Sub S2()\n    End Sub\nEnd Class\n```\n\nWhen combining partial type declarations, at least one of the declarations must have a `Partial` modifier, otherwise a compile-time error results.\n\n__Note.__ Although it is possible to specify `Partial` on only one declaration among many partial declarations, it is better form to specify it on all partial declarations. In the situation where one partial declaration is visible but one or more partial declarations are hidden (such as the case of extending tool-generated code), it is acceptable to leave the `Partial` modifier off of the visible declaration but specify it on the hidden declarations.\n\nOnly classes and structures can be declared using partial declarations. The arity of a type is considered when matching partial declarations together: two classes with the same name but different numbers of type parameters are not considered to be partial declarations of the same time. Partial declarations can specify attributes, class modifiers, `Inherits` statement or `Implements` statement. At compile time, all of the pieces of the partial declarations are combined together and used as a part of the type declaration. If there are any conflicts between attributes, modifiers, bases, interfaces, or type members, a compile-time error results. For example:\n\n```vb\nPublic Partial Class Test1\n    Implements IDisposable\nEnd Class\n\nClass Test1\n    Inherits Object\n    Implements IComparable\nEnd Class\n\nPublic Partial Class Test2\nEnd Class\n\nPrivate Partial Class Test2\nEnd Class\n```\n\nThe previous example declares a type `Test1` that is `Public`, inherits from `Object` and implements `System.IDisposable` and `System.IComparable`. The partial declarations of `Test2` will cause a compile-time error because one of the declarations says that `Test2` is `Public` and another says that `Test2` is `Private`.\n\nPartial types with type parameters can declare constraints and variance for the type parameters, but the constraints and variance from each partial declaration must match. Thus, constraints and variance are special in that they are not automatically combined like other modifiers:\n\n```vb\nPartial Public Class List(Of T As IEnumerable)\nEnd Class\n\n' Error: Constraints on T don't match\nClass List(Of T As IComparable)\nEnd Class\n```\n\nThe fact that a type is declared using multiple partial declarations does not affect the name lookup rules within the type. As a result, a partial type declaration can use members declared in other partial type declarations, or may implement methods on interfaces declared in other partial type declarations. For example:\n\n```vb\nPublic Partial Class Test1\n    Implements IDisposable\n\n    Private IsDisposed As Boolean = False\nEnd Class\n\nClass Test1\n    Private Sub Dispose() Implements IDisposable.Dispose\n        If Not IsDisposed Then\n            ...\n        End If\n    End Sub\nEnd Class\n```\n\nNested types can have partial declarations as well. For example:\n\n```vb\nPublic Partial Class Test\n    Public Partial Class NestedTest\n        Public Sub S1()\n        End Sub\n    End Class\nEnd Class\n\nPublic Partial Class Test\n    Public Partial Class NestedTest\n        Public Sub S2()\n        End Sub\n    End Class\nEnd Class\n```\n\nInitializers within a partial declaration will still be executed in declaration order; however, there is no guaranteed order of execution for initializers that occur in separate partial declarations.\n\n## Constructed Types\n\nA generic type declaration, by itself, does not denote a type. Instead, a generic type declaration can be used as a \"blueprint\" to form many different types by applying type arguments. A generic type that has type arguments applied to it is called a *constructed type*. The type arguments in a constructed type must always satisfy the constraints placed on the type parameters they match to.\n\nA type name might identify a constructed type even though it doesn't specify type parameters directly. This can occur where a type is nested within a generic class declaration, and the instance type of the containing declaration is implicitly used for name lookup:\n\n```vb\nClass Outer(Of T) \n    Public Class Inner \n    End Class\n\n    ' Type of i is the constructed type Outer(Of T).Inner\n    Public i As Inner \nEnd Class\n```\n\nA constructed type `C(Of T1,...,Tn)` is accessible when the generic type and all the type arguments are accessible. For instance, if the generic type `C` is `Public` and all of the type arguments `T1,...,Tn` are `Public`, then the constructed type is `Public`. If either the type name or one of the type arguments is `Private`, however, then the accessibility of the constructed type is `Private`. If one type argument of the constructed type is `Protected` and another type argument is `Friend`, then the constructed type is accessible only in the class and its subclasses in this assembly or any assembly that has been given `Friend` access. In other words, the accessibility domain for a constructed type is the intersection of the accessibility domains of its constituent parts.\n\n__Note.__ The fact that the accessibility domain of constructed type is the intersection of its constituted parts has the interesting side effect of defining a new accessibility level. A constructed type that contains an element that is `Protected` and an element that is `Friend` can only be accessed in contexts that can access *both* `Friend` *and* `Protected` members. However, there is no way to express this accessibility level in the language, as the accessibility `Protected Friend` means that an entity can be accessed in a context that can access *either* `Friend` *or* `Protected` members.\n\nThe base, implemented interfaces and members of constructed types are determined by substituting the supplied type arguments for each occurrence of the type parameter in the generic type.\n\n### Open Types and Closed Types\n\nA constructed type for who one or more type arguments are type parameters of a containing type or method is called an *open type*. This is because some of the type parameters of the type are still not known, so the actual shape of the type is not yet fully known. In contrast, a generic type whose type arguments are all non-type parameters is called a *closed type*. The shape of a closed type is always fully known. For example:\n\n```vb\nClass Base(Of T, V)\nEnd Class\n\nClass Derived(Of V)\n    Inherits Base(Of Integer, V)\nEnd Class\n\nClass MoreDerived\n    Inherits Derived(Of Double)\nEnd Class\n```\n\nThe constructed type `Base(Of Integer, V)` is an open type because although the type parameter `T` has been supplied, the type parameter `U` has been supplied another type parameter. Thus, the full shape of the type is not yet known. The constructed type `Derived(Of Double)`, however, is a closed type because all type parameters in the inheritance hierarchy have been supplied.\n\nOpen types are defined as follows:\n\n* A type parameter is an open type.\n\n* An array type is an open type if its element type is an open type.\n\n* A constructed type is an open type if one or more of its type arguments are an open type.\n\n* A closed type is a type that is not an open type.\n\nBecause the program entry point cannot be in a generic type, all types used at run-time will be closed types.\n\n## Special Types\n\nThe .NET Framework contains a number of classes that are treated specially by the .NET Framework and by the Visual Basic language:\n\nThe type `System.Void`, which represents a void type in the .NET Framework, can be directly referenced only in `GetType` expressions.\n\nThe types `System.RuntimeArgumentHandle`, `System.ArgIterator` and `System.TypedReference` all can contain pointers into the stack and so cannot appear on the .NET Framework heap. Therefore, they cannot be used as array element types, return types, field types, generic type arguments, nullable types, `ByRef` parameter types, the type of a value being converted to `Object` or `System.ValueType`, the target of a call to instance members of `Object` or `System.ValueType`, or lifted into a closure.\n"
  }
]