Simple and Very Intersting Problem:
From the below Code, I was wondering that In both conditions the Check
variable will be true
but i was wrong.
using System;
namespace Problem
{
class Program
{
static void Main(string[] args)
{
int firstNumber = 1;
int secondNumber = 9;
bool Check = false;
Console.WriteLine("Checking First Condition.");
Console.WriteLine("------------------");
if (firstNumber == (firstNumber = secondNumber))
{
Check = true;
Console.WriteLine("First Check : {0}", Check);
}
else
{
Check = false;
Console.WriteLine("First Check : {0}", Check);
}
Console.WriteLine("------------------");
Console.WriteLine();
Console.WriteLine("Checking Second Condition.");
Console.WriteLine("------------------");
// Resetting firstNumber value:
firstNumber = 1;
if ((firstNumber = secondNumber) == firstNumber)
{
Check = true;
Console.WriteLine("Second Check : {0}", Check);
}
else
{
Check = false;
Console.WriteLine("Second Check : {0}", Check);
}
Console.WriteLine("------------------");
}
}
}
But from while ago and thinking about it. but i can't get it why the first condition returning True
Dry Runs:
First Condition. (1 == (1 = 9) // firstnumber = 9. so 9 == 9 // True.
Second Condition. ((1 = 9) == 1) // firstnumber = 9. so 9 == 9 // True.
Output:
Can someone explain breifly what is happening under the hood ?
// What is done by a C# Compiler in both the cases ?.
conditions/expressions are evaluated from left to right. so,
int firstNumber = 1;
int secondNumber = 3;
First Case:
firstNumber == (firstNumber = secondNumber)
1 == (firstNumber = secondNumber)
1 == ( 1 = secondNumber)
1 == ( 1 = 3 )
1 == 3
false
Second Case:
((firstNumber = secondNumber) == firstNumber)
( 1 = secondNumber) == firstNumber
( 1 = 3 ) == firstNumber
( 3 ) == firstNumber //firstNumber became 3
3 == 3
true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.