Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way in C# to override a class method with an extension method?

There have been occasions where I would want to override a method in a class with an extension method. Is there any way to do that in C#?

For example:

public static class StringExtension {     public static int GetHashCode(this string inStr)     {         return MyHash(inStr);     } } 

A case where I've wanted to do this is to be able to store a hash of a string into a database and have that same value be used by all the classes that use the string class's hash (i.e. Dictionary, etc.) Since the built-in .NET hashing algorithm is not guaranteed to be compatible from one version of the framework to the next, I want to replace it with my own.

There are other cases I've run into where I'd want to override a class method with an extension method as well so it's not just specific to the string class or the GetHashCode method.

I know I could do this with subclassing off an existing class but it would be handy to be able to do it with an extension in a lot of cases.

like image 634
Phred Menyhert Avatar asked May 22 '09 19:05

Phred Menyhert


People also ask

What is the fastest way to learn C?

Most easy way is to get familiar with a compiler and start writing basic programs on it .

Is there an alternative to C?

The best alternative is Java. It's not free, so if you're looking for a free alternative, you could try Rust or C++. Other great apps like C (programming language) are Go (Programming Language), C#, Lua and Perl.

Is C used anymore?

There is at least one C compiler for almost every existent architecture. And nowadays, because of highly optimized binaries generated by modern compilers, it's not an easy task to improve on their output with hand written assembly.

How do you check if a pointer is freed or not?

You can't. The way to track this would be to assign the pointer to 0 or NULL after freeing it. However as Fred Larson mentioned, this does nothing to other pointers pointing to the same location.


2 Answers

No; an extension method never takes priority over an instance method with a suitable signature, and never participates in polymorphism (GetHashCode is a virtual method).

like image 73
Marc Gravell Avatar answered Sep 25 '22 02:09

Marc Gravell


If the method has a different signature, then it can be done -- so in your case: no.

But otherwise you need to use inheritance to do what you are looking for.

like image 28
Chris Brandsma Avatar answered Sep 22 '22 02:09

Chris Brandsma