Equality operators - which way is best?

Page 1 of 1

3 Replies - 12942 Views - Last Post: 06 June 2012 - 08:00 PM

#1 DimitriV

• vexing conundrum

Reputation: 587
• Posts: 2,746
• Joined: 24-July 11

Equality operators - which way is best?

Posted 14 March 2012 - 01:03 PM

I've been expanding my programming ventures lately and I've come across this operator:
==
Which is used in comparisons. In VB I've found that people use this for setting and testing of values:
=
However, I think I prefer the == method as the = symbol is used for replacing what ever is on the left side with whatever is on the right.
What do you think of this? What's your preferred method?
Is This A Good Question/Topic? 0

Replies To: Equality operators - which way is best?

#2 nK0de

• Catch me As Exception

Reputation: 206
• Posts: 823
• Joined: 21-December 11

Re: Equality operators - which way is best?

Posted 14 March 2012 - 01:16 PM

Can you use == operator in VB.NET? I don't think so. In C# however, it is the preferred way.
Was This Post Helpful? 0

#3 AdamSpeight2008

• MrCupOfT

Reputation: 2298
• Posts: 9,535
• Joined: 29-May 08

Re: Equality operators - which way is best?

Posted 14 March 2012 - 04:40 PM

The equality operation is contextual in vb.net, so == isn't needed.
```Dim A=3
Dim B=4
Dim result = (A = B)/>
```

A = B this is an value equality check (assuming it hasn't be overridden)
The first = is an assignment.

```   {variable} = {exppression} Assignment
{exppression} = {exppression} Value Equality Check
{exppession} Is {exppression} Reference Equality Check

```

This post has been edited by AdamSpeight2008: 14 March 2012 - 04:41 PM

Was This Post Helpful? 0

#4 BobRodes

• Lovable Curmudgeon

Reputation: 600
• Posts: 3,069
• Joined: 19-May 09

Re: Equality operators - which way is best?

Posted 06 June 2012 - 08:00 PM

nK0de, on 14 March 2012 - 03:16 PM, said:

Can you use == operator in VB.NET? I don't think so. In C# however, it is the preferred way.

VB.Net doesn't have a == operator; the = operator is overloaded to handle both assignment and equality. In C#, == isn't the preferred way, it's the required way. They are actually two different operators: = is the assignment operator and == is the equality operator. They aren't interchangeable. A good defensive programming technique is to do this: if(3 == x) rather than the reverse which is more common. In this way, accidentally using the assignment operator will always produce a syntax error on the line rather than in some cases assigning the integer value to the variable, thereby creating a much more difficult to find logical error.

This post has been edited by BobRodes: 06 June 2012 - 08:02 PM

Was This Post Helpful? 1

Page 1 of 1

 Query failed: unknown local index 'forums_search_posts_main' in search request.