Understanding C#'s `Uri.ReferenceEquals()` Method: Checking for Reference Equality
Learn how to use C#'s `Uri.ReferenceEquals()` method to determine if two `Uri` objects point to the same memory location. This tutorial clarifies the difference between reference equality and value equality when comparing URIs in C#.
Using C#'s `Uri.ReferenceEquals()` Method
The C# `Uri.ReferenceEquals()` method isn't a method specific to the `Uri` class itself; it's inherited from the base `Object` class. It checks if two `Uri` objects refer to the *same* instance in memory (reference equality), not if they represent the same URI.
Understanding Reference Equality
In C#, when you have two variables of a reference type (like `Uri`), assigning one to the other creates a new reference to the *same* object. The `ReferenceEquals()` method determines whether two variables point to the exact same memory location.
`Uri.ReferenceEquals()` Syntax
public static bool ReferenceEquals(object objA, object objB);
The method takes two objects (`objA` and `objB`) as input and returns `true` if they refer to the same object; otherwise, `false`.
Example 1: Comparing Null URIs
Uri uri1 = null;
Uri uri2 = null;
bool isEqual = Uri.ReferenceEquals(uri1, uri2); // isEqual will be true
Console.WriteLine(isEqual);
Example 2: Comparing URIs
Uri uri1 = new Uri("https://www.example.com");
Uri uri2 = new Uri("https://www.example.com");
Uri uri3 = uri1;
// ... (code to test using ReferenceEquals and print results) ...
Advantages of `Uri.ReferenceEquals()`
- Direct Reference Comparison: Quickly determines if two variables point to the same object instance in memory.
- Handles Nulls: Gracefully handles null values.
- Performance: Faster than comparing URI values.
- Memory Management: Useful for understanding object identity in memory management scenarios.