Visual Basic .NET/Assignation and comparison operators

Assignment [ edit | edit source ].

The "=" operator is used for assignment. The operator also serves as a comparison operator (see Comparison).

  • To set values:

You can use variables in the equal operator, as well.

Comparison [ edit | edit source ]

The "=" operator is used for comparison. The operator also serves as a assignation operator (see Assignment).

  • To compare values:

Let's try a slightly more advanced operation.

You will get an error if you try to assign a constant or a literal a value, such as 7 = 2. You can compare 7 and 2, but the answer will always be False .

In the case of two equal operators appearing in a statement, such as

The second equal operator will be processed first, comparing 2 and 7, giving a False . Then the first equal operator will be processed, assigning False to x.

More Comparison Operators [ edit | edit source ]

(x less than y), (x more than y), (x not equal to y), (x less than or equal y) & (x greater than or equal to y)

Note the way round the operators are on the last two, putting them the other way round is not valid.

vb.net assignment vs equality

  • Book:Visual Basic .NET

Navigation menu

Visual Basic .NET Language

  • Getting started with Visual Basic .NET Language
  • Learn Tutorial
  • Awesome Book
  • Awesome Community
  • Awesome Course
  • Awesome Tutorial
  • Awesome YouTube
  • BackgroundWorker
  • ByVal and ByRef keywords
  • Connection Handling
  • Data Access
  • Debugging your application
  • Declaring variables
  • Dictionaries
  • Disposable objects
  • Error Handling
  • Extension methods
  • File Handling
  • File/Folder Compression
  • Google Maps in a Windows Form
  • Introduction to Syntax
  • Multithreading
  • NullReferenceException
  • OOP Keywords
  • Operator Overloading
  • String Concatenation
  • Widening and Narrowing
  • Option Explicit
  • Option Infer
  • Option Strict
  • Reading compressed textfile on-the-fly
  • Short-Circuiting Operators (AndAlso - OrElse)
  • Task-based asynchronous pattern
  • Type conversion
  • Unit Testing in VB.NET
  • Using axWindowsMediaPlayer in VB.Net
  • Using BackgroundWorker
  • Using Statement
  • Visual Basic 14.0 Features
  • WinForms SpellCheckBox
  • Working with Windows Forms
  • WPF XAML Data Binding

Visual Basic .NET Language Operators Assignment

Fastest entity framework extensions.

There is a single assignment operator in VB.

  • The equal sign = is used both for equality comparison and assignment. Dim value = 5

Notes Watch out for assignment vs. equality comparison.

In this example you can see the equal sign being used as both a comparison operator and an assignment operator, unlike other languages. In this case, result will be of type Boolean and will contain the value of the equality comparison between leftValue and rightValue .

Related: Using Option Strict On to declare variables properly

Got any Visual Basic .NET Language Question?

pdf

  • Advertise with us
  • Cookie Policy
  • Privacy Policy

Get monthly updates about new articles, cheatsheets, and tricks.

VB .NET Language in a Nutshell by Steven Roman PhD

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 assignment vs equality

# Operators

If you have the following variables

Addition Performed by the plus sign + .

Subtraction Performed by the minus sign - .

Multiplication Performed by the star symbol * .

Division Performed by the forward slash symbol / .

Integer Division Performed by the backslash symbol </kbd>.

Modulus Performed by the Mod keyword.

Raise to a Power of Performed by the ^ symbol.

# String Concatenation

String concatenation is when you combine two or more strings into a single string variable.

String concatenation is performed with the & symbol.

Non-string values will be converted to string when using & .

Always use & (ampersand) to perform string concatenation.

DON'T DO THIS While it is possible, in the simplest of cases, to use the + symbol to do string concatenation, you should never do this. If one side of the plus symbol is not a string, when Option strict is off, the behavior becomes non-intuitive, when Option strict is on it will produce a compiler error. Consider:

The problem here is that if the + operator sees any operand that is a numeric type, it will presume that the programmer wanted to perform an arithmetic operation and attempt to cast the other operand to the equivalent numeric type. In cases where the other operand is a string that contains a number (for example, "10"), the string is converted to a number and then arithmetically added to the other operand. If the other operand cannot be converted to a number (for example, "2g"), the operation will crash due to a data conversion error. The + operator will only perform string concatenation if both operands are of String type.

The & operator, however, is designed for string concatenation and will cast non-string types to strings.

# Assignment

There is a single assignment operator in VB.

  • The equal sign = is used both for equality comparison and assignment. `Dim value = 5`

Notes Watch out for assignment vs. equality comparison.

In this example you can see the equal sign being used as both a comparison operator and an assignment operator, unlike other languages. In this case, result will be of type Boolean and will contain the value of the equality comparison between leftValue and rightValue .

(opens new window)

# Comparison

Comparison operators compare two values and return to you a boolean ( True or False ) as the result.

  • The equal sign = is used both for equality comparison and assignment. `If leftValue = rightValue Then` ...
  • The left angle bracket nest to the right angle bracket <> performs an unequal comparison. `If leftValue <> rightValue Then` ...

Greater Than

  • The left angle bracket < performs a greater than comparison. `If leftValue < rightValue Then` ...

Greater Than Or Equal

  • The equal sign nest to the left angle bracket => performs a greater than or equals comparison. `If leftValue =< rightValue Then` ...
  • The right angle bracket > performs a less than comparison. `If leftValue > rightValue Then` ...

Less Than Or Equal

  • The equal sign nest to the right angle bracket => performs a greater than or equals comparison. `If leftValue => rightValue Then` ...
  • The Like operator tests the equality of a string and a search pattern.
  • See further info on [MSDN](https://msdn.microsoft.com/en-us/library/swf8kaxw.aspx) in the remarks section. `If string Like pattern Then ...`

# Widening and Narrowing

Needs editing.

# Operator Overloading

These are the bitwise operators in VB.NET : And, Or, Xor, Not

Example of And bitwise operation

The value of a will be 1. The result is obtained after comparing 3 and 5 in binary for. 3 in binary form is 011 and 5 in binary form is 101. The And operator places 1 if both bits are 1. If any of the bits are 0 then the value will be 0

So the binary result is 001 and when that is converted to decimal, the answer will be 1.

Or operator places 1 if both or one bit is 1

Xor operator places 1 if only one of the bit is 1 (not both)

Not operator reverts the bits including sign

Operators are used to assign or compare values. They consist of a single symbol or keyword and are usually sandwiched between a left and a right value. For example: right = left .

Operators are intrinsic to the language (such as = ), and not functions such as those provided by System.Math.

← Introduction to Syntax Conditions →

vb.net assignment vs equality

  • Latest Articles
  • Top Articles
  • Posting/Update Guidelines
  • Article Help Forum

vb.net assignment vs equality

  • View Unanswered Questions
  • View All Questions
  • View C# questions
  • View C++ questions
  • View Javascript questions
  • View Visual Basic questions
  • View Python questions
  • CodeProject.AI Server
  • All Message Boards...
  • Running a Business
  • Sales / Marketing
  • Collaboration / Beta Testing
  • Work Issues
  • Design and Architecture
  • Artificial Intelligence
  • Internet of Things
  • ATL / WTL / STL
  • Managed C++/CLI
  • Objective-C and Swift
  • System Admin
  • Hosting and Servers
  • Linux Programming
  • .NET (Core and Framework)
  • Visual Basic
  • Web Development
  • Site Bugs / Suggestions
  • Spam and Abuse Watch
  • Competitions
  • The Insider Newsletter
  • The Daily Build Newsletter
  • Newsletter archive
  • CodeProject Stuff
  • Most Valuable Professionals
  • The Lounge  
  • The CodeProject Blog
  • Where I Am: Member Photos
  • The Insider News
  • The Weird & The Wonderful
  • What is 'CodeProject'?
  • General FAQ
  • Ask a Question
  • Bugs and Suggestions

vb.net assignment vs equality

Comparing Values for Equality in .NET: Identity and Equivalence

vb.net assignment vs equality

Introduction

The various ways of comparing two values for equality in .NET can be very confusing. In fact if we have two objects a and b in C# there are at least four ways to compare their identity, plus one operator that looks like an identity comparison to add to the confusion:

  • if (a.Equals(b)) {}
  • if (object.Equals(a, b)) {}
  • if (object.ReferenceEquals(a, b) {}
  • if (a == b) {}
  • if (a is b) {}

As if that isn't confusing enough, these methods and operators behave differently depending on:

  • whether a and b are reference types or value types
  • whether they are reference types which are made to behave like value types for these purposes ( System.String is one of these)

This article is an attempt to clarify why we have all these versions of equality, and what they all mean.

What does it mean to be the same?

Firstly, we have to understand that there are actually two basic types of equality for objects:

  • Identity (reference equality): Two objects are identical if they actually are the same object in memory. That is, references to them point to the same memory address.
  • Equivalence (value equality): Two objects are equivalent if the value or values they contain are the same.

So if we have two integers, a and b , both set to value 3, they are equivalent (they have the same value) but not necessarily identical ( a and b can refer to different memory addresses).

However if two objects are identical (the same object) then they must be equivalent (have the same underlying values).

What type of Equality do we expect?

Clearly these notions of identity and equivalence are related to the concept of reference types and value types.

Value types are intended as lightweight objects that have value semantics: two objects are the same if they have the same value, and then can be used interchangeably. So integers a and b are the same in the example above because their values are both 3, it doesn't matter if references a and b actually refer to the same underlying object in memory.

We don't in general expect reference types to behave this way. Suppose we have two separate objects of type Book (a class). Book has one member variable called ' title ' (a string ). Do we necessarily consider these the 'same' Book if they have the same title ? We might do so, but it isn't clear.

To clarify the situation we might add an additional field ' BookId ' which is unique for a given actual book. We could then say that two books are the same if they have the same BookId , even if they have different titles. But then we wouldn't normally expect to have two separate Book s with the same BookId in memory at the same time: there's only one underlying book. So potentially we can just compare memory addresses to see if two Book s are the same.

The point is that equality for reference types is trickier to define. Our default definition is going to be that two reference types are the same if they are identical.

Types of Equality

Now I'll go through each of the types of equality referred to in the first paragraph in turn and try to explain why they exist. I'll also explain how they are implemented for value and reference types, and when you should override or overload them.

a.Equals(b)

Equals() is a virtual method on System.Object . This means every single object can call this, and in your own type definitions you can override it to give the behaviour you want.

The base System.Object implementation of Equals() is to do an identity comparison. However, Equals() is intended to test for identity or equivalence as appropriate (see the discussion in the paragraph above).

Value Types

For value types this method is overridden to do a value (equivalence) comparison. In particular, System.ValueType itself, the root of all value types, contains an override that will compare two objects by reflecting over their internal fields to see if they are all equal. If you inherit this (by setting up a struct) your struct will get this override by default.

Reference Types

For reference types, as discussed above, the situation is trickier. In general we expect Equals() for reference types to do an identity comparison (to check whether the objects actually are the same in memory).

However, certain reference types aren't lightweight enough to work as value types, but nevertheless have value semantics. The canonical example is System.String . System.String is a reference type. However if we have a = "abc" and b = "abc" we expect a to be equal to b . So in the framework Equals() is overridden to do a value comparison.

Override or not?

As mentioned above, for value types there is a default override of a.Equals(b) in the base class System.ValueType which will work for any structs you set up. This method uses reflection to iterate over all of the fields of the two value types you are trying to compare, checking that their values are equal. In general this is what you want for value type comparison.

However, the overridden Equals() method uses reflection, which is slow, and involves a certain amount of boxing. For speed optimization it can be good to override this method. For a more detailed discussion of this see Jeffrey Richter's book 'Applied Microsoft .NET Framework Programming'.

In general it is considered good practice to leave Equals() doing its default identity comparison when defining new reference types (classes). The exception is when you know you want value semantics for your class (like System.String ), or when you want Equals to work in a specific way. In particular, if your class is going to be used as a key in a Hashtable you need to override Equals if that is to be in any way efficient.

Note that if you override a.Equals(b) you should also override GetHashCode() and should consider overriding IComparable.CompareTo() .

object.Equals(a, b)

object.Equals(a, b) is a static method on the object class. Jeffery Richter describes it as 'a little helper method'. It's easiest to think of it as a method that does some checking for null s and then calls a.Equals(b) .

The reason it exists is that if a is null a call to a.Equals(b) will throw a NullReferenceException . If there's a possibility that a will be null it is easier to call object.Equals(a, b) than explicitly check for the null . If a can't be null there's no need for the additional check and a call to a.Equals(b) will be better.

In detail, this method does the following for a call to object.Equals(a, b) :

  • Check if a and b are identical (i.e. they refer to the same location in memory or are both null ). If so return true .
  • Check if either of a and b is null . We know they are not both null otherwise the routine would have returned in 1) above, so if either is null return false .
  • Both a and b are not null : return the value of a.Equals(b) .

Value Types and Reference Types

Since a and b can't be null for value types, object.Equals(a, b) is identical to a.Equals(b) . In general you should call a.Equals(b) in preference to object.Equals(a, b) for value types.

For reference types, as discussed above, you should call this method if there's a chance that a will be null in a call to a.Equals(b) .

object.Equals(a, b) is a static method on System.Object , and consequently can't be overridden. However, since it calls into a.Equals(b) any overrides of Equals will affect calls to this method as well.

object.ReferenceEquals(a, b)

Whilst the two incarnations of Equals() above check for identity or equivalence depending on the underlying type, ReferenceEquals is intended to always check for identity.

For reference types object.ReferenceEquals(a, b) returns true if and only if a and b have the same underlying memory address.

In general we shouldn't care whether value types occupy the same underlying memory address. It isn't relevant for anything we'd want to normally use them for. But the definition above gives us a problem when we come to value types being compared with ReferenceEquals .

The difficulty comes from the fact that ReferenceEquals expects two System.Objects as parameters. This means that our value types will get boxed onto the heap as they are passed in to this routine. Normally, because of the way the boxing process works, they will get boxed separately to different memory addresses on the heap. This of course means the call to ReferenceEquals returns false .

So for example object.ReferenceEquals(10, 10) returns false , for these reasons.

You can see it's the boxing that causes the problem in the following code:

ReferenceEquals is a static method on object, and so once again cannot be overridden. It will always perform identity checks as outlined above.

== is an operator, clearly, and not a method. In my humble opinion it has been included in C# largely as a syntactic convenience and to make the language look like C/C++.

As with a.Equals(b) , == is intended to test for identity or equivalence as appropriate (see the discussion in the paragraph "What type of Equality do we expect?" above. In fact, in almost all circumstances == should behave like a.Equals(b) .

For value types within the .NET Framework, == is implemented as you would expect, and will test for equivalence (value equality). However, for any custom value types you implement (structs) a default == will not be available unless you provide one.

For reference types a default == is available, and this will test for identity (reference equality). For most reference types in the .NET Framework == will again test for identity, but, as for a.Equals(b) , there are certain classes where the operator has been overloaded to do a value comparison. System.String is once again the canonical example, for the reasons discussed in part 1 of this article.

Override (overload?) or not?

Since == is an operator we can't override it. However, we can overload it to provide a different functionality to the base functionality described above.

For reference types Microsoft recommends that you don't overload == unless you have reference types behaving as value types as discussed above. This means that even if you override a.Equals(b) to provide some custom functionality you should leave your == operator to provide an identity test. This is, I think, the only occasion where == should behave differently from a.Equals(b) .

For value types , as mentioned above, a default overload of == will not be available and you will have to provide one if you need one. The easiest thing to do is simply to call a.Equals(b) from an operator overload in your struct: in general your implementation of == should not be different from a.Equals(b) .

Note that if you overload == you should overload != . You should also override a.Equals(b) to do the same thing, and as a result should overload GetHashCode . Finally you should consider overriding IComparable.CompareTo() .

Care with == and Reference Types

One final thing to note is that operator overloads don't behave like overrides. If you use the == operator with reference types without thinking, this can be a problem.

For example, suppose you have an untyped DataSet ds containing a DataTable dt . Suppose this has columns Id and Name. dt has two rows. Consider the following code:

When we compare with == in the example above we get false , even though the column in both rows contains the integer 1 . The reason is that both row1[Value] and row2[Value] return objects, not integers. So == will use the == in System.Object , not any overloaded version in integer. The == in System.Object does an identity comparison (reference equality test). The underlying values have been separately boxed onto the heap, so aren't in the same memory address, and the test fails.

When we compare with .Equals we get true. This is because .Equals is overridden in System.Int32 to do a value comparison, so the comparison uses the overridden version to correctly compare the values of the two integers.

a is b isn't actually a test for object equality at all, although it looks like one. b here has to be a type name (so b would need to be a class name, for example). The operator tests whether object a is either of type b or can be cast to it without an exception being thrown. This is equivalent to TypeOf a Is b in VB.NET, which is a little clearer.

Value Types/Reference Types

The operator works in the same way for both value types and reference types.

The operator cannot be overloaded (or overridden clearly).

The Final Twist: String Interning

On the basis of the above what should this do?

At first glance you might say that:

  • a and b are reference types containing strings (you would be right).
  • .Equals is overridden in the string class to do an equivalence (value) comparison, and the values are equal. So a.Equals(b) is true (you would still be right).
  • However, a == b is an overload and on the object type it does an identity comparison, not a value comparison (you would still be right).
  • a and b are separate objects in memory so a == b is false (you would be wrong)

4. is actually wrong, but only because of an optimization in the CLR. The CLR keeps a list of all strings currently being used in an application in something called the intern pool. When a new string is set up in code the CLR checks the intern pool to see if the string is already in use. If so, it will not allocate memory to the string again, but will re-use the existing memory. Hence a == b is true above.

You can prevent strings being interned by using a StringBuilder as below. In this case a.Equals(b) will be true , and a== b will be false , which is what you would expect:

This article has talked mainly about C#. However, the situation is similarly confusing in VB.NET. Because they are methods on System.Object , VB.NET has methods a.Equals(b) , object.Equals(a, b) and object.ReferenceEquals(a, b) which are the same as the methods described above.

VB.NET has no == operator, or any operator equivalent to it.

VB.NET additionally has the Is operator. This operator's use in TypeOf a Is b statements was discussed under a is b : Overview above.

VB.NET: a Is b

The Is operator can also be used for identity (reference equality) comparisons on two reference types in VB.NET. However, unlike a.ReferenceEquals(b) , which does the same thing for reference types, the Is operator cannot be used at all with value types. The Visual Basic compiler will not compile code where either of a or b in the statement a Is b are value types.

  • Jeffrey Richter "Applied Microsoft .NET Framework Programming" http://www.microsoft.com/mspress/books/sampchap/5353.aspx#SampleChapter
  • Interning strings http://msdn2.microsoft.com/en-us/library/system.string.intern.aspx
  • When to overload == http://msdn2.microsoft.com/en-us/library/ms173147.aspx
  • Ravi Gyani's less verbose 'Understanding Equality in C#' http://www.codeproject.com/dotnet/Equality.asp

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

vb.net assignment vs equality

Comments and Discussions

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

vb.net assignment vs equality

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

comparison-operators.md

Latest commit, file metadata and controls, comparison operators (visual basic).

The following are the comparison operators defined in Visual Basic.

< operator

<= operator

> operator

>= operator

<> operator

Is Operator

IsNot Operator

Like Operator

These operators compare two expressions to determine whether or not they are equal, and if not, how they differ. Is , IsNot , and Like are discussed in detail on separate Help pages. The relational comparison operators are discussed in detail on this page.

result Required. A Boolean value representing the result of the comparison.

expression1 , expression2 Required. Any expression.

comparisonoperator Required. Any relational comparison operator.

object1 , object2 Required. Any reference object names.

string Required. Any String expression.

pattern Required. Any String expression or range of characters.

The following table contains a list of the relational comparison operators and the conditions that determine whether result is True or False .

The = Operator is also used as an assignment operator.

The Is operator, the IsNot operator, and the Like operator have specific comparison functionalities that differ from the operators in the preceding table.

Comparing Numbers

When you compare an expression of type Single to one of type Double , the Single expression is converted to Double . This behavior is opposite to the behavior found in Visual Basic 6.

Similarly, when you compare an expression of type Decimal to an expression of type Single or Double , the Decimal expression is converted to Single or Double . For Decimal expressions, any fractional value less than 1E-28 might be lost. Such fractional value loss may cause two values to compare as equal when they are not. For this reason, you should take care when using equality ( = ) to compare two floating-point variables. It is safer to test whether the absolute value of the difference between the two numbers is less than a small acceptable tolerance.

Floating-point Imprecision

When you work with floating-point numbers, keep in mind that they do not always have a precise representation in memory. This could lead to unexpected results from certain operations, such as value comparison and the Mod Operator . For more information, see Troubleshooting Data Types .

Comparing Strings

When you compare strings, the string expressions are evaluated based on their alphabetical sort order, which depends on the Option Compare setting.

Option Compare Binary bases string comparisons on a sort order derived from the internal binary representations of the characters. The sort order is determined by the code page. The following example shows a typical binary sort order.

A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø

Option Compare Text bases string comparisons on a case-insensitive, textual sort order determined by your application's locale. When you set Option Compare Text and sort the characters in the preceding example, the following text sort order applies:

(A=a) < (À= à) < (B=b) < (E=e) < (Ê= ê) < (Ø = ø) < (Z=z)

Locale Dependence

When you set Option Compare Text , the result of a string comparison can depend on the locale in which the application is running. Two characters might compare as equal in one locale but not in another. If you are using a string comparison to make important decisions, such as whether to accept an attempt to log on, you should be alert to locale sensitivity. Consider either setting Option Compare Binary or calling the xref:Microsoft.VisualBasic.Strings.StrComp%2A, which takes the locale into account.

Typeless Programming with Relational Comparison Operators

The use of relational comparison operators with Object expressions is not allowed under Option Strict On . When Option Strict is Off , and either expression1 or expression2 is an Object expression, the run-time types determine how they are compared. The following table shows how the expressions are compared and the result from the comparison, depending on the runtime type of the operands.

Numeric comparisons treat Nothing as 0. String comparisons treat Nothing as "" (an empty string).

Overloading

The relational comparison operators ( < . <= , > , >= , = , <> ) can be overloaded , which means that a class or structure can redefine their behavior when an operand has the type of that class or structure. If your code uses any of these operators on such a class or structure, be sure you understand the redefined behavior. For more information, see Operator Procedures .

Notice that the = Operator can be overloaded only as a relational comparison operator, not as an assignment operator.

The following example shows various uses of relational comparison operators, which you use to compare expressions. Relational comparison operators return a Boolean result that represents whether or not the stated expression evaluates to True . When you apply the > and < operators to strings, the comparison is made using the normal alphabetical sorting order of the strings. This order can be dependent on your locale setting. Whether the sort is case-sensitive or not depends on the Option Compare setting.

[!code-vb VbVbalrOperators#1 ]

In the preceding example, the first comparison returns False and the remaining comparisons return True .

  • xref:System.InvalidCastException
  • Operator Precedence in Visual Basic
  • Operators Listed by Functionality
  • Troubleshooting Data Types
  • Comparison Operators in Visual Basic

Logo for Rebus Press

Want to create or adapt books like this? Learn more about how Pressbooks supports open publishing practices.

Assignment vs Equality

Kenneth Leroy Busbee

Assignment  sets and/or re-sets the value stored in the storage location denoted by a variable name. [1] Equality is a relational operator that tests or defines the relationship between two entities. [2]

Most control structures use a test expression that executes either selection (as in the: if then else) or iteration (as in the while; do while; or for loops) based on the truthfulness or falseness of the expression. Thus, we often talk about the Boolean expression that is controlling the structure. Within many programming languages, this expression must be a Boolean expression and is governed by a tight set of rules. However, in many programming languages, each data type can be used as a Boolean expression because each data type can be demoted into a Boolean value by using the rule/concept that zero and nothing represent false and all non-zero values represent true.

Within various languages, we have the potential added confusion of the equals symbol = as an operator that does not represent the normal math meaning of equality that we have used for most of our life. The equals symbol typically means: assignment. To get the equality concept of math we often use two equal symbols to represent the relational operator of equality. Let’s consider:

The test expression of the control structure will always be true because the expression is an assignment (not the relational operator of == ). It assigns the ‘y’ to the variable pig, then looks at the value in pig and determines that it is not zero; therefore the expression is true. And it will always be true and the else part will never be executed. This is not what the programmer had intended. The correct syntax for a Boolean expression is:

This example reminds you that you must be careful in creating your test expressions so that they are indeed a question, usually involving the relational operators. Some programming languages will generate a warning or an error when an assignment is used in a Boolean expression, and some do not.

Don’t get caught using assignment for equality.

  • cnx.org: Programming Fundamentals – A Modular Structured Approach using C++
  • Wikipedia: Assignment (computer science) ↵
  • Wikipedia: Relational operator ↵

Programming Fundamentals Copyright © 2018 by Kenneth Leroy Busbee is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License , except where otherwise noted.

Share This Book

Logo for Open Textbook Publishing

Want to create or adapt books like this? Learn more about how Pressbooks supports open publishing practices.

Assignment vs Equality

Kenneth Leroy Busbee

Assignment  sets and/or re-sets the value stored in the storage location denoted by a variable name. [1] Equality is a relational operator that tests or defines the relationship between two entities. [2]

Most control structures use a test expression that executes either selection (as in the: if then else) or iteration (as in the while; do while; or for loops) based on the truthfulness or falseness of the expression. Thus, we often talk about the Boolean expression that is controlling the structure. Within many programming languages, this expression must be a Boolean expression and is governed by a tight set of rules. However, in many programming languages, each data type can be used as a Boolean expression because each data type can be demoted into a Boolean value by using the rule/concept that zero and nothing represent false and all non-zero values represent true.

Within various languages, we have the potential added confusion of the equals symbol = as an operator that does not represent the normal math meaning of equality that we have used for most of our life. The equals symbol typically means: assignment. To get the equality concept of math we often use two equal symbols to represent the relational operator of equality. Let’s consider:

The test expression of the control structure will always be true because the expression is an assignment (not the relational operator of == ). It assigns the ‘y’ to the variable pig, then looks at the value in pig and determines that it is not zero; therefore the expression is true. And it will always be true and the else part will never be executed. This is not what the programmer had intended. The correct syntax for a Boolean expression is:

This example reminds you that you must be careful in creating your test expressions so that they are indeed a question, usually involving the relational operators. Some programming languages will generate a warning or an error when an assignment is used in a Boolean expression, and some do not.

Don’t get caught using assignment for equality.

  • archive.org: Programming Fundamentals – A Modular Structured Approach using C++
  • Wikipedia: Assignment (computer science) ↵
  • Wikipedia: Relational operator ↵

Programming Fundamentals Copyright © 2018 by Kenneth Leroy Busbee is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License , except where otherwise noted.

Share This Book

Library homepage

  • school Campus Bookshelves
  • menu_book Bookshelves
  • perm_media Learning Objects
  • login Login
  • how_to_reg Request Instructor Account
  • hub Instructor Commons

Margin Size

  • Download Page (PDF)
  • Download Full Book (PDF)
  • Periodic Table
  • Physics Constants
  • Scientific Calculator
  • Reference & Cite
  • Tools expand_more
  • Readability

selected template will load here

This action is not available.

Engineering LibreTexts

4.6: Assignment vs Equality

  • Last updated
  • Save as PDF
  • Page ID 10659

\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

\( \newcommand{\Span}{\mathrm{span}}\)

\( \newcommand{\id}{\mathrm{id}}\)

\( \newcommand{\kernel}{\mathrm{null}\,}\)

\( \newcommand{\range}{\mathrm{range}\,}\)

\( \newcommand{\RealPart}{\mathrm{Re}}\)

\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

\( \newcommand{\Argument}{\mathrm{Arg}}\)

\( \newcommand{\norm}[1]{\| #1 \|}\)

\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

\( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

\( \newcommand{\vectorC}[1]{\textbf{#1}} \)

\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

Assignment sets and/or re-sets the value stored in the storage location denoted by a variable name. [1] Equality is a relational operator that tests or defines the relationship between two entities. [2]

Most control structures use a test expression that executes either selection (as in the: if then else) or iteration (as in the while; do while; or for loops) based on the truthfulness or falseness of the expression. Thus, we often talk about the Boolean expression that is controlling the structure. Within many programming languages, this expression must be a Boolean expression and is governed by a tight set of rules. However, in many programming languages, each data type can be used as a Boolean expression because each data type can be demoted into a Boolean value by using the rule/concept that zero and nothing represent false and all non-zero values represent true.

Within various languages, we have the potential added confusion of the equals symbol = as an operator that does not represent the normal math meaning of equality that we have used for most of our life. The equals symbol typically means: assignment. To get the equality concept of math we often use two equal symbols to represent the relational operator of equality. Let’s consider:

The test expression of the control structure will always be true because the expression is an assignment (not the relational operator of == ). It assigns the ‘y’ to the variable pig, then looks at the value in pig and determines that it is not zero; therefore the expression is true. And it will always be true and the else part will never be executed. This is not what the programmer had intended. The correct syntax for a Boolean expression is:

This example reminds you that you must be careful in creating your test expressions so that they are indeed a question, usually involving the relational operators. Some programming languages will generate a warning or an error when an assignment is used in a Boolean expression, and some do not.

Don’t get caught using assignment for equality.

  • cnx.org: Programming Fundamentals – A Modular Structured Approach using C++
  • Wikipedia: Assignment (computer science) ↵
  • Wikipedia: Relational operator ↵

This browser is no longer supported.

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

Equality comparisons (C# Programming Guide)

  • 16 contributors

It is sometimes necessary to compare two values for equality. In some cases, you are testing for value equality , also known as equivalence , which means that the values that are contained by the two variables are equal. In other cases, you have to determine whether two variables refer to the same underlying object in memory. This type of equality is called reference equality , or identity . This topic describes these two kinds of equality and provides links to other topics for more information.

Reference equality

Reference equality means that two object references refer to the same underlying object. This can occur through simple assignment, as shown in the following example.

In this code, two objects are created, but after the assignment statement, both references refer to the same object. Therefore they have reference equality. Use the ReferenceEquals method to determine whether two references refer to the same object.

The concept of reference equality applies only to reference types. Value type objects cannot have reference equality because when an instance of a value type is assigned to a variable, a copy of the value is made. Therefore you can never have two unboxed structs that refer to the same location in memory. Furthermore, if you use ReferenceEquals to compare two value types, the result will always be false , even if the values that are contained in the objects are all identical. This is because each variable is boxed into a separate object instance. For more information, see How to test for reference equality (Identity) .

Value equality

Value equality means that two objects contain the same value or values. For primitive value types such as int or bool , tests for value equality are straightforward. You can use the == operator, as shown in the following example.

For most other types, testing for value equality is more complex because it requires that you understand how the type defines it. For classes and structs that have multiple fields or properties, value equality is often defined to mean that all fields or properties have the same value. For example, two Point objects might be defined to be equivalent if pointA.X is equal to pointB.X and pointA.Y is equal to pointB.Y. For records, value equality means that two variables of a record type are equal if the types match and all property and field values match.

However, there is no requirement that equivalence be based on all the fields in a type. It can be based on a subset. When you compare types that you do not own, you should make sure to understand specifically how equivalence is defined for that type. For more information about how to define value equality in your own classes and structs, see How to define value equality for a type .

Value equality for floating-point values

Equality comparisons of floating-point values ( double and float ) are problematic because of the imprecision of floating-point arithmetic on binary computers. For more information, see the remarks in the topic System.Double .

Related topics

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

IMAGES

  1. Invalid left-hand side in assignment in JavaScript [Solved]

    vb.net assignment vs equality

  2. What is Accessible Education? Equality vs Equity in Inclusive Learning

    vb.net assignment vs equality

  3. Equality vs Equity Storyboard by 45d1fdc7

    vb.net assignment vs equality

  4. Intelephense appears to confuse equality operator with assignment operator? · Issue #1185

    vb.net assignment vs equality

  5. 0604 Assignment Operator vs. Equality Operator

    vb.net assignment vs equality

  6. EQUALITY vs. EQUITY 11x17 Printable Classroom Poster (PNG Format)

    vb.net assignment vs equality

VIDEO

  1. Events Method in vb.net 6 vs2022 windows form app.(part 5): for beginner

  2. 2023 Java Training Session 03 Datatype Variable Operator Literal Unary Binary Ternary

  3. Mastering JavaScript Operators: Assignment, Comparison, Equality Operators

  4. ASP.NET Tutorial-CompareValidator

  5. Assignment vs Equality operator

  6. If Statements and Basic Types

COMMENTS

  1. Understanding assignment/comparison vb.net

    The equals sign (=) is used for two entirely different operators in VB.NET. It is used as the assignment operator as well as for the equality test operator. The operator, to which the character evaluates, depends on the context. So, for instance, in this example: Dim x As Integer = 1 Dim y As Integer = 2 Dim z As Integer = x = y

  2. vb.net

    In VB.NET, there's no == operator for comparison, so the = operator serves that purpose as well as assignment. I have a function, and I want it to return the boolean result of a comparison, without storing that result in a variable: Private Function foo() As Boolean. Dim bar As Integer = 1. Return bar = 2. End Function.

  3. 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

  4. Comparison Operators in Visual Basic

    The Is operator, the IsNot operator, and the Like operator have specific comparison functionalities that differ from the operators in the preceding table.. Comparing Numbers. When you compare an expression of type Single to one of type Double, the Single expression is converted to Double.This behavior is opposite to the behavior found in Visual Basic 6. ...

  5. Comparison Operators (Visual Basic)

    Comparing Strings. Visual Basic compares strings using the Like Operator as well as the numeric comparison operators. The Like operator allows you to specify a pattern. The string is then compared against the pattern, and if it matches, the result is True.Otherwise, the result is False.The numeric operators allow you to compare String values based on their sort order, as the following example ...

  6. Visual Basic .NET/Assignation and comparison operators

    MessageBox. Show ("Seven equals two is "& (7 = 2) & ".") ' The parentheses are used because otherwise, by order of operations (equals is ' processed last), it would be comparing the strings "Seven equals two is 7" and "2.". ' Note here that the & operator appends to the string. We will talk about this later. ' ' The result of this should be a message box popping up saying "Seven equals two is ...

  7. Visual Basic .NET Language Tutorial => Assignment

    There is a single assignment operator in VB. The equal sign = is used both for equality comparison and assignment. Dim value = 5. Notes. Watch out for assignment vs. equality comparison. Dim result = leftValue = rightValue. In this example you can see the equal sign being used as both a comparison operator and an assignment operator, unlike ...

  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. Visual Basic .NET

    Watch out for assignment vs. equality comparison. Dim result = leftValue = rightValue ... These are the bitwise operators in VB.NET : And, Or, Xor, Not. Example of And bitwise operation. Dim a as Integer a = 3 And 5. The value of a will be 1. The result is obtained after comparing 3 and 5 in binary for. 3 in binary form is 011 and 5 in binary ...

  10. Comparing Values for Equality in .NET: Identity and Equivalence

    VB.NET. This article has talked mainly about C#. However, the situation is similarly confusing in VB.NET. Because they are methods on System.Object, VB.NET has methods a.Equals(b), object.Equals(a, b) and object.ReferenceEquals(a, b) which are the same as the methods described above. VB.NET has no == operator, or any operator equivalent to it.

  11. docs/docs/visual-basic/language-reference/operators/comparison ...

    This repository contains .NET Documentation. Contribute to dotnet/docs development by creating an account on GitHub.

  12. Assignment vs Equality

    Assignment vs Equality Kenneth Leroy Busbee. Overview. Assignment sets and/or re-sets the value stored in the storage location denoted by a variable name. [1] Equality is a relational operator that tests or defines the relationship between two entities. [2] Discussion. Most control structures use a test expression that executes either selection (as in the: if then else) or iteration (as in the ...

  13. = Operator

    The element on the left side of the equal sign ( =) can be a simple scalar variable, a property, or an element of an array. The variable or property cannot be ReadOnly. The = operator assigns the value on its right to the variable or property on its left. The = operator is also used as a comparison operator. For details, see Comparison Operators.

  14. Assignment vs Equality

    Assignment vs Equality Kenneth Leroy Busbee. Overview. Assignment sets and/or re-sets the value stored in the storage location denoted by a variable name. [1] Equality is a relational operator that tests or defines the relationship between two entities. [2] Discussion. Most control structures use a test expression that executes either selection (as in the: if then else) or iteration (as in the ...

  15. 4.6: Assignment vs Equality

    Within various languages, we have the potential added confusion of the equals symbol = as an operator that does not represent the normal math meaning of equality that we have used for most of our life. The equals symbol typically means: assignment. To get the equality concept of math we often use two equal symbols to represent the relational ...

  16. Best Practices for Comparing Strings in .NET

    Use the String.ToUpperInvariant method instead of the String.ToLowerInvariant method when you normalize strings for comparison. Use an overload of the String.Equals method to test whether two strings are equal. Use the String.Compare and String.CompareTo methods to sort strings, not to check for equality.

  17. Equality Operators

    Some of the information on this page may be out-of-date. This section discusses overloading equality operators and refers to operator== and operator!= as equality operators. DO NOT overload one of the equality operators and not the other. ️ DO ensure that Object.Equals and the equality operators have exactly the same semantics and similar ...

  18. I want Get Is Equal operator in VB.net

    If I understand it correctly, you want an equality comparison. On VB.net the equality operator is just =. Therefore False = False returns True. Based on your example Console.WriteLine((100 <> 100) = False) should result in True. For reference: Comparison operators on VB.net. answered Oct 15, 2021 at 23:27. jmiguel.

  19. Equality Comparisons

    It is sometimes necessary to compare two values for equality. In some cases, you are testing for value equality, also known as equivalence, which means that the values that are contained by the two variables are equal. In other cases, you have to determine whether two variables refer to the same underlying object in memory.