Some Standard C# Object Methods That You Might Want to Override
Written on
Alright, I’ll get it straight to the point, since this is just a note to myself anyway,
First one, the ToString() :
:::csharp
class YourClass{
private string name;
private int age;
public override string ToString()
{
return "Name: "+this.name+",Age: "+this.age.toString();
}
}
The reason to this is, simple, to have an easy way to get a string
representation of your object. Of course, in a way, you can also create
a new method to return the same thing, but it is a good idea to do it
the “C# way”, and the ToString method is always there, so why create two
methods that serve the same purpose? This is similar to the
__string__
method in Python.
The second one, Equals():
:::csharp
public class MyClass
{
private int x;
private int y;
public override bool Equals(object obj)
{
MyClass myclass = (MyClass)obj;
if(myclass.x == this.x && myclass.y == this.y)
{
return true;
}
else
{
return false;
}
}
}
The reason to do this, is so to have an easy way to compare objects in C#, as objects are stored as references, a ‘==’ comparison will always return false, even if they have the same properties values, unless they actually refer to the same object. The reason to override this method instead of creating a new one, is the same as the reason to override the ToString() method I mentioned above.