Or, ‘am I doing it wrong’?
I am writing a small function that will return a string, quoted (as quoted-printable) if necessary, otherwise it returns it as is. A character is input into the function; the result is a string.
What I tried to do at first was:
private string QuotedChar(char ch) { if(ch < (char)128 && !char.IsWhiteSpace(ch)) return(new string(ch)); // ... }
However, the compiler says CS0214, ‘Pointers and fixed size buffers may only be used in an unsafe context’, when compiling that return statement. If I change the code to say instead:
private string QuotedChar(char ch) { if(ch < (char)128 && !char.IsWhiteSpace(ch)) return(new string(new char[] { ch })); // ... }
… it works just fine. However that seems rather pointless. I don’t understand why it thinks I am trying to use a pointer or a fixed size buffer, since it’s just a char. Am I missing something seriously silly, or is this a problem/bug?
FYI, this is Mono 2.0, not the Microsoft .NET Framework. I don’t run Windows, so I don’t have Microsoft’s C# compiler to see if it does the same thing or not, which is why I wonder if it is a bug.
Well, it’s not a bug that it doesn’t compile. There’s no string constructor overload which takes a char. I suspect that Mono thought you meant the
string(char*)constructor and tried that – leading to the error.The simplest way of converting a
charto astringis simply to callToString()though:The MS C# compiler guesses the same overload, but gives a different error message: