14 Features of Visual Basic 14

Source: Internet
Author: User
Tags microsoft dynamics

Like Visual Studio, Visual Basic also jumps directly from version 12 to 14. While many of the features in the new version are the first to be introduced in C #, there are still a lot of enhancements that are specifically aimed at VB, which is designed to simplify the use of VB. This article lists some of the features that are most interesting to us.

Support for NULL

A feature of the new version is the support for null values, which is used by the?. Operator. This feature is identical to C #, and the right expression continues to be evaluated if the return value of the expression to the left of the operator is not NULL. This feature is especially useful when dealing with small amounts of data returned by external resources. For example:

If customer. Primaryresidence IsNot Nothing AndAlso customer. Primaryresidence.garage IsNot Nothing AndAlso property. PrimaryResidence.Garage.Cars = 2 Then Print ("both Car Garage")

This code will be simplified into the following statement:

If property. Primaryresidence?. Garage?. Cars = 2 Then Print ("both Car Garage")

In addition, you can combine the operator with the IF operator to provide a default value for the expression:

Dim Numberofcarports = If (property. Primaryresidence?. Garage?. Cars, 0)

C # and VB are not the only languages that support this type of NULL processing. The Objective-c language, which is widely used in Apple's products, supports this behavior by default. In particular, its method invocation also uses the. operator, which works in a similar way to VB. Operator.

In the Objective-c community, there is a mixed assessment of this trait. Some developers love this feature because they do not have to worry about the generation of null reference exceptions when making method calls. Other developers resent this because they will not see a null reference exception when the problem occurs, only to see that the method call has failed. As a result, they are confused as to why the method returns null instead of returning a valid value or throwing an exception.

Meta-programming

In Visual Basic 12, we first saw the introduction of the Callernameattribute feature. Although this feature addresses the issue of property change notification, its versatility is not sufficient to address the other part of the problem, where a unique identifier expressed in string form is required, in which case You need to use this operator to nameof.

The following example is provided by Lucian Wischik from the Visual Basic team, which includes the logic to validate the parameters.

Function Lookup (name as String) as Customerif name is what then Throw New ArgumentNullException (NameOf (name))

This avoids changing the name of the parameter, forgetting to modify the string defined in the constructor of the thrown exception. Because the nameof operator actually creates a constant, you can use the operator whenever you need to use a hard-coded string.

string interpolation (interpolation)

Ever since 10 years ago. NET first time, String.Format This method requires developers to count the number of parameters. Over the years, there have been countless bugs due to counting errors. String interpolation this technique was originally created by the mono team for the C # language, and it completely solves the bad practice of counting.

The interpolated string starts with $ "instead of using it alone." For each position where you need to insert a value, use a pair of curly braces to escape, which is the same as String.Format. Another thing that is the same as String.Format is that you can add formatting options to the escape. In the following simple example, there are two variables, name and total, which will be formatted as currency.

Dim message = $ "Hello {name}, your amount due is {TOTAL:C2}"

The syntax itself uses the String.Format method, so the user also needs to be aware of escaping in the appropriate situations, considering the following string:

Dim Requesturl = $ "Http://{server}/customer?name={customername}"

This code produces a bug, and what the developer actually needs is the following code:

Dim Requesturl = $ "Http://{server}/customer?name={urlencode (CustomerName)}"
Formattedstring Object

At first glance, the syntax of an interpolated string does not seem to handle a scenario that takes a string from an external resource, such as getting a string from a localized table or resource dictionary. However, Microsoft is working to achieve this capability. Lucian Wischik wrote:

Not only can it be used in different language cultures, but it can also extract the original formatted string or parameters (for example, if you intend to use the syntax in SQL queries, or you will need to escape the parameters to avoid string injection attacks). But so far, we haven't completely decided on the design specifications for the grammar.

According to the current specification statement, the interpolated string can be a regular string, or it can be implemented by an object named Formattedstring. When you attempt to assign an interpolated string to a variable or parameter that implements the IFormattable interface, an instance of the Formattedstring type is automatically created.

The IFormattable.ToString method of the object accepts a parameter of type IFormatProvider, which is used to override the formatting-related behavior.

String iformattable.tostring (String ignored, IFormatProvider formatprovider)        {            return String.Format ( formatprovider, format, args);        }

In the preceding section of code, the format and args two parameters represent the original string to Interpolate, and the value it corresponds to.

Multi-line string

One of the newly added features in VB is a multi-line string. Implement it without any special syntax, just omit the quotation marks where you want the branch to be. Depending on the line break used by the source code file, the line break automatically selects between symbols such as vbCrLf, vbcr, and vblf. For Visual Studio users, vbCrLf is basically selected.

At this time, some developers will choose to use CDATA paragraphs in the XML text to mimic this feature, which, while achieving the desired effect, may seem tedious and clumsy.

Property

Automatic attributes can now be marked as read-only. You can assign a value to the property at declaration time, or in a constructor.

The way this syntax should be used should not surprise you:

Public ReadOnly FirstName As String = "Anonymous" public ReadOnly LastName as Stringpublic Sub New (FirstName as String, LA Stname as String)    me.firstname = FirstName    me.lastname = Lastnameend Sub

When using this feature, some special cases should be taken into account. To understand these situations, you must first understand the copy-in and copy-out concepts of parameter passing. The CLR only allows you to pass references to variables and fields (that is, ref or out operators in C #). In VB, however, you can also pass a reference to a property.

To mitigate the differences between the two, VB creates a local variable when it prepares to make a function call, and the value of the property is copied to the local variable. The local variable is then passed to the function, and the function body is able to modify the value of the local variable. When the function returns, the value of the local variable is copied back into the property.

When you use a read-only automatic attribute, the following rules apply:

    1. If you use a read-only automatic attribute in a lambda expression in a constructor, the compiler prompts for a syntax error.
    2. If you use a read-only automatic attribute in a constructor or initializer, the copy-in and copy-out rules are applied. The Copy-out action writes the value to the field generated by the system for the property.
    3. If you do not use a read-only automatic attribute in a constructor or initializer, only the copy-in rule is applied. The copy-out operation does not occur at all, but it does not produce any syntax errors.

These rules are generated based on how read-only fields work.

Comments

Now you can add comments at the end of each line of a multiline statement. In previous versions, comments could only be added at the end of the last line of a multiline statement. Take a look at the following example:

Dim emaillist = from     C in Customers    Where c.isactive ' ignore inactive Customers and not    c.donotemail ' we don ' t Need another spam violation    Select c.fullname, c.emailaddress
Structural body

Structs can now support parameterless constructors. Although the CLR natively supports this feature, there is no mainstream programming language to implement this feature because the runtime of the constructor is unclear. For example, when you create an array of a struct, the constructor for that struct does not run.

If your code is MyStruct = new Mystructure (), it is clear that the constructor will execute immediately. And if your code is MyStruct = Nothing, the constructor is obviously not executed. But will the constructor be executed when a local variable or member variable is automatically initialized? Whichever answer you choose will always make some people feel uncomfortable.

Data text (literals)

Starting this year, the data text (a feature that is very important for JSON format) has finally been replaced with ISO-compliant formats. In the past, data literals have been used in a format based on the United States, creating some confusion for people living in Europe.

    • Old Style: #3/4/2005# (March 4, or April 3?) )
    • New style: #2005 -4-3#
Interoperability with C #

The overrides modifier will implicitly use the overloads modifier. In the past, developers of VB had to use both modifiers to ensure that C # users could invoke the correct overloaded method when using a class library created by VB.

Interface fuzziness

The use of interfaces in C # to inherit this feature makes it difficult to determine which interface method is called. This scenario is not allowed in VB, but due to the fact that C # allows this feature, it can result in some interfaces that are not implemented by VB. (This happens several times in a product in Microsoft Dynamics.) )

This restriction is relaxed in VB 14 relative to the "Hide by Name" (hide-by-name) overload rule used in C #, instead of a more traditional way (for VB), the "Hide by signature" rule.

Namespace resolution

VB has also been on the issue of namespace resolution on a somersault, consider the following code:

Threading.Thread.Sleep (1000)

According to Lucian Wischik said:

Before, VB will try to find "threading" this namespace, because it can not distinguish between system.threading and System.Windows.Threading, so the direct error. Now, VB14 will support both of these possible matching namespaces. If you enter threading in the Code Editor, after you enter the. Number, you will see support for both namespaces in the smart tip.

There are a number of similar cases, for example: When writing WinForms applications, Componentmodel.inotifypropertychanged event will not be able to distinguish between System.ComponentModel and System.Windows.Forms.ComponentModel, this problem will now disappear.

typeof and IsNot

Microsoft created the isnot operator ten years ago, and since then, there have been developers of VB who have asked Microsoft to allow the use of the isnot operator in typeof expressions, for example:

If TypeOf Sender IsNot Button Then
preprocessing directives

VB 14 provides a two-point improvement for pre-processing instructions.

Regi7on

Region will be able to use it in the function body, even across two function bodies.

Close Warning

As with C #, Visual Basic can now turn off compilation warnings for a block of code. An example is provided in the specification:

#Disable Warning BC42356 ' suppress Warning about-no awaits in this method

Typically, a developer will reopen this warning from somewhere else in the code file via a directive.

#Enable Warning BC42356

If the ID of the warning contains spaces or punctuation marks, you must use quotation marks. Microsoft's tools do not automatically do this for you, but the third-party parser rules written by Roslyn may be able to do this.

The quick fix feature of VB enables you to bypass certain warnings by automatically adding these instructions. This is especially useful for the third-party parser rules mentioned earlier, because you won't be able to quickly find the corresponding ID.

XML Document Validation

For now, the VB compiler ignores the contents of the XML document. In VB 14, the compiler tries to find errors in the document, such as incorrect parameter reference names. It is also able to "properly handle generics and operators in crefs tags."

Partial module and Interface declaration

With classes and struct types, you can now declare modules and interfaces as partial (partial). Typically, this feature is intended for the code generator, but it can also work when sharing code across multiple platforms.

14 Features of Visual Basic 14

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.