Reduce code that refers to the same object?

Asked

Viewed 75 times

2

Here the code, would you have any way to reduce it? (Just for learning reasons)

worksheet.Row(1).Style.Font.FontColor = ClosedXML.Excel.XLColor.White;
worksheet.Row(1).Style.Font.Bold = true;
worksheet.Row(1).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
worksheet.Row(1).Style.Alignment.SetVertical(XLAlignmentVerticalValues.Center);
worksheet.Row(1).Height = 32;

I thought of something like...

worksheet.Row(1)(.Style.Font.FontColor = ClosedXML.Excel.XLColor.White).Style.Font.Bold = true;

But it doesn’t work :/

  • You’re using this nuget package: https://www.nuget.org/packages/ClosedXML/

1 answer

1


It doesn’t really work and it doesn’t make any sense. The most you could do is:

var objeto = worksheet.Row(1).Style;
objeto.Font.FontColor = ClosedXML.Excel.XLColor.White;
objeto.Font.Bold = true;
objeto.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
objeto.Alignment.SetVertical(XLAlignmentVerticalValues.Center);

I put in the Github for future reference.

Obviously you could have another object without the Stype to catch the Height and could also have one that had together the Font or the Aligment. But there’s no gain.

I’d avoid that until I’m sure you’ve mastered all the consequences. This, the way it is, without considering the context, will work, but a more complex example may not work the way you expect.

This is a normal repetition that does not cause problems, it is not a case for DRY.

  • It was worth the/! But like, say I’m working on something extremely thorough in performance, doing the way you suggested, I would win or lose?

  • 1

    When it comes to GUI it would be irrelevant. If it’s something else more thorough it’s probably C# is the wrong language to do it. Otherwise, I would have to measure. There are no absolute truths.

  • Friend @bigown is 100% correct when he says that the loss of performance is irrelevant. The Pope of Computing already said that we spend 97% of the time wasting time optimizing what is not necessary. In the case the object is not copied, only a reference to it is stored in memory. Probably the C# optimizer will remove the assignment and put everything inline.

  • @Loudenvier very well observed, including by the "probably", since there are no grantias, can even be more optimized by not having to call O Row() and the Style many times. We cannot guarantee. Optimization is not something you count on for sure, depends on implementation, can even change in the future. That’s why I said I have to measure. In each case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.