Could someone please explain this for me, how this even work??
How is it even possible to return anything out of ToString(), without creating an actual method?
using System;
namespace ConsoleApplication4
{
class Person
{
private string name;
private int age;
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
**/*
* What is ToString() method?
* What I am overriding Here?
*/**
public override string ToString()
{
return "Name= " + Name + " Age=" + Age;
}
}
class Sample
{
static void Main(string[] args)
{
Person P1 = new Person();
P1.Name = "ABC";
P1.Age = 21;
Console.WriteLine(P1.ToString());
Console.ReadLine();
**//Ouput Name = ABC Age = 23**
}
}
}
All classes and structs in C# derive implicitly from System.Object. You are overriding Object.ToString.
In C#, when you write:
class Person
{
It's effectively the same as writing
class Person : System.Object
{
How is it even possible to return anything out of ToString(), without creating an actual method?
If you don't override ToString, you'll get the default implementation provided by System.Object.ToString().
The implicit base class being System.Object is documented in 4.2.2 of the C# language spec:
The object class type is the ultimate base class of all other types. Every type in C# directly or indirectly derives from the object class type.
The keyword object is simply an alias for the predefined class System.Object.
Note that it's slightly different with a custom struct, since value types derive from System.ValueType, but System.Object is still part of the inheritance hierarchy.
This is documented in 4.1.1 of the C# language spec:
All value types implicitly inherit from the class System.ValueType, which, in turn, inherits from class object. It is not possible for any type to derive from a value type, and value types are thus implicitly sealed (§10.1.1.2).
Note that System.ValueType is not itself a value-type. Rather, it is a class-type from which all value-types are automatically derived.
how is it even possible to return anything out of ToString(), without creating an actual method
The default implementation of Object.ToString() is simply:
return GetType().ToString();
This returns the (unqualified) name of the type. If you had not overridden it on your Person class, then it would have returned "Person".
Subclasses are free to override this method to return a more useful string, which might include some of the object's state, or even a human-friendly representation of the object. (DateTime does this, for example.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With