-1

With a sample code I have below, Im trying to understand what is the exact difference between "=" operator vs "==" in the where clause?

I have list of items with a property of IsActive. When I do this:

GetAllItemsFromCache -- just returns List<Item> 2 of them are IsActive False, 8 of them are True

// this return 10 items whereas 2 of them were `IsActive` property was set to `false`in the initial list, but now IsActive seems true for all the items
bool someFlag = true;
var result = GetAllItemsFromCache().Where(i => i.IsActive = someFlag).ToList(); 

// this return nothing - In the list 2 of them were `IsActive` property was set to `false` 
bool someFlag = false;
var result = GetAllItemsFromCache().Where(i => i.IsActive = someFlag).ToList(); 

// using regular == operator just returns as expected based on the flag. No question here
bool someFlag = false;
var result = GetAllItemsFromCache().Where(i => i.IsActive == someFlag).ToList(); 

Can someone explain? (or if you share a link so I can read details)

curiousBoy
  • 6,334
  • 5
  • 48
  • 56
  • 2
    `=` is assignment. Do not use it if you do not want to assign a new value. `==` is comparison, use it when you want to check for equality. – crashmstr Jun 26 '20 at 15:44
  • 3
    `i.IsActive = someFlag` means you are assigning `someFlag` to `IsActive` and then return the value of `IsActive`. – Sean Jun 26 '20 at 15:44
  • But it returns nothing when the someFlag is false tho. Wouldnt it return all the items and assign their IsActive to false in that case? – curiousBoy Jun 26 '20 at 15:46
  • @Sean - Does that work exact same way with .ForEach(x=>x.IsActive = someFlag) ? So basically var result = GetAllItemsFromCache().ForEach(x=>x.IsActive = someFlag).Where(i => someFlag == true).ToList(); same with what I have in post? – curiousBoy Jun 26 '20 at 15:53

2 Answers2

3

In C#, the assignement expression using the = operator returns the assigned value, so since someFlag is a boolean, the value returned by i.IsActive = someFlag is the value of someFlag

Here is the language specification :

The result of a simple assignment expression is the value assigned to the left operand. The result has the same type as the left operand and is always classified as a value.

More information here : https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#assignment-operators

antoninod
  • 338
  • 3
  • 10
0

In C# the '=' is used when a variable is initalized.

int a = 5;
int b = 6;

Here 'a' equals with 5 and 'b' equals with 6.

The '==' is used when you want to decide something.

int a = 5;
int b = 6;
bool c = true;
if (a == b){
    c = true
}
else{
    c = false
}

This piece of code gives true out when 'a' and 'b' equals.

redfox23
  • 21
  • 3