C # common string extension

Source: Internet
Author: User

String is the most commonly used class in c #. Compared with its usage frequency, string has few operations. There are only about 30 instance methods and more than 10 static methods, it is far from meeting our daily needs.
This article uses the extension method to add the string function. Here are several examples!

First, we extend IsNullOrEmpty, the most common static method of the string class, to the "instance" method:
Public static bool IsNullOrEmpty (this string s)
{
Return string. IsNullOrEmpty (s );
} The following is the call code: 1 public static void Test1 ()
2 {
3 string s = "";
4 bool b1 = string. IsNullOrEmpty (s );
5 bool b2 = s. IsNullOrEmpty ();
6}

Don't underestimate this step. After expansion, we can reduce the time for coding and increase the encoding speed. If you have doubts about this, you can enter the code of lines 4th and lines 5th manually for 100 times (you cannot copy and paste the Code) and try again!
If you need it, you can also extend "IsNotNullOrEmpty ".

Let's take a look at the FormatWith extension.
 

Public static string FormatWith (this string format, params object [] args)
{
Return string. Format (format, args );
}
Public static void Test2 ()
{
String today = "Today is: {0: yyyy, MM, dd, dd, week ddd}". FormatWith (DateTime. today );
}

It is also very simple. Here we will briefly discuss the efficiency problem. The string. Format function has multiple overloading:
 

1 public static string Format (string format, params object [] args );
2 public static string Format (string format, object arg0 );
3 public static string Format (string format, object arg0, object arg1 );
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.