How does MessageBoxIcon Enumeration manage to have Error as part of it - vb.net

I would like to create an Enumeration, one item of which would be Error. As Error is a keyword the compiler, as expected, points out that that is not on. As I have Option Strict On on by default I thought that possibly this would be one instance where setting it specifically to off would help. However it doesn't.
So put very simply how does the MessageBoxIcon manage to use Error as an item in its enumeration?

Enclose the Error keyword in square brackets
Public Enum SimpleSettings
[Error] = 0
Warn = 1
Correct = 2
End Enum
From the VB.NET Language specifications
Regular identifiers may not match keywords, but escaped identifiers
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.

Try something like this:
Public Enum Foo
Bar
Faa
[Error]
End Enum

Related

Assign Bang argument programmatically?

I'm not successful in using the Bang (!) operator without it's argument being hardcoded, i.e., Me.VBProject.References!Excel. In this example, the Excel reference is hardcoded.
Out of frustration I've tried all permutations I can think of in an attempt to utilize it:
[Me.VBProject.References!(str)]
[Me.VBProject.References! & (str)]
["Me.VBProject.References!" & str]
["Me.VBProject.References!" & (str)]
and many more with parens added to ensure proper pre-evaluation including the longhand Application.evaluate method. Nada!
No, you can't do that.
The bang operator is just a shortcut for calling the default member of the object, and passing the text after the bang as a string to the first parameter of the default member:
The bang notation:
Me.VBProject.References!Excel
is exactly equivalent to:
Me.VBProject.References.Item("Excel")
and, because it is the default member, you can omit the Item function call:
Me.VBProject.References("Excel")
So, to use your (really badly named) variable str:
str = "Excel"
Debug.Print Me.VBProject.References.Item(str).Name
This is an X-Y problem.
Bang notation is a means to an end.
It's one of the tools made available to you, to retrieve an item from a collection.
Nothing more, nothing less.
What you want isn't to use the bang operator with a variable.
What you want is to retrieve an item from a collection using a variable.
Collection types have a default member, typically named Item. Default members can be specified explicitly, or implicitly accessed:
Dim foo As New Collection
foo.Add Item:=42, Key:="test"
Debug.Print foo.Item("test") 'explicit reference to the default member
Debug.Print foo("test") 'implicit reference to the same default member
The bang operator is just another way to make an implicit call to the collection's default member:
Debug.Print foo!test
All 3 Debug.Print statements above will call the foo.Item default member to output the 42 associated with the key "test".
Square brackets
As you can see, what comes immediately after the ! operator is really a string literal. Because a string literal can contain whitespace, the VB6/VBA parser needed a way to support them.
That's what the [square brackets] are for:
foo.Add 72, "spaces in the key"
Debug.Print foo![spaces in the key]
When they're not delimiting a string literal for bang notation, square brackets are usually1 interpreted as a run-time expression for the host application to evaluate. For example this is legal (though questionably advisable) in Excel VBA:
Debug.Print [A1]
The VBA parser identifies a bracketed expression and defers its evaluation to the host application - here Excel; at run-time, the instruction ultimately equates to:
Debug.Print ActiveSheet.Range("A1").Value
If you don't believe the evaluation of a bracketed expression is deferred to the host application, consider what needs to happen for this instruction to print 4:
Debug.Print [Sum(2,2)]
Therefore, every single one of the attempts/permutations in your post missed the mark and made Excel try to evaluate an expression that only VBA would be able to resolve, because Me.VBProject.References means absolutely nothing to Excel.
Square-bracket expressions should usually be avoided, because you lose compile-time checks and any error can only be caught at run-time.
1Usually, because they can also be used in some identifiers,
for example in Enum types, to make a [_hidden] enum member.
Bottom Line
Bang notation is a way to retrieve an item from a collection by leveraging default members and making string literals look like an identifier. You can't make it work without "hard-coding" the string literal, because it requires a string literal.
If you want to parameterize the collection retrieval, you can't use the bang operator.
It's useful for typing the code faster. If you don't know exactly how it works and what it does for you though, it's a double-edged blade that hides what's really going on and ultimately makes the code harder to read and understand. Code shouldn't be written just to be run. Code should be written to be read and understood.
Note: Bang notation isn't actually only for collections. It actually passes its argument as a string literal to the first parameter of anything that has a default member. I would strongly advise avoiding it for anything other than a collection class though (e.g. Collection.Item, Workbooks.Item, Worksheets.Item, Recordset.Fields, etc.), for the sake of future maintainers' sanity.

Why am I getting 'Trim' is not declared with this VB.NET code?

I am trying to get a VB.NET app to compile. Besides the "elephant in the room", I'm also getting 7 "'Trim' is not declared" errors on code like this:
...as well as one "'IsNothing' is not declared. It may be inaccessible due to its protection level." on this line:
If IsNothing(memberList) = False Then
I don't know VB, so there may be a simple solution to this, but I have no clue what the problems are.
The Trim function requires a reference to Microsoft.VisualBasic from the assembly Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)
Usually is preferable to use the native Trim method from the string class and not add a reference to this assembly (mainly used to help porting old VB6 apps)
mail.CC.Add(addr.Trim())
Notice also that the string.Trim removes other whitespace characters as tabs while the Microsoft.VisualBasic function does not.
You have to use addr.Trim instead of Trim(addr)
Read more about Trim in this MSDN article
And you should use
If not memberList Is Nothing Then
Instead of
If IsNothing(memberList) = False Then
Or
You have to import Microsoft.VisualBasic namespace
If you use the Left(), Mid(), and Right() string functions you might find it easier to convert those too:
Left(t, l) becomes t.Substring(0, l)
Mid(t, s, l) becomes t.Substring(s-1, l)
Right(t, l) becomes t.Substring(t.Length - l)
Often Left and Right are properties and stop you using the old VB string functions.
String.Trim doesn't take a string parameter. It returns a new string in which all leading and trailing occurrences of a set of specified characters from the current String object are removed.
It should be...
addr.Trim()

VB.NET Brackets () {} [] <>

Can someone please fill in the blanks for me, including a brief description of use and perhaps a code snippet? I'm well aware of the top two in particular, but a little hazy on the last one especially:
() - Used for calling a function, object instantiation, passing parameters, etc.
{} - Used for defining and adding elements to arrays or sets.
[] - Used for forcing an object to be treated as a type rather than keyword.
<> - Used for... ?
For Example, I see stuff like this all the time, but still not quite sure what the brackets means...
<TemplateContainer(GetType(TemplateItem))> _
Public Property MessageTemplate As ITemplate
VB.net uses parentheses for, among other things, arithmetic groupings and function parameters (both of which use parentheses in C#), as well as array subscripts and default-property parameters (both of which use brackets in C#), (indexers), etc. It also uses (Of ... ) to enclose a list of types (which would be enclosed in < ... > in C#, with no "Of" keyword.
Braces are used for array or set initialization expressions, and are also used when defining a generic type with multiple constraints (e.g. (Of Foo As {IEnumerable, IDisposable, Class})). Note that the latter usage is only permitted in constraints; it is alas not possible to e.g. Dim MyThing As {IEnumerable, IDisposable, Class}).
Braces are now also used for the New With {} construct:
Dim p = New Person With {.Name = "John Smith", .Age = 27}
Dim anon = New With {.Name = "Jack Smythe", .Age = 23}
Square brackets are used to enclose identifiers whose spelling would match that of a reserved word. For example, if a class defined a method called Not (perhaps the class was written in a language without a keyword Not), one could use such a method within VB by enclosing its name in square brackets (e.g. someVariable = [Not](5)). In the absence of the square brackets, the above expression would set someVariable to -6 (the result of applying the vb.net Not operator to the value 5).
Angle brackets, as noted elsewhere, are used for attributes. Note that in many cases, attributes are placed on the line above the thing they affect (so as to avoid pushing the affected variable past the right edge of the screen). In older versions of vb, such usage requires the use of a line-continuation mark (trailing underscore).
Angle brackets are also used for XML Literals and XML Axis Properties:
Dim xml = <simpleTag><anotherTag>text</anotherTag></simpleTag>
Console.WriteLine(xml.<anotherTag>.First.Value)
In this case it's used for the Attribute declaration. It can also be used in XML Literals as follows:
<TestMethod>
Public Sub ThisIsATest()
If 1 <> 0 Then
Dim foo = <root>
<child>this is some XML</child>
</root>
End If
End Sub
In VB.Net, <> is used to enclose Attributes.
VB.NET uses <> for attributes as well as to indicate "does not equal" (!=)
In your example it is just enclosing attributes. That same code in C# would be
[TemplateContainer(GetType(TemplateItem))]
public ITemplate MessageTemplate { get; set; }
This attribute is used in developing templated controls, which separate data from presentation. In other words, a templated control can retain the same functionality while changing it's appearance.

what's the meaning of the brackets in Property definition?

What is the meaning of the square brackets around the name of a property in the definition ?
Example :
Public Property [Date] As String
To use reserved keywords as identifiers, the brackets must be used to
distinguish between the identifier and the keyword:
dim [String] As String
public sub [Stop]
end sub
On msdn it says:
Any program element — such as a variable, class, or member — can have
the same name as a restricted keyword. For example, you can create a
variable named Loop. However, to refer to your version of it — which
has the same name as the restricted Loop keyword — you must either
qualify it by preceding it with its full namespace, or enclose it in
square brackets ([ ]), as in the following examples:
Reference here
This syntax allows you to use a reserved word as the name of a member or variable. Not recommended though IMHO from a code maintainability point of view (though see comments below for an alternative point of view on this particular point)!
Particularly not recommended if you're going to declare a property called "Date" as a string, but that's a separate issue...
Date is a reserved keyword in VB.NET, but can be used as a property or variable name if enclosed in square brackets:
http://msdn.microsoft.com/en-us/library/ksh7h19t(v=vs.90).aspx

Exclamation operator?

I'm learning D and have seen a lot of code like this:
ushort x = to!ushort(args[1]);
I assume this casts args[1] to ushort, but what's the difference between this and cast(ushort)?
EDIT: And what other uses does the exclamation mark operator have?
In D,
to!ushort(args[1])
is shorthand for the template instantiation
to!(ushort)(args[1])
and is similar to
to<ushort>(args[1])
in languages like C++/Java/C#.
The exclamation point is to note the fact that it's not a regular argument, but a template argument.
The notation does not use angle brackets because those are ridiculously difficult to parse correctly for a compiler (they make the grammar very context-sensitive), which makes it that much more difficult to implement a correct compiler. See here for more info.
The only other use I know about is just the unary 'not' operation (e.g. false == !true)... I can't think of any other uses at the moment.
Regarding the cast:
cast(ushort) is an unchecked cast, so it won't throw an exception if the value is out of range.
to!ushort() is a checked cast, so it throws an exception if the value is out of range.
The exclamation mark here is not an operator, it is just a token part of the explicit template instantiation syntax (described in detail here).
std.conv.to (docs) is a function template for converting between arbitrary types. It is implemented entirely in the library and has no special support in the language. It has a broader and different scope compared to the cast operator.
The to template takes two type parameters; a "to" type and a "from" type, in that order. In your example, the template is explicitly instantiated with the single type argument ushort for the "to" parameter, and a second type argument string (assuming args comes from the first parameter to main) is automatically inferred from the regular function argument passed to the function (args[1]) as the "from" parameter.
The resulting function takes a string parameter and returns a ushort parsed from that string, or throws an exception if it failed. The cast operator will not attempt this kind of high-level conversion.
Note that if there is more than one explicit template parameter, or that parameter has more than one token in it (ushort is a single keyword token), you must wrap the template parameter list in parentheses:
ushort result;
result = to!(typeof(result))(args[1]);
In this example, typeof, (, result and ) are four separate tokens and the parentheses are thus required.
To answer your last question, the ! token is also used for the unary not operator, unrelated to template instantiations:
bool yes = true;
bool no = !yes; // 'no' is false
You already got two excellent answers by jA_cOp and Merhdad. I just want answer directly to the OP question (what's the difference between this and cast(ushort)?) - The difference is that cast(ushort)args[1] will not work (you cannot cast from a string to an uint just like that), while the to!(type)(param) template knows what to do with the string and how to convert it to the primitive type.