C# 3.5: Extending System.String
Posted @ Sep 01, 2008 01:36 AM | Permalink
With the new extension method feature of C# 3.5 it's now easy to extend your classes for additional functionality. Here are some useful functionalities to add to your favorite System.String:

1
2 // Sample namespace
3 namespace CompanyName.ProjectName.Common {
4 public static class StringExtension {
5 public static string Left(
6 this string text,
7 int length
8 ) {
9
10 if (text.Length < length) {
11 return text;
12 }
13
14 return text.Substring(0, length);
15 }
16
17 public static string Right(
18 this string text,
19 int length
20 ) {
21
22 if (text.Length < length) {
23 return text;
24 }
25
26 return text.Substring(
27 text.Length - length,
28 length
29 );
30 }
31
32 public static string Mid(
33 this string text,
34 int start
35 ) {
36
37 return Mid(
38 text,
39 start,
40 text.Length - (start - 1)
41 );
42 }
43
44 public static string Mid(
45 this string text,
46 int start, int length
47 ) {
48
49 if (text.Length < length + 1) {
50 length = text.Length - 1;
51 }
52
53 return text.Substring(start - 1, length);
54 }
55 }
56 }
57


Sample usage would be like this:

1
2 string text = "ABCDE";
3
4 Console.WriteLine(text.Left(1));
5 Console.WriteLine(text.Right(2));
6 Console.WriteLine(text.Mid(3));
7 Console.WriteLine(text.Mid(3, 1));
8
9 // Output:
10 A
11 DE
12 CDE
13 C
14

No Comments

Leave a Comment

(optional)

2 + 3 =
Enter the sum of the 2 numbers above.