Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I replace a C# method with another with the same name and signature?

Tags:

c#

.net

I have a following situation. Some .Net runtime method doesn't work very well and I need to craft a workaround. Like there's SqlCommand.ExecuteReader() which sometimes returns a closed reader object and I want to have code like this:

 SqlDataReader MyExecuteReader( this SqlCommand command )
 {
     var reader = command.ExecuteReader();
     if( reader.IsClosed() ) {
        throw new ClosedReaderReturnedException();
     }
     return reader;
 }

This would be just fine except I now need to change all the code that calls ExecuteReader() so that it now calls MyExecuteReader() and it makes maintenance harder.

Is there a way to somehow declare that whenever any of my code wants SqlCommand.ExecuteReader() called MyExecuteReader() is called instead? Effectively is it possible to replace an existing method with another one having exactly the same signature and the same name?

like image 886
sharptooth Avatar asked Jan 09 '13 06:01

sharptooth


People also ask

Can I replace my AC by myself?

Simply put, no, you cannot replace your AC unit yourself. Even if you have the technical know-how to install an AC unit, all of the electrical components add an elevated level of risk to the process. Plus, it takes nuanced HVAC experience to ensure you get the right unit for the size of your house.

Can I replace my AC without replacing furnace?

If your existing furnace and your new air conditioner are compatible, you don't necessarily need to replace both systems. This is usually the case when you replace your air conditioner with a similar model. A new furnace could boost your system's efficiency.

Is it worth replacing air conditioner?

If you have a relatively new AC unit, unless the cost of repairs runs into thousands of dollars, it rarely makes financial sense to replace it with a new one. Many HCAV pros use the “5,000 rule” as a general guide.


1 Answers

No, what you want is not supported. If the class is not sealed, and the method is not static, you could inherit the class with the same name in a different namespace and change the using, and override the method. But that is a limited solution.

Your best option would be to implement standart extension method with a different name, and replace all usages. This might seems like a lot of work in a large code base, and might be prone to human errors down the road - someone adding new call to the original method. However, the one time cost is offset by the fact that your code now is explicit that you have made modifications to the behavior; and you can guard against human errors by writing your own custom FxCop rule (or whatever static analysis tool you are running regularly).

like image 170
Franci Penov Avatar answered Sep 28 '22 23:09

Franci Penov