Hiding a method from a VB class in a derived C# class

502 Views Asked by At

I'm writing a set of unit tests for a large, complex class called ImageEditor from a piece of legacy code, where image processing and GUI functionality isn't strictly divided. One of the methods in the class, BaseImageChanged, seems to be concerned entirely with how images get displayed and should be disabled in my unit tests to avoid unnecessary complexity. The test project is in C#, and the original code is in VB; my idea was to create a Decorator for the class in C# and then hide the method behind an empty one that does nothing. However, when I try running the unit test, the VB code keeps referencing the old BaseImageChanged method as though the replacement didn't exist. Here's what I'm doing:

(VB class)

Public Class ImageEditor
  ...
  Public Sub BaseImageChanged()
  ...
  End Sub
  ...
End Class

(C# class)

class ImageEditorTestingClass : ImageEditor_Accessor
{
   public new void BaseImageChanged() {}
}

Is there a way to accomplish this sort of interoperability, or will I have to find another way?

EDIT: The compiler error turned out to be a problem with reflection. Also, overriding the method didn't work as long as the base class was an accessor of ImageEditor instead of the original ImageEditor class.(No compiler error, but the base method's behavior wasn't overridden.)

3

There are 3 best solutions below

3
On BEST ANSWER

Do you have access to the VB code? if so mark it virtual (C# syntax); Then in the C# code override it with an empty body so that id does nothing.

You should (almost) never use 'new' to redeclare methods or properties. If some code is assuming it's the base class, even if you pass a derived one, the base methods will be called.

For better understanding read about late-binding and early-binding in .NET

Early and late binding

It seems @estanford accepted this answer due to my comment below

"Where you call BaseImageChanged try using reflection"

4
On

I don't know VB at all, but this sounds more like a case for a virtual method with an override than a method hiding. The VB code is probably calling "this.BaseImageChanged()" somewhere, which wouldn't call your new method... right?

0
On

It looks like what's going on here is that

  1. You have a library written in VB.Net
  2. Your unit tests are written in C# and are using MSTest
  3. You're trying to derive from the generated accessor instead of the original class

In this case the only option you have is to use new. The generated accessor class will not add virtual methods and hence if you want to provide an alternate method with the same name new is the only way to do so.