0
0
C Sharp (C#)programming~10 mins

String comparison and equality in C Sharp (C#) - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - String comparison and equality
Start
Get string1
Get string2
Compare strings
Are strings equal?
YesOutput: Equal
Output: Not Equal
End
This flow shows how two strings are taken, compared for equality, and then outputs if they are equal or not.
Execution Sample
C Sharp (C#)
string s1 = "Hello";
string s2 = "hello";
bool areEqual = s1 == s2;
Console.WriteLine(areEqual);
This code compares two strings for equality and prints True or False.
Execution Table
StepVariable/ExpressionValueCondition/CheckAction/Output
1s1"Hello"N/AAssign string "Hello" to s1
2s2"hello"N/AAssign string "hello" to s2
3areEqual = s1 == s2FalseCompare "Hello" == "hello"Result is False because of case difference
4Console.WriteLine(areEqual)FalsePrint value of areEqualOutput: False
💡 Comparison done, output printed, program ends.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
s1null"Hello""Hello""Hello""Hello"
s2nullnull"hello""hello""hello"
areEqualundefinedundefinedundefinedFalseFalse
Key Moments - 2 Insights
Why does s1 == s2 return False even though the words look similar?
Because string comparison in C# is case-sensitive by default, "Hello" and "hello" differ in letter case, so the comparison returns False as shown in step 3 of the execution_table.
Can we use == to compare strings safely in C#?
Yes, == compares string contents, not references, so it works for equality checks as shown in step 3. But it is case-sensitive.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of areEqual at step 3?
AFalse
BTrue
Cnull
DUndefined
💡 Hint
Check the 'Value' column at step 3 in execution_table.
At which step is the output printed to the console?
AStep 1
BStep 2
CStep 4
DStep 3
💡 Hint
Look for Console.WriteLine action in the execution_table.
If s2 was "Hello" instead of "hello", what would be the value of areEqual at step 3?
AFalse
BTrue
Cnull
DUndefined
💡 Hint
Consider how == compares strings case-sensitively as shown in step 3.
Concept Snapshot
String comparison in C# uses == to check if contents are equal.
Comparison is case-sensitive by default.
"Hello" == "hello" is False.
Use String.Equals with StringComparison for case-insensitive checks.
Console.WriteLine prints the boolean result.
Full Transcript
This example shows how two strings s1 and s2 are assigned values "Hello" and "hello" respectively. Then, the equality operator == compares them. Because C# string comparison is case-sensitive, the result is False. Finally, the program prints False to the console. Beginners often wonder why similar words are not equal; it's due to case sensitivity. The == operator compares string contents, not references, so it is safe for equality checks. If both strings had the same case, the result would be True.