C # ToString (string format) Extension

Source: Internet
Author: User

In. net, System. object. toString () is one of the most commonly used methods. The ToString () method is defined as virtual in the Object class, and the Object class gives it a default implementation:

1 public virtual string ToString ()
2 {
3 return this. GetType (). ToString ();
4}

In. Net, the original class or struct, such as int and DateTime, all override it to make it return more valuable values, rather than type names. It is very convenient to program and debug the ToString () method. However, after all, a class has only one ToString () method, which cannot satisfy our diversified needs. Many classes overload ToString. As follows:

1 string dateString = DateTime. Now. ToString ("yyyy"); // 2009
2 string intString = 10. ToString ("d4"); // 0010

Int and DateTime all implement the ToString (string format) method, which greatly facilitates our use.

We should also provide a reasonable ToString () rewrite for our own defined types. If we can provide another ToString (string format), it will make our later work easier. Types:

1 public class People
2 {
3 private List <People> friends = new List <People> ();
4
5 public int Id {get; set ;}
6 public string Name {get; set ;}
7 public DateTime Brithday {get; set ;}
8 public People Son {get; set ;}
9 public People [] Friends {get {return friends. ToArray ();}}
10
11 public void AddFriend (People newFriend)
12 {
13 if (friends. Contains (newFriend) throw new ArgumentNullException ("newFriend"
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.