Another pointless operator for C#
I remember discovering C#'s null coalescing operator a while ago. I can't say I use it a lot, but it's useful to clean up my code when I do need it. However, there is another similar scenario that it doesn't cover:
SearchResult res = directorySearcher.FindOne();
return res != null ? res.GetDirectoryEntry() : null;
In this case I have my first object, res, and if it IS null, I want to return it - and if it isn't, I want to return a property of that object. In effect, it's the reverse of the ?? operator - return the first object if it is null, or the second object otherwise.
Can anyone think of a way of implementing such an operator without bothering the C# team over it? :)
EDIT: Here's a code sample of my proposed extension. Note the sneaky usage of the inverted question mark for the inverted operator.
SearchResult res = directorySearcher.FindOne();return res ¿¿ res.GetDirectoryEntry();
This, in the beautiful world inside my head, would return res.GetDirectoryEntry() if res is not null, but return null if it is. It relates to the first code sample like the way the two code samples in my original link do.
3 Comments
Comments have been disabled for this content.
Mark Treadwell said
Try replacing the right hand "null" with "res", which is null. Per the C# spec, the conditional operator tries to convert the type of the true/false result expression to the type of the conditional-or-expression. I guess you are getting a type error?
Joe Chung said
Please don't write code like this. Keep it simple. Unnecessary complexity is the root of all evil.
Ryan Ternier said
When you return Res, it will be null, which would be the same as returning null. But, if the object is null, returning a property from a null object would also bring forward more issues. As to the conditional statement on the return - that's the best way of doing it (verses a 3-5 line if statement). It's clean and precise.