A C# Operator I would like to see.
You could argue there are too many operators in C# as it is; however, I feel having an acute knowledge of the available operators is like knowing CTRL + B will bold the selected text in most word processing software.
To put it simply, it hurts no-one, whilst providing shortcuts to advanced users.
Consider the following:
if (MyObject != null)
{
return MyObject;
}
else
{
return SomeOtherObject;
}
In C# 2.0, the kind people at Microsoft provided the ?? operator to make this a much more sucinct:
return MyObject ?? SomeOtherObject;
One thing that I find ugly and boring in code is that of checking for nulls in nested object properties, so for a moderately extreme example:
Staff.Manager.PersonalDetails.Address.Location.Postcode
In order for me to be sure that I can access the “Postcode” part of this chain correctly (with the caviet that each of these proerty objects might be null) I’d have to write something like the following:
if (Staff != null && Staff.Manager != null &&
Staff.Manager.PersonalDetails != null &&
Staff.Manager.PersonalDetails.Address != null && .....
{
I’m sure you’ll agree the above is pretty ugly, especially if you don’t really care which property is null, just if any of them are.
So, I propose a new operator, the “Is anything in this chain null” operator, to be used something like so:
return ??{Staff.Manager.PersonalDetails.Address.Location.Postcode} : “No Postcode”
The actual syntax of this operator isn’t important, just the functionality.
0 Responses to A C# Operator I would like to see.
Something to say?