ToString() C# with Example



ToString() C# with Example

The ToString() method is present on all reference object types. This is due to all reference types being derived from 
Object which has the ToString() method on it. The ToString() method on the object base class returns the type 
name. The fragment below will print out "User" to the console. 
public class User 
{ 
public string Name { get; set; } 
public int Id { get; set; } 
} 
... 
var user = new User {Name = "User1", Id = 5}; 
Console.WriteLine(user.ToString()); 
However, the class User can also override ToString() in order to alter the string it returns. The code fragment below 
prints out "Id: 5, Name: User1" to the console. 
public class User 
{ 
public string Name { get; set; } 
public int Id { get; set; } 
public override ToString() 
{ 
return string.Format("Id: {0}, Name: {1}", Id, Name); 
} 
} 
... 
var user = new User {Name = "User1", Id = 5}; 
Console.WriteLine(user.ToString()); 
 

0 Comment's

Comment Form

Submit Comment