Search code examples
c#structqueueref

Peek method return ref object


Alright, so I have a Queue that I use for my print method. It stores the text and the selected font for each line that I need to be printed. The following loop is supposed to print out the contents of the Queue, but it looks like peek returns the value of the object and not the actual reference to the object. Is there any way to make it return a reference?

        while (reportData.Count > 0 && checkLine(yPosition, e.MarginBounds.Bottom, reportData.Peek().selectedFont.Height))
        {
            ReportLine currentLine = reportData.Peek();

            maxCharacters = e.MarginBounds.Width / (int)currentLine.selectedFont.Size;

            if (currentLine.text.Length > maxCharacters)
            {
                e.Graphics.DrawString(currentLine.text.Substring(0, maxCharacters), currentLine.selectedFont, Brushes.Black, xPosition, yPosition);
                yPosition += currentLine.selectedFont.Height;
                currentLine.text.Remove(0, maxCharacters);
            }
            else
            {
                e.Graphics.DrawString(currentLine.text, currentLine.selectedFont, Brushes.Black, xPosition, yPosition);
                yPosition += currentLine.selectedFont.Height;
                reportData.Dequeue();
            }
        }

ReportLine is a structure, so it always passes by value unless otherwise specified. I do not want to change it to a class since its only purpose is to hold 2 pieces of information.

[Edit]

This is what ReportLine looks like. It is very simple:

public struct ReportLine
{
    public string text;
    public Font selectedFont;
}

Solution

  • text is a field of type string and you expect it to be changed by currentLine.text.Remove(0, maxCharacters);. But Remove does not modify the string, it returns a new string.

    Try:

    currentLine.text = currentLine.text.Remove(0, maxCharacters); 
    

    and make ReportLine a reference type:

    public class ReportLine
    {
        public string text;
        public Font selectedFont;
    }