Tangible Software Solutions

The Most Trusted Name in Source Code Conversion

C# Equivalent to Java Anonymous Inner Classes

The closest equivalent to Java anonymous inner classes in C# is to use a private class which implements the corresponding interface (but if the interface is a functional interface, then the closest equivalent is to replace the functional interface with a delegate and the anonymous inner class with a lambda).

Original Java:

public class ConversionOfAnonymousInnerClasses
{
   private void Test()
   {
      BaseInterface localVar = new BaseInterface()
      {
         public void method1()
         {
            someCode();
         }
         public void method2(int i, boolean b)
         {
            someCode();
         }
      };
   }
}

Equivalent C#:

public class ConversionOfAnonymousInnerClasses
{
   private void Test()
   {
      BaseInterface localVar = new BaseInterfaceAnonymousInnerClassHelper(this);
   }

   private class BaseInterfaceAnonymousInnerClassHelper : BaseInterface
   {
      private readonly ConversionOfAnonymousInnerClasses outerInstance;

      public BaseInterfaceAnonymousInnerClassHelper(ConversionOfAnonymousInnerClasses outerInstance)
      {
         this.outerInstance = outerInstance;
      }

      public virtual void method1()
      {
         someCode();
      }
      public virtual void method2(int i, bool b)
      {
         someCode();
      }
   }
}

If you need to convert from Java to C# and you are depending on the results being reliable and accurate, then you will want to have Java to C# Converter, the best Java to C# converter, at your fingertips.

Copyright © 1997 - 2017 Tangible Software Solutions Inc.