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

Bug #245330 reported by Krisztian Gyuris

This bug report was converted into a question: question #38144: ?? behaviour is different in Visual Studio (TEST BUG).

2
Affects Status Importance Assigned to Milestone
WIN Do
Invalid
Undecided
Unassigned

Bug Description

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

Revision history for this message
Krisztian Gyuris (gyurisc) wrote :

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) wrote :

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

Changed in windo:
status: New → Invalid
Revision history for this message
brian.pedersen (brian-pedersen) wrote :

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

To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.