In C#, static methods could only be called through their respective type references. The power of Extensions Methods lies in the fact they could be called on an object instance. In fact, they could ONLY be called on an object instance. This ability is vital for implementing Linq in C# 3.0.
1 using System;2 using System.Collections.Generic;3 using System.Linq;4 using System.Text;5
6 namespace TestBed7 {
8
9 public class TestExtensionMethods10 {
11 public static void Main()12 {
13
14 string val = "Vyas";15
16 //Static method of string class called through the class17 Console.WriteLine("Is Internered: {0}", string.IsInterned(val));18
19 //Static method called through an instance20 //Intellisense does not display it21 //Error: Member 'string.IsInterned(string)' cannot be22 //accessed with an instance reference;23 //qualify it with a type name instead24 //Console.WriteLine(val.IsInterned(val));25
26
27 //The ability for a static method to be called through an instance28 Console.WriteLine(val.Reverse());29
30 //Does not compile31 //Error: 'string' does not contain a definition for 'Reverse'32 //Console.WriteLine(string.Reverse(val));33 Console.Read();34 }
35
36 }
37
38 public static class StringUtils39 {
40 public static string Reverse(this string arg)41 {
42 char [] reversed;43 Array.Reverse(reversed = arg.ToCharArray());44 return new string(reversed);45
46 }
47 }
48
49
50 }
Sunday, July 06, 2008
Extension Methods: Calling on an object instance
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment