Can extension methods be applied to the class?
For example, extend DateTime to include a Tomorrow() method that could be invoked like:
DateTime.Tomorrow();
I know I can use
static DateTime Tomorrow(this Datetime value) { //... }
Or
public static MyClass { public static Tomorrow() { //... } }
for a similar result, but how can I extend DateTime so that I could invoke DateTime.Tomorrow?
You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself.
Definition and UsageThe extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class.
Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class.
C# does not support multiple inheritance , because they reasoned that adding multiple inheritance added too much complexity to C# while providing too little benefit. In C#, the classes are only allowed to inherit from a single parent class, which is called single inheritance .
Use an extension method.
Ex:
namespace ExtensionMethods { public static class MyExtensionMethods { public static DateTime Tomorrow(this DateTime date) { return date.AddDays(1); } } }
Usage:
DateTime.Now.Tomorrow();
or
AnyObjectOfTypeDateTime.Tomorrow();
You cannot add methods to an existing type unless the existing type is marked as partial, you can only add methods that appear to be a member of the existing type through extension methods. Since this is the case you cannot add static methods to the type itself since extension methods use instances of that type.
There is nothing stopping you from creating your own static helper method like this:
static class DateTimeHelper { public static DateTime Tomorrow { get { return DateTime.Now.AddDays(1); } } }
Which you would use like this:
DateTime tomorrow = DateTimeHelper.Tomorrow;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With