views:

66

answers:

2

I have a function that takes a ref parameter and would like to use it in a linq query but the compiler complains.

The function is called BreakLine and breaks a string up into lines based on a line length, the ref parameter is used to keep track of where it is in the string on each call:

string BreakLine(string text, int lineLimit, ref offset);

The query is:

from pt in productText 
let offset = 0
from ll in lineLimits
select new Line() { Text = BreakLine(pt, ll, ref offset) }

(Line is a simple data class)

The error is:

"Cannot pass the range variable 'offset' as an out or ref parameter"

Any way to workaround this?

+1  A: 

The parameter offset has no type specified. Try to change the BreakLine method signature into this:

string BreakLine(string text, int lineLimit, ref int offset);

...but I guess that is just a typo in your question. The real problem you have is that you get compiler error CS1939. Quote from the documentation:

A range variable is a read-only variable that is introduced in a query expression and serves as an identifier for each successive element in a source sequence. Because it cannot be modified in any way, there is no point in passing it by ref or out. Therefore, both operations are not valid.

Fredrik Mörk
I left out the type of the parameter by mistake, its actually as you have it. Removing the ref keyword just gives another error cause it doesnt match the method signature.
+1  A: 
Func<string, int, Line> lineFunc = (pt, ll) =>
{
    int offset = 0;
    return new Line() { Text = BreakLine(pt, ll, ref offset) };
};
var test = from pt in productText
            from ll in lineLimits
            select lineFunc(pt, ll);
Jerome