Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension Method Overriding

Let's assume that I have two class.

public class A {...} 
public class B : A {...}

What I want is to achieve is to override an extension function for both type.

public static void HelperExtension(this A a) {...}
public static void HelperExtension(this B b) {...}

I know that they are not virtual functions or behave like them. However I really wonder compiler behavior in this case.

Is there a way to call the function for type B without resolving its type? Or any auto-resolve suggestions?

like image 461
ozanbora Avatar asked Mar 15 '13 14:03

ozanbora


People also ask

Can we override method in extension Swift?

If a protocol defines a method, and provides a default implementation in an extension, a class can override that method, and the override will be called for any reference to the instance, even if the reference's type is declared as the protocol.

What is extension method with example?

An extension method is actually a special kind of static method defined in a static class. To define an extension method, first of all, define a static class. For example, we have created an IntExtensions class under the ExtensionMethods namespace in the following example.

What is extension method in Java?

In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are features of some object-oriented programming languages.

Are there extension methods in Java?

Java does not support extension methods. Instead, you can make a regular static method, or write your own class.


1 Answers

This is not overriding - it is overloading, if anything.

It is fine - since the signatures are different, the compiler will not have any problem compiling it, even in the same namespace.

However, which extension method will be called depends on the exact type of the variable.


Now:

Is there a way to call the function for type B without resolving its type? Or any auto-resolve suggestions?

Without casting this is not possible. The extension is bound to the exact type that is being extended, so you need to have the exact type in order to call an extension on it.

This is why most of LINQ is defined on IEnumerable<T>.

like image 71
Oded Avatar answered Oct 05 '22 00:10

Oded