Search code examples
javac#overridingobjectinstantiation

Converting Java to C# - Override on Instantiation


I'm having difficulty converting the below code from Java to C#.

        this.document.add(new VerticalPositionMark() {
            @Override
            public void draw(final PdfContentByte canvas, final float llx, final float lly, final float urx, final float ury, final float y)
            {
                final PdfTemplate createTemplate = canvas.createTemplate(50, 50);
                Main.this.tocPlaceholder.put(title, createTemplate);

                canvas.addTemplate(createTemplate, urx - 50, y);
            }
        });

I'm not really sure if it's possible to override on instantiation in C#. If there isn't, is there a way to replicate the code to achieve what's needed?


Solution

  • C# doesn't have anonymous classes like we know in Java (they can't extend other classes or implement interfaces). I would suggest you use Lambda expressions, but since you're working with a framework that's not an option.

    Consider your starting Java code as the following, which extracts the anonymous inner class to a named class.

    public class ContextClass
    {
        public void ContextMethod()
        {
          this.document.add(new CustomVerticalPositionMark(title, this.tocPlaceholder));
        }
    }
    
    class CustomVerticalPositionMark extends VerticalPositionMark
    {
        final String title;
        final PlaceHolder tocPlaceholder;
    
        CustomVerticalPositionMark(String title, PlaceHolder tocPlaceholder)
        {
            this.title = title;
            this.tocPlaceholder = tocPlaceholder;
        }
    
       @Override
       public void draw(final PdfContentByte canvas, final float llx, final float lly, final float urx, final float ury, final float y)
       {
           final PdfTemplate createTemplate = canvas.createTemplate(50, 50);
           tocPlaceholder.put(title, createTemplate);
    
           canvas.addTemplate(createTemplate, urx - 50, y);
       }
    }