• Mark Forums Read
  • Today's Posts
  • View Site Leaders
  • What's New?
  • Advanced Search
[RESOLVED] (newbie question) "Use compound assignment" in a simple program by clicking the link above. You may have to before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below. New Member --> The error message says the error occurs on Line 12, where there is the statement n = n/2. This seems to be a fatal error, as the program neither compiles nor runs. Any ideas?

Paul King . Reason: Complete code
New Member --> I just compiled it again, and I am getting a different error:
I didn't change anything. When I set up the project, I didn't like saving the project to C: drive, so I chose a location on another drive. There was also a pop-up I got which said that the exe file that was "in my debug profile" doesn't exist -- which was a strange error. Where is this debug profile, and how can I change it?

Paul .
New Member --> I didn't change anything. When I set up the project, I didn't like saving the project to C: drive, so I chose a location on another drive. There was also a pop-up I got which said that the exe file that was "in my debug profile" doesn't exist -- which was a strange error. Where is this debug profile, and how can I change it?

Paul It looks like VB made sub Main() my startup object in the debug configuration. I changed it to "Form1". This was under the "Debug|ProgName debug Properties" menu item. A tab of debug properties comes up,and you need to choose the "Application" tab, and change the setting for Startup Object near the bottom of that form.

|
| |
| | | | | | |

| [RESOLVED] (newbie question) "Use compound assignment" in a simple program Posting Permissions post new threads post replies post attachments edit your posts is are code is code is





 alt=

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.

VB.Net Programming Tutorial

  • VB.Net Basic Tutorial
  • VB.Net - Home
  • VB.Net - Overview
  • VB.Net - Environment Setup
  • VB.Net - Program Structure
  • VB.Net - Basic Syntax
  • VB.Net - Data Types
  • VB.Net - Variables
  • VB.Net - Constants
  • VB.Net - Modifiers
  • VB.Net - Statements
  • VB.Net - Directives
  • VB.Net - Operators
  • VB.Net - Decision Making
  • VB.Net - Loops
  • VB.Net - Strings
  • VB.Net - Date & Time
  • VB.Net - Arrays
  • VB.Net - Collections
  • VB.Net - Functions
  • VB.Net - Subs
  • VB.Net - Classes & Objects
  • VB.Net - Exception Handling
  • VB.Net - File Handling
  • VB.Net - Basic Controls
  • VB.Net - Dialog Boxes
  • VB.Net - Advanced Forms
  • VB.Net - Event Handling
  • VB.Net Advanced Tutorial
  • VB.Net - Regular Expressions
  • VB.Net - Database Access
  • VB.Net - Excel Sheet
  • VB.Net - Send Email
  • VB.Net - XML Processing
  • VB.Net - Web Programming
  • VB.Net Useful Resources
  • VB.Net - Quick Guide
  • VB.Net - Useful Resources
  • VB.Net - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

VB.Net - Assignment Operators

There are following assignment operators supported by VB.Net −

Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assign value of A + B into C
+= Add AND assignment operator, It adds right operand to the left operand and assigns the result to left operand C += A is equivalent to C = C + A
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assigns the result to left operand C -= A is equivalent to C = C - A
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assigns the result to left operand C *= A is equivalent to C = C * A
/= Divide AND assignment operator, It divides left operand with the right operand and assigns the result to left operand (floating point division) C /= A is equivalent to C = C / A
\= Divide AND assignment operator, It divides left operand with the right operand and assigns the result to left operand (Integer division) C \= A is equivalent to C = C \A
^= Exponentiation and assignment operator. It raises the left operand to the power of the right operand and assigns the result to left operand C^=A is equivalent to C = C ^ A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Concatenates a String expression to a String variable or property and assigns the result to the variable or property.

Str1 &= Str2 is same as

Str1 = Str1 & Str2

Try the following example to understand all the assignment operators available in VB.Net −

When the above code is compiled and executed, it produces the following result −

vb.net compound assignment

  • Table of Contents
  • Course Home
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • 1.1 Getting Started
  • 1.1.1 Preface
  • 1.1.2 About the AP CSA Exam
  • 1.1.3 Transitioning from AP CSP to AP CSA
  • 1.1.4 Java Development Environments
  • 1.1.5 Growth Mindset and Pair Programming
  • 1.1.6 Pretest for the AP CSA Exam
  • 1.1.7 Survey
  • 1.2 Why Programming? Why Java?
  • 1.3 Variables and Data Types
  • 1.4 Expressions and Assignment Statements
  • 1.5 Compound Assignment Operators
  • 1.6 Casting and Ranges of Values
  • 1.7 Unit 1 Summary
  • 1.8 Mixed Up Code Practice
  • 1.9 Toggle Mixed Up or Write Code Practice
  • 1.10 Coding Practice
  • 1.11 Multiple Choice Exercises
  • 1.12 Method Signatures (preview 2026 curriculum)
  • 1.13 Calling Class Methods (preview 2026 curriculum)
  • 1.4. Expressions and Assignment Statements" data-toggle="tooltip">
  • 1.6. Casting and Ranges of Values' data-toggle="tooltip" >

Time estimate: 45 min.

1.5. Compound Assignment Operators ¶

Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to the current value of x and assigns the result back to x . It is the same as x = x + 1 . This pattern is possible with any operator put in front of the = sign, as seen below. If you need a mnemonic to remember whether the compound operators are written like += or =+ , just remember that the operation ( + ) is done first to produce the new value which is then assigned ( = ) back to the variable. So it’s operator then equal sign: += .

Since changing the value of a variable by one is especially common, there are two extra concise operators ++ and -- , also called the plus-plus or increment operator and minus-minus or decrement operator that set a variable to one greater or less than its current value.

Thus x++ is even more concise way to write x = x + 1 than the compound operator x += 1 . You’ll see this shortcut used a lot in loops when we get to them in Unit 4. Similarly, y-- is a more concise way to write y = y - 1 . These shortcuts only exist for + and - as they don’t really make sense for other operators.

If you’ve heard of the programming language C++, the name is an inside joke that C, an earlier language which C++ is based on, had been incremented or improved to create C++.

Here’s a table of all the compound arithmetic operators and the extra concise incremend and decrement operators and how they relate to fully written out assignment expressions. You can run the code below the table to see these shortcut operators in action!

Operator

Written out

= x + 1

= x - 1

= x * 2

= x / 2

= x % 2

Compound

+= 1

-= 1

*= 2

/= 2

%= 2

Extra concise

Run the code below to see what the ++ and shorcut operators do. Click on the Show Code Lens button to trace through the code and the variable values change in the visualizer. Try creating more compound assignment statements with shortcut operators and work with a partner to guess what they would print out before running the code.

If you look at real-world Java code, you may occassionally see the ++ and -- operators used before the name of the variable, like ++x rather than x++ . That is legal but not something that you will see on the AP exam.

Putting the operator before or after the variable only changes the value of the expression itself. If x is 10 and we write, System.out.println(x++) it will print 10 but aftewards x will be 11. On the other hand if we write, System.out.println(++x) , it will print 11 and afterwards the value will be 11.

In other words, with the operator after the variable name, (called the postfix operator) the value of the variable is changed after evaluating the variable to get its value. And with the operator before the variable (the prefix operator) the value of the variable in incremented before the variable is evaluated to get the value of the expression.

But the value of x after the expression is evaluated is the same in either case: one greater than what it was before. The -- operator works similarly.

The AP exam will never use the prefix form of these operators nor will it use the postfix operators in a context where the value of the expression matters.

exercise

1-5-2: What are the values of x, y, and z after the following code executes?

  • x = -1, y = 1, z = 4
  • This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y.
  • x = -1, y = 2, z = 3
  • x = -1, y = 2, z = 2
  • x = 0, y = 1, z = 2
  • x = -1, y = 2, z = 4

1-5-3: What are the values of x, y, and z after the following code executes?

  • x = 6, y = 2.5, z = 2
  • This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3).
  • x = 4, y = 2.5, z = 2
  • x = 6, y = 2, z = 3
  • x = 4, y = 2.5, z = 3
  • x = 4, y = 2, z = 3

1.5.1. Code Tracing Challenge and Operators Maze ¶

Use paper and pencil or the question response area below to trace through the following program to determine the values of the variables at the end.

Code Tracing is a technique used to simulate a dry run through the code or pseudocode line by line by hand as if you are the computer executing the code. Tracing can be used for debugging or proving that your program runs correctly or for figuring out what the code actually does.

Trace tables can be used to track the values of variables as they change throughout a program. To trace through code, write down a variable in each column or row in a table and keep track of its value throughout the program. Some trace tables also keep track of the output and the line number you are currently tracing.

../_images/traceTable.png

Trace through the following code:

1-5-4: Write your trace table for x, y, and z here showing their results after each line of code.

After doing this challenge, play the Operators Maze game . See if you and your partner can get the highest score!

1.5.2. Summary ¶

Compound assignment operators ( += , -= , *= , /= , %= ) can be used in place of the assignment operator.

The increment operator ( ++ ) and decrement operator ( -- ) are used to add 1 or subtract 1 from the stored value of a variable. The new value is assigned to the variable.

The use of increment and decrement operators in prefix form (e.g., ++x ) and inside other expressions (i.e., arr[x++] ) is outside the scope of this course and the AP Exam.

VB .NET Language in a Nutshell by Steven Roman PhD, Ron Petrusha, Paul Lomax

Get full access to VB .NET Language in a Nutshell and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Assignment Operators

Along with the equal operator, there is one assignment operator that corresponds to each arithmetic and concatenation operator. Its symbol is obtained by appending an equal sign to the arithmetic or concatenation symbol.

The arithmetic and concatenation operators work as follows. They all take the form:

where <operator> is one of the arithmetic or concatenation operators. This is equivalent to:

To illustrate, consider the addition assignment operator. The expression:

is equivalent to:

which simply adds 1 to x. Similarly, the expression:

which concatenates the string "end" to the end of the string s.

All of the “shortcut” assignment operators—such as the addition assignment operator or the concatenation assignment operator—are new to VB .NET.

The assignment operators are:

The equal operator, which is both an assignment operator and a comparison operator. For example:

Note that in VB .NET, the equal operator alone is used to assign all data types; in previous versions of VB, the Set statement had to be used along with the equal operator to assign an object reference.

Addition assignment operator. For example:

adds 1 to the value of lNumber and assigns the result to lNumber.

Subtraction assignment operator. For example:

subtracts 1 from the value of lNumber and assigns the ...

Get VB .NET Language in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

vb.net compound assignment

Performing Calculations in VB.NET

   
Application Development Using Visual Basic and .NET
By Robert J. Oberg, Peter Thorsteinson, Dana L. Wyatt
Table of Contents
Chapter 3.  VB.NET Essentials, Part I

Our "Hello, world" program illustrated the basic structure of a VB.NET program, but we will need a slightly more elaborate example to show the use of other basic programming constructs, such as variables , expressions, and control structures. The example illustrates a number of features, which we will explain later. Our next example is a simple calculator for an IRA account. We calculate the accumulation of deposits to an IRA of $2000.00 a year at 6% interest for 10 years , assuming that each deposit is made at the end of the year. Our calculation is performed in two ways:

The example program is in the folder Ira\Step1 .

If you compile and run it, you will see this output:

.00 ,000.00 2 ,000.00 0.00 ,120.00 3 ,000.00 7.20 ,367.20 4 ,000.00 2.03 ,749.23 5 ,000.00 4.95 ,274.19 6 ,000.00 6.45 ,950.64 7 ,000.00 7.04 ,787.68 8 ,000.00 ,007.26 ,794.94 9 ,000.00 ,187.70 ,982.63 10 ,000.00 ,378.96 ,361.59 Total using formula = 26361.59

In VB.NET variables are always of a specific data type. Some common types are Integer for integers and Double for floating-point numbers . VB.NET has the Decimal data type, which has a high degree of precision, suitable for financial calculations.

You must declare variables before you use them, and you may optionally initialize them.

If an initial value is not specified in the declaration, the variable is automatically initialized . For example, an uninitialized Decimal variable is set to zero. We will discuss initialization later in the chapter.

Variables must be either local within a method or members of a class. There are no global variables in VB.NET.

A literal is used when you explicitly write a value in a program rather than represent it with a variable name . An integer literal is represented by an ordinary base-10 integer, an octal integer, or a hexadecimal integer. An octal integer is indicated with the &O prefix, such as &O77 (which is 63 in base 10). A hexadecimal literal is indicated with the &H prefix, such as &H7FFF (which is 32,767 in base 10). The suffixes S , I , and L are used to designate Short, Integer, and Long. A floating-point literal is represented by a number with a decimal point or by exponential notation. You may determine the type that is used for storing a literal by a suffix. The suffix F indicates single precision (32-bit) floating point. The suffix R indicates double precision (64-bit) floating point. The Single and Double types are often suitable for scientific and engineering purposes. The suffix D indicates Decimal , which is usually more suitable for financial calculations, and it represents a high precision (128-bit) fixed-point number.

That is the letter O, not the number 0.

We discuss VB.NET types, such as Single , Double , and Decimal , later in the chapter.

A character string literal is represented by a sequence of characters in double quotes.

You can combine variables and literals via operators to form expressions. The VB.NET operators are similar to those in other .NET languages.

One of the newest features of VB.NET is its new compound assignment operators that perform arithmetic operations as part of the assignment. Here are examples from the Ira program:

There are six new compound assignment operators available in VB.NET. They are demonstrated in the following example:

There is also a compound assignment operator for string concatenation. The following expression concatenates an exclamation point to the end of the string contained in the variable buf:

VB.NET introduces several operators that are new to VB6 programmers. OrElse and AndAlso provide shortcut evaluation of conditional expressions. And the assignment operators ^= , *= , /= , \= , += , -= , and &= provide shortcuts for common operations.

Precedence rules determine the order in which operators within expressions are evaluated. Operators are applied in the precedence order shown in Table 3-1. Operators within a row have equal precedence. For operators of equal precedence within the same expression, the order of evaluation is from left to right, as they appear in an expression. Order of evaluation can be explicitly controlled by using parentheses.

Table 3-1. Operator Precedence in VB.NET

Category Operators
Primary All non-operator expressions (literals, variables)
Exponentiation ^
Unary negation +, -
Multiplicative *, /
Integer division \
Modulus Mod
Additive +, -
Concatenation &
Relational =, <>, <, >, <=, >=, Like, Is, TypeOf...Is
Conditional NOT Not
Conditional AND And, AndAlso
Conditional OR Or, OrElse
Conditional XOR Xor

Output and Formatting

The Console class in the System namespace supports two simple methods for performing output:

WriteLine writes out a string followed by a new line.

Write writes out just the string without the new line.

You can write out other data types by relying on the ToString method of System.Object , which will provide a string representation of any data type. System.Object is the base class from which all classes inherit. We will discuss this class in Chapter 6, where you will also see how to override ToString for your own custom data types. You can use the string concatenation operator & to build up an output string.

The output is all on one line:

Placeholders

A more convenient way to build up an output string is to use placeholders such as {0}, {1}, and so on. An equivalent way to do the output shown above is

The program OutputDemo illustrates the output operations just discussed.

We will generally use placeholders for our output from now on. Placeholders can be combined with formatting characters to control output format.

Format Strings

VB.NET has extensive formatting capabilities, which you can control through placeholders and format strings.

Simple placeholders: {n}, where n is 0, 1, 2, , indicating which variable to insert

Control width: {n,w}, where w is width (positive for right justified and negative for left justified) of the inserted variable

Format string: {n:S}, where S is a format string indicating how to display the variable

Width and format string: {n,w:S}

A format string consists of a format character followed by an optional precision specifier . Table 3-2 shows the available format characters.

Table 3-2. Format Characters

Format Character Meaning
C Currency (locale specific)
D Decimal integer
E Exponential (scientific)
F Fixed point
G General (E or F)
N Number with embedded commas
X Hexadecimal

Sample Formatting Code

The sample program in Ira\Step1 provides an example. The header uses width specifiers, and the output inside the loop uses width specifiers and the currency format character.

Control Structures

The preceding code fragment illustrates a While End While loop. VB.NET supports several control structures, including the If and Select decision statements as well as For and While loops .

While End While

Do While Loop

Do Until Loop

Do Loop While

Do Loop Until

For Each Next

If Then End If

If Then Else End If

If Then ElseIf Then End If

Select Case End Select

With End With

SyncLock End SyncLock

Try Catch Finally

Most of these will be familiar to Visual Basic programmers. The Throw and Try statements are used in exception handling. We will discuss exceptions later in this chapter. The SyncLock statement can be used to enforce synchronization in multithreading situations. We will discuss multithreading in Chapter 10.

Select Case Statement

A Select Case statement is used to execute one of several groups of statements, depending on the value of a test expression. The test expression must be one of the following data types: Boolean , Byte , Char , Date , Double , Decimal , Integer , Long , Object , Short , Single , or String .

After a particular case statement is executed, control automatically continues after the following End Select . The program SelectDemo illustrates use of the Select Case statement in VB.NET.

Our Ira\Step1 example program has a method IraTotal for computing the total IRA accumulation by use of a formula. In VB.NET, every function is a method of some class or module; there are no freestanding global functions. If a method does not refer to any instance variables of the class, the method can be declared as Shared . We will discuss instance data of a class later in this chapter. If a method is accessed only from within a single class, it may be designated as Private . Note the use of the Private keyword in the Ira\Step1 example. The Shared keyword is not used however, since the example uses a module instead of a class. All methods in a module are shared by default.

Also in the Ira\Step1 example, note the use of the Pow and Round methods of the Math class, which is another class in the System namespace. These methods are shared methods. To call a shared method from outside the class in which it is defined, place the name of the class followed by a period before the method name.

Console Input in VB.NET

Our first Ira program is not too useful, because the data are hardcoded. To perform the calculation for different data, you would have to edit the source file and recompile. What we really want to do is allow the user of the program to enter the data at runtime.

An easy, uniform way to do input for various data types is to read the data as a string and then convert it to the desired data type. Use the ReadLine method of the System.Console class to read in a string. Use the ToXxxx methods of the System.Convert class to convert the data to the type you need. This can be seen in the Ira\Step2 example.

We mentioned earlier in the chapter that if you run a Visual Studio console application under the debugger, the console window will close automatically when the program exits. If you want to keep the window open, you can place a ReadLine statement at the end of your Main procedure. The program HelloWithPause provides an illustration.

End Sub

Although console input in VB.NET is fairly simple, we can make it even easier using object-oriented programming. We can encapsulate the details of input in an easy-to-use wrapper class, InputWrapper (which is not part of VB.NET or the .NET Framework class library, and was created for this book).

Using the Inputwrapper Class

In VB.NET, you instantiate a class by using the New keyword.

This code creates the object instance iw of the InputWrapper class.

The InputWrapper class wraps interactive input for several basic data types. The supported data types are int , double , decimal , and string . Methods getInt , getDouble , getDecimal , and getString are provided to read those types from the command line. A prompt string is passed as an input parameter. The directory InputWrapper contains the files InputWrapper.vb , which implements the class, and TestInputWrapper.vb , which tests the class. (For convenience, we provide the file InputWrapper.vb in each project where we use it.)

You can use the InputWrapper class without knowing its implementation. With such encapsulation, complex functionality can be hidden by an easy-to-use interface. (A listing of the InputWrapper class is in the next section.)

Here is the code for Ira\Step2 . We read in the deposit amount, the interest rate, and the number of years, and we compute the IRA accumulation year by year. The first input is done directly, and then we use the InputWrapper class. The bolded code illustrates how to use the InputWrapper class. Instantiate an InputWrapper object iw by using new . Prompt for and obtain input data by calling the appropriate getXXX method.

Inputwrapper Class Implementation

The InputWrapper class is implemented in the file InputWrapper.vb . You should find the code reasonably intuitive, given what you already know about classes.

Note that, unlike the method IraTotal , the methods of the InputWrapper class are used outside of the class so they are marked as public .

If bad input data is presented, an exception will be thrown. Exceptions are discussed in Chapter 5.

   
Top

Application Development Using Visual BasicR and .NET

  • Testing for No Records
  • Creating Constraints, PrimaryKeys, Relationships Based on Multiple Columns
  • Populating a Windows Forms ComboBox
  • Enumerating and Maintaining Database Objects
  • Retrieving Database Schema Information from SQL Server
  • Characters, Strings, and Text Output
  • Making Programs Think Branching Statements and Subroutines
  • Adding Sound Effects to Your Game
  • Multiplayer Programming The Crazy Carnage Game
  • Classes in VBScript (Writing Your Own COM Objects)
  • Super-Charged Client-Side Scripting
  • HTML Applications
  • Server-Side Web Scripting
  • Adding VBScript to Your VB Applications
  • Basic SWT Widgets
  • Drag and Drop and the Clipboard
  • JFace Windows and Dialogs
  • Eclipse Forms
  • Part I - The Underpinning Theory
  • Leading change
  • Part II - The Applications
  • Cultural change
  • IT-based process change
  • Configuring Accounting
  • Deployment Scenarios
  • Manual (Cut-and-Paste) Enrollment
  • VPN Management Using ASDM

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IDE0054 "Use compound assignment" false positive in object initializer #33382

@dgrunwald

dgrunwald commented Feb 14, 2019

: VS2019 Preview 3

:

There is an IDE0054 "Use compound assignment" hint for , but this doesn't make sense in an object initializer.

@vatsalyaagrawal

jnm2 commented Mar 9, 2019

Hitting this on RC.1 SVC1.

Sorry, something went wrong.

@mavasani

mavasani commented Mar 9, 2019

Tagging

@CyrusNajmabadi

CyrusNajmabadi commented Mar 9, 2019

can you supply a repro here?

jnm2 commented Mar 9, 2019 • edited Loading

Foo { public string Name { get; set; } public Foo Clone() { // ↓ IDE0054 Use compound assignment return new Foo { Name = Name + " (copy)" }; } }

And the fixer does:

(2019 RC.1 SVC1)

Oh. This went in only about 3 weeks ago. I doubt that would make the 16.0 train. Have confirmed it does not repro in a recent roslyn-hive.

Do you know what the cutoff for 16.0 was?

I don’t think the bug was assigned 16.0 Preview4 milestone, so I would assume the fix will show up in 16.1.

@sharwell

No branches or pull requests

@dgrunwald

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

ICompound Assignment Operation Interface

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Represents a compound assignment that mutates the target with the result of a binary operation.

Current usage: (1) C# compound assignment expression. (2) VB compound assignment expression.

This node is associated with the following operation kinds:

  • CompoundAssignment

This interface is reserved for implementation by its associated APIs. We reserve the right to change it in the future.

An enumerable of child operations for this operation.

(Inherited from )

An array of child operations for this operation. Deprecated: please use .

(Inherited from )

If the operation is an expression that evaluates to a constant value, is true and is the value of the expression. Otherwise, is false.

(Inherited from )

Type parameter which runtime type will be used to resolve virtual invocation of the , if any. Null if is resolved statically, or is null.

Conversion applied to before the operation occurs.

if overflow checking is performed for the arithmetic operation.

Set to True if compiler generated /implicitly computed by compiler code

(Inherited from )

if this assignment contains a 'lifted' binary operation.

Identifies the kind of the operation.

(Inherited from )

The source language of the IOperation. Possible values are and .

(Inherited from )

Kind of binary operation.

Operator method used by the operation, null if the operation does not use an operator method.

Conversion applied to the result of the binary operation, before it is assigned back to .

IOperation that has this operation as a child. Null for the root.

(Inherited from )

Optional semantic model that was used to generate this operation. Non-null for operations generated from source with API and operation callbacks made to analyzers. Null for operations inside a .

(Inherited from )

Syntax that was analyzed to produce the operation.

(Inherited from )

Target of the assignment.

(Inherited from )

Result type of the operation, or null if the operation does not produce a result.

(Inherited from )

Value to be assigned to the target of the assignment.

(Inherited from )
(Inherited from )
(Inherited from )

Extension Methods

Gets the underlying information from this . This conversion is applied before the operator is applied to the result of this conversion and .

Gets the underlying information from this . This conversion is applied after the operator is applied, before the result is assigned to .

Returns all the descendant operations of the given in evaluation order.

Returns all the descendant operations of the given including the given in evaluation order.

Gets the underlying information from this . This conversion is applied before the operator is applied to the result of this conversion and .

Gets the underlying information from this . This conversion is applied after the operator is applied, before the result is assigned to .

Additional resources

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Multiassignment in VB like in C-Style languages

Is there a way to perform this in VB.NET like in the C-Style languages:

  • variable-assignment
  • c#-to-vb.net

Shimmy Weitzhandler's user avatar

  • 1 Is there any advantage of the multiple assignment versus performing each assignment individually? Many translator applications will optimize the two to be equal at run-time. –  Thomas Matthews Commented Feb 22, 2010 at 18:29
  • Yes, there is an advantage. If you want to assign a specific value, say 1.7834 to H(I) and W(J), you have to type 1.7834 only once, effectively treating it as a 1-time constant, whereas typing it twice, it's not obvious that the two constants, although equal, are the same constant. E.g., if H & W are the height and width, it could be a coincidence that the height & width are equal or they might always represent a square. –  Chelmite Commented Jun 18, 2013 at 23:42

2 Answers 2

Expanding on Mark's correct answer

This type of assignment style is not possible in VB.Net. The C# version of the code works because in C# assignment is an expression which produces a value. This is why it can be chained in this manner.

In VB.Net assignment is a statement and not an expression. It produces no value and cannot be changed. In fact if you write the code "a = b" as an expression it will be treated as a value comparison and not an assignment.

Eric's recent blog post on this subject for C#

  • http://blogs.msdn.com/ericlippert/archive/2010/02/11/chaining-simple-assignments-is-not-so-simple.aspx

At a language level assignment is a statement and not an expression.

JaredPar's user avatar

  • For info, it is a wishlist item to add support for this: blogs.msdn.com/lucian/archive/2010/02/12/… –  Rowland Shaw Commented Mar 2, 2010 at 17:13

As soon as I post this, someone will provide an example of how to do it. But I don't think it is possible . VB.NET treats the single equals in the r-value as a comparison. For example:

The above code prints 0 (false) and -1 (true).

Mark Wilkins's user avatar

  • 1 It's not possible. Here's where Lucian, who leads the VB.Net specification, blogs about whether it's worth adding. blogs.msdn.com/lucian/archive/2010/02/12/… For bonus marks here's Eric Lippert (works on C# compiler) blogging about how confusing it is in C#. blogs.msdn.com/ericlippert/archive/2010/02/11/… –  MarkJ Commented Feb 22, 2010 at 17:13

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c# c++ vb.net variable-assignment c#-to-vb.net or ask your own question .

  • The Overflow Blog
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Why did the Chinese government call its actual languages 'dialects'? Is this to prevent any subnational separatism?
  • Are positive definite linear operator always invertible?
  • Python script to renumber slide ids inside a pptx presentation
  • security concerns of executing mariadb-dump with password over ssh
  • If someone threatens force to prevent another person from leaving, are they holding them hostage?
  • Will there be Sanhedrin in Messianic Times?
  • How would you address the premises of Schellenberg's non-resistant divine hiddenness argument?
  • I have been trying to solve this Gaussian integral, which comes up during the perturbation theory
  • What was the newest chess piece
  • Explode multiple columns with different lengths
  • Stuck as a solo dev
  • press the / key to isolate an object, my blueprint background images also disappear
  • Trying to find air crash for a case study
  • Coloring a function based on its monotonicity
  • Where are the DC-3 parked at KOPF?
  • I am an imaginary variance
  • Should I be careful about setting levels too high at one point in a track?
  • Using a standard junction box as a pull point in a run. Do I need to leave a loop of wire in the box or should I take the slack out?
  • What properties of the fundamental group functor are needed to uniquely determine it upto natural isomorphism?
  • Solaris 11 cbe: no more updates?
  • Seeking a Text-Based Version of Paul Dirac's 1926 Paper on Quantum Mechanics
  • Can All Truths Be Scientifically Verified?
  • How to change my document's font
  • When a creature enchanted with Fungal Fortitude dies and returns to the battlefield, does it keep Fungal Fortitude?

vb.net compound assignment

IMAGES

  1. Compound Interest in VB NET

    vb.net compound assignment

  2. VB.net Programming Challenge: Calculating Compound Interest (VB.net Functions)

    vb.net compound assignment

  3. ASP.NET With Visual Basic: Operators and Operands

    vb.net compound assignment

  4. VB NET

    vb.net compound assignment

  5. ASP.NET With Visual Basic: Operators and Operands

    vb.net compound assignment

  6. Coding is Everything

    vb.net compound assignment

VIDEO

  1. HOW TO LOAD DATA FROM TABLE TO COMBOBOX USING VB.NET

  2. Inheritance in Console For Beginners

  3. Permutation and Combination C#

  4. Mini Project in VB.NET with SQL Server

  5. JavaScript Recap: Assignment Operators

  6. Lecture 103 Compound Assignment Operator Example in java in hindi

COMMENTS

  1. Use compound assignment (IDE0054 and IDE0074)

    If you want to suppress only a single violation, add preprocessor directives to your source file to disable and then re-enable the rule. C#. Copy. #pragma warning disable IDE0054 // Or IDE0074 // The code that's violating the rule is on this line. #pragma warning restore IDE0054 // Or IDE0074. To disable the rule for a file, folder, or project ...

  2. Assignment Operators

    The following are the assignment operators defined in Visual Basic. = Operator ^= Operator *= Operator /= Operator \= Operator += Operator-= Operator <<= Operator >>= Operator &= Operator. See also. Operator Precedence in Visual Basic; Operators Listed by Functionality; Statements

  3. VS 2019 [RESOLVED] (newbie question) "Use compound assignment" in a

    Re: (newbie question) "Use compound assignment" in a simple program. Originally Posted by David Anton. It both compiles and runs for me. The issue about compound assignment is just a suggestion by Visual Studio - you can rewrite that statement as "n /= 2", but your version is still correct. I just compiled it again, and I am getting a different ...

  4. c#

    myFactory.GetNextObject().MyProperty += 5; You _certainly wouldn't do. myFactory.GetNextObject().MyProperty = myFactory.GetNextObject().MyProperty + 5; You could again use a temp variable, but the compound assignment operator is obviously more succinct. Granted, these are edge cases, but it's not a bad habit to get into.

  5. VB.Net

    There are following assignment operators supported by VB.Net −. Operator. Description. Example. =. Simple assignment operator, Assigns values from right side operands to left side operand. C = A + B will assign value of A + B into C. +=. Add AND assignment operator, It adds right operand to the left operand and assigns the result to left operand.

  6. &= Operator

    Remarks. The element on the left side of the &= operator can be a simple scalar variable, a property, or an element of an array. The variable or property cannot be ReadOnly. The &= operator concatenates the String expression on its right to the String variable or property on its left, and assigns the result to the variable or property on its left.

  7. 1.5. Compound Assignment Operators

    1.5. Compound Assignment Operators¶. Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to the current value of x and assigns the result back to x.It is the same as x = x + 1.This pattern is possible with any operator put in front of the = sign, as seen below. If you need a mnemonic to remember whether the compound ...

  8. Assignment Operators

    The assignment operators are: =. The equal operator, which is both an assignment operator and a comparison operator. For example: oVar1 = oVar2. Note that in VB .NET, the equal operator alone is used to assign all data types; in previous versions of VB, the Set statement had to be used along with the equal operator to assign an object reference.

  9. PDF Statements in Visual Basic

    A variety of compound assignment operations can be performed using operators of this type. For a list of these operators and more information about them, see Assignment Operators (Visual Basic). The concatenation assignment operator (&=) is useful for adding a string to the end of already existing strings, as the following example illustrates.

  10. Section 5.8. Compound Assignment Operators

    5.8. Compound Assignment Operators. Visual Basic provides several compound assignment operators for abbreviating assignment statements. For example, the statement. value = value + 3 can be abbreviated with the addition assignment operator, += as. value += 3 The += operator adds the value of the right operand to the value of the left operand and stores the result in the left operand's variable.

  11. Performing Calculations in VB.NET

    One of the newest features of VB.NET is its new compound assignment operators that perform arithmetic operations as part of the assignment. Here are examples from the Ira program: i += 1 ' this is equivalent to i = i + 1 total += amount + interest ' this is equivalent to ' total = total + amount + interest . There are six new compound ...

  12. IDE0054 Use compound assignment

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.

  13. IDE0054 "Use compound assignment" false positive in object ...

    There is an IDE0054 "Use compound assignment" hint for level = level - 1, but this doesn't make sense in an object initializer. The text was updated successfully, but these errors were encountered: All reactions. ...

  14. += Operator

    This assignment operator implicitly performs widening but not narrowing conversions if the compilation environment enforces strict semantics. For more information on these conversions, see Widening and Narrowing Conversions.For more information on strict and permissive semantics, see Option Strict Statement.. If permissive semantics are allowed, the += operator implicitly performs a variety of ...

  15. Statements in Visual Basic

    A statement in Visual Basic is a complete instruction. It can contain keywords, operators, variables, constants, and expressions. Each statement belongs to one of the following categories: Declaration Statements, which name a variable, constant, or procedure, and can also specify a data type. Executable Statements, which initiate actions.

  16. The compound assignment operator "-=" in VB.NET is equivalent to

    The core claim of the question is to identify the equivalent operation of the compound assignment operator "-=" in VB.NET. Rationale: The compound assignment operator "-=" in VB.NET performs subtraction and assignment simultaneously, meaning it subtracts the right operand from the left operand and assigns the result to the left operand. ...

  17. Concat strings by & and

    26. & is only used for string concatenation. + is overloaded to do both string concatenation and arithmetic addition. The double purpose of + leads to confusion, exactly like that in your question. Especially when Option Strict is Off, because the compiler will add implicit casts on your strings and integers to try to make sense of your code.

  18. ICompoundAssignmentOperation Interface (Microsoft.CodeAnalysis

    Represents a compound assignment that mutates the target with the result of a binary operation. Current usage: (1) C# compound assignment expression. (2) VB compound assignment expression.

  19. Multiassignment in VB like in C-Style languages

    This type of assignment style is not possible in VB.Net. The C# version of the code works because in C# assignment is an expression which produces a value. This is why it can be chained in this manner. In VB.Net assignment is a statement and not an expression. It produces no value and cannot be changed. In fact if you write the code "a = b" as ...