Training
Module
Implement Class Inheritance - Training
Learn how to create a class hierarchy using base and derived classes and how to hide or override members of a derived class by using `new`, `virtual`, `abstract`, and `override` keywords.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Every class or struct in C# implicitly inherits the Object class. Therefore, every object in C# gets the ToString method, which returns a string representation of that object. For example, all variables of type int
have a ToString
method, which enables them to return their contents as a string:
int x = 42;
string strx = x.ToString();
Console.WriteLine(strx);
// Output:
// 42
When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code.
For information about how to use format strings and other types of custom formatting with the ToString
method, see Formatting Types.
Important
When you decide what information to provide through this method, consider whether your class or struct will ever be used by untrusted code. Be careful to ensure that you do not provide any information that could be exploited by malicious code.
To override the ToString
method in your class or struct:
Declare a ToString
method with the following modifiers and return type:
public override string ToString(){}
Implement the method so that it returns a string.
The following example returns the name of the class in addition to the data specific to a particular instance of the class.
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return "Person: " + Name + " " + Age;
}
}
You can test the ToString
method as shown in the following code example:
Person person = new Person { Name = "John", Age = 12 };
Console.WriteLine(person);
// Output:
// Person: John 12
.NET feedback
.NET is an open source project. Select a link to provide feedback:
Training
Module
Implement Class Inheritance - Training
Learn how to create a class hierarchy using base and derived classes and how to hide or override members of a derived class by using `new`, `virtual`, `abstract`, and `override` keywords.
Documentation
Constants in C# are compile-time literal values, which do not change once the program is compiled. Only C# built-in types can be constants.
Casting and type conversions - C#
Learn about casting and type conversions, such as implicit, explicit (casts), and user-defined conversions.
new operator - Create and initialize a new instance of a type - C# reference
The C# new operator is used to create a optionally initialize a new instance of a type.