Loading...

C# Equals

Compare string text with Equals so matching words print True. Inside Pine.Main, build string a = "red"; and string b = "red";, then print a.Equals(b). Add string c = "blue"; and print a.Equals(c). Run with dotnet run. The screen should show True, then False. A second demo builds two fresh string objects that both hold red, so == and Equals still print True while object.ReferenceEquals prints False. Leave debugging for the next page. This lesson is text match versus being the same object.

Match text with Equals

The polymorphism page ran different Horn bodies through Machine variables and printed tone, honk, and beep. This page compares text. Open the Pine file. The starting class name stays Pine. Delete leftover Machine, Truck, and Car demos if they bury the string story, leftover abstract fills, leftover Path demos, and any ReadLine line. The program must not wait for typing. Keep using System; at the top.
Inside Main, build three strings:
string a = "red";
string b = "red";
string c = "blue";
Print the comparisons:
Console.WriteLine(a.Equals(b));
Console.WriteLine(a.Equals(c));
The method Equals looks at the characters. Same text returns true. Different text returns false. The call is Equals with a capital E. Java writes equals in lowercase. Do not copy that spelling into this file.

Pine Equals red and blue

csharp
using System;

public class Pine
{
    public static void Main()
    {
        string a = "red";
        string b = "red";
        string c = "blue";
        Console.WriteLine(a.Equals(b));
        Console.WriteLine(a.Equals(c));
    }
}

Save, then run with dotnet run. The screen shows True, then False. Walk the run once. C# starts at Pine.Main. a.Equals(b) compares red with red and prints True. a.Equals(c) compares red with blue and prints False. You called a method on a and passed the other string as the argument.
Read the capital letters on the screen. Console.WriteLine prints a bool as True or False, with a capital first letter. The source words true and false are lowercase. The screen words are not. If you hunt for a lowercase true line, you will think the program failed when it actually printed True.
The comparison is case-sensitive. "Red".Equals("red") is false, because R and r are different characters. This page keeps both teaching words fully lowercase so the match is only about the letters you chose, not about capitals inside the text.
If you also print a == b for these two red literals, the screen shows True as well. For string, the == sign compares the text. It does not ask whether the two variables are the same object. Java often uses == for object identity. C# does not, once the values are strings. Prefer Equals or == when you care about the words. The next demo shows the check that really asks about identity.
If you still see tone, honk, or beep from a polymorphism file, move to the equals file and run again. If you print the strings themselves instead of the Equals results, you will see red and blue on the screen. Wrap a.Equals(b) inside WriteLine so the bool appears.
Say the rule out loud while you watch the screen: Equals asks whether the text matches character by character. Do not invent a debugger window on this page. Debugging waits for the next lesson.

Separate the same object from the same text

A second program builds two fresh string objects that both hold red. It prints a == b, then object.ReferenceEquals(a, b), then a.Equals(b).

Pine == Equals and ReferenceEquals

csharp
using System;

public class Pine
{
    public static void Main()
    {
        string a = new string("red".ToCharArray());
        string b = new string("red".ToCharArray());
        Console.WriteLine(a == b);
        Console.WriteLine(object.ReferenceEquals(a, b));
        Console.WriteLine(a.Equals(b));
    }
}

Run again with dotnet run. The screen shows True, then False, then True. Walk the three lines. new string("red".ToCharArray()) builds a new string object from those characters. Doing it twice builds two objects. Both hold the letters r, e, d.
a == b prints True because == on string compares the text. a.Equals(b) prints True for the same reason. object.ReferenceEquals(a, b) prints False because a and b are two objects, not one object stored in two variables. That third check is the identity question. == is not that question for strings.
Read the three prints in order. Text with ==. Identity with ReferenceEquals. Text again with Equals. Keep all three so the contrast stays on one screen. If you only print ==, you never see the False that proves the objects are distinct.
Two quoted literals can be a different story. C# may reuse one pooled object for "red" written twice, so ReferenceEquals on those literals can print True by accident. This demo uses new string on purpose so identity stays False while the text stays a match. When you care about the words, use Equals or ==. When you care whether two variables point at one object, use ReferenceEquals.
Do not call Equals on a string variable that holds no object. If a is null, a.Equals(b) stops the program. A null check belongs with the nullable lesson. This page keeps every string filled with text.
If leftover polymorphism demos still sit nearby, keep them as history. For this lesson, run the equals file so the screen shows True and False, not horn words.

Compared with polymorphism calls

On the polymorphism page, one method name ran different bodies through parent-typed variables. On this page, Equals answers whether two strings hold the same text, == answers the same text question for string, and ReferenceEquals answers whether they are the same object. You still run with dotnet run. The new pieces are Equals, the screen words True and False, and object.ReferenceEquals.
If a leftover Machine t = new Truck() file is still the one you run, you will see Horn calls. Move to the equals file so Main builds strings and prints comparison results. Keep debugging-tool demos off this page. Keep keyboard input off this page.

What this leaves for debugging

This page compares string text and shows why == is a text check for string, not an identity check. The next page shows debugging, where you find why a program misbehaves by reading the screen and the source together. Stay with Equals, ==, and ReferenceEquals here. Do not require a debugger walkthrough yet.
When you later debug a wrong branch, a failed text check is a common cause. A capital letter, a swapped ReferenceEquals, or a print of the string instead of the bool will send you to the wrong line. Treat this page as the comparison half of that story. Run both Pine demos until True then False, and True then False then True, feel automatic before you open the debugging lesson.

Before debugging

You can call a.Equals(b) on matching red text and see True, then see False for blue. You can build two fresh red strings and see == print True, ReferenceEquals print False, and Equals print True. Run Pine with dotnet run for each kept demo in turn. Text match and object identity stayed separate. The next page is debugging, where you hunt mistakes with the screen and the source side by side.
Keep the three-string Equals demo for a clear text check. Keep the new string demo for a clear identity contrast. Keep debugging files off this page. Those three habits are the checkpoint before you move on. When Equals prints True for matching text, and when ReferenceEquals prints False for two new objects with that text, this lesson did its job, and you are ready for the next topic about debugging.
One last pass through the file: one Pine with Main, string comparisons, capital Equals, no keyboard wait, and no forced debugger. Run dotnet run once more on the demo you keep open. If the screen still prints the bools you expect, the comparison story is solid.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
6
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top