Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between string.Equals() and "string".Equals()

I am new to C# and found two ways to compare strings. Whats the difference between these approaches?

var a = "hello";
var b = "hello";

a.Equals(b);
string.Equals(a, b);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The difference is that a.Equals(b) throws an exception if a is null:

string a = null;
string b = "hello";

a.Equals(b); // throws a NullReferenceException
string.Equals(a, b); // returns false

Especially when you know that the strings could be null (for example user inputs) it’s safer to use string.Equals(a, b).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading