Adam Wróbel
Adam Wróbel

Reputation: 453

Creating a new object and calling the method at the same time

I have simple code (iTextShar library) who generate PdfCell with Phrase:

//I create new Phrase
Phrase p = new("Lorem ipsum", myFont);

//I set leading for Phrase
p.setFixedLeading(10f);

//I create new Table Cell end insert Phrase
PdfPCell cell = new(p);

Why can't I generate Phrase directly on PdfPCell and simultaneously run method .setFixedLeading. Somethink like this?

PdfPCell cell = new(Phrase p("Lorem ipsum", myFont).setFixedLeading(10f));

Is there any way to set Leading using the .setFixedLeading method when creating a new Phrase object?

Upvotes: 0

Views: 827

Answers (1)

SomeBody
SomeBody

Reputation: 8743

You could write your own method:

private Phrase CreatePhraseWithFixedLeading(string text, Font font, float fixedLeading)
{
   Phrase p = new(text, font);
   p.setFixedLeading(fixedLeading);
   return p;
}

Usage is

Phrase p = CreatePhraseWithFixedLeading("lorem ipsum", myFont, 10f);
PdfPCell cell = new(p);

or, if you don't need the phrase after creating the cell

PdfPCell cell = new(CreatePhraseWithFixedLeading("lorem ipsum", myFont, 10f));

If you have more methods to call after you created your phrase, you could take a look at the builder pattern.

But on the other hand, you should ask what you gain by this. The code you presented was perfectly fine. Don't try to put as much into one line as possible.

Upvotes: 1

Related Questions