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

#1 DimitriV  Icon User is offline

  • They don't think it be like it is, but it do
  • member icon

Reputation: 584
  • View blog
  • Posts: 2,738
  • 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  Icon User is offline

  • Catch me As Exception
  • member icon

Reputation: 205
  • View blog
  • 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  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2268
  • View blog
  • Posts: 9,482
  • 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  Icon User is offline

  • Your Friendly Local Curmudgeon
  • member icon

Reputation: 574
  • View blog
  • Posts: 2,989
  • Joined: 19-May 09

Re: Equality operators - which way is best?

Posted 06 June 2012 - 08:00 PM

View PostnK0de, 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