?? behaviour is different in Visual Studio (TEST BUG)

Asked by Krisztian Gyuris

The code is sprinkled with statements like this:

return listOfInts ?? listOfInts = new List<int>;

However this is not accepted by the the C# compiler in Visual Studio. I

Question information

Language:
English Edit question
Status:
Solved
For:
WIN Do Edit question
Assignee:
No assignee Edit question
Solved by:
brian.pedersen
Solved:
Last query:
Last reply:
Revision history for this message
Krisztian Gyuris (gyurisc) said :
#1

The following code can replace the statement and it works, although it is much longer:

if(listOfInts == null)
{
   listOfInts = new List<int>;
}

return listOFInts;

This works, but is there any way to do this with the use of ?? operator?

Revision history for this message
Krisztian Gyuris (gyurisc) said :
#2

This is a coding howto question, please answer if you can.

Revision history for this message
Best brian.pedersen (brian-pedersen) said :
#3

The ?? operator is a feature from C# 2.0 called the "null coalescing operator", you can read more about it here: http://msdn.microsoft.com/en-us/library/ms173224.aspx

As far as I can see .NET does not like the assignment inside the statement, so "return listOfInts ?? new List<int>;" would work in terms of returning a new List but would of course fail to initialize the listOfInts variable.

What you can do if you want to avoid the long replacement block, is to put brackets around the assignment: "return listOfInts ?? (listOfInts=new List<int>);", I believe this should work.

/Brian

Revision history for this message
Krisztian Gyuris (gyurisc) said :
#4

Thanks brian.pedersen, that solved my question.