Composition vs Inheritance - Inheritance shows -is-a relation. Composition shows - has-a relation.
extension methods in c#
extension methods in c#
- An extension method is defined as static method but it is called like as instance method.
- An extension method first parameter specifies the type of the extended object, and it is preceded by the "this" keyword.
- An extension method having the same name and signature like as an instance method will never be called since it has low priority than instance method.
- An extension method can't override the existing instance methods.
- An extension method cannot be used with fields, properties or events.
- The compiler doesn't cause an error if two extension methods with same name and signature are defined in two different namespaces and these namespaces are included in same class file using directives. Compiler will cause an error if you will try to call one of them extension method.
- //defining extension method
- public static class MyExtensions
- {
- public static int WordCount(this String str)
- {
- return str.Split(new char[] { ' ', '.', ',' }).Length;
- }
- }
- class Program
- {
- public static void Main()
- {
- string s = "Dot Net Tricks Extension Method Example";
- //calling extension method
- int i = s.WordCount();
- Console.WriteLine(i);
- }
- }
Chaining of extension method
- public static class ExtensionClass
- {
- public static string Pluralize (this string s) {...}
- public static string Capitalize (this string s) {...}
- }
- //we can do chainig of above methods like as
- string x = "Products".Pluralize().Capitalize();
Removing ambiguity
- static class StringExtension
- { // first method
- public static bool IsCapitalized (this string s) {...}
- }
- static class ObjectExtension
- {
- // second method
- public static bool IsCapitalized (this object s) {...}
- }
- // code here
- // first method is called
- bool flag1 = "Dotnet-Tricks".IsCapitalized();
- // second method is called
- bool test2 = (ObjectHelper.IsCapitalized ("Dotnet-Tricks"));
No comments:
Post a Comment