C#: How about borrowing some Ruby conditional expressions
After using Ruby for some time I have become quiet attached to its conditional statement syntax. In particular I like statement modifiers which allow you to tag conditional statements at the end of a normal statement.
If C# supported this then in C# terms this'd mean instead of writing
if (!File.Exist(fileName)) throw new FileNotExistException(fileName));
You could have written
throw new FileNotExistException(fileName)) if (!File.Exist(fileName));
If things go as it seems this could actually be the future of C#. I know this does not look that intuitive at first, but once I got used to it I started using it at all places. A quick glance in my Ruby sources reveals code like
Utility.showHelp if ARGV.length < 2
ARGV.each do |srcFileName|
next if srcFileName =~ /^-/ #skip arguments starting with a -
...
end
I liked the unless keyword as well. This is a negated version of if used in Ruby. If C# supported this then we could have written
unless (File.Exist(fileName)) throw new FileNotExistException(fileName));
or better still
throw new FileNotExistException(fileName) unless (File.Exist(fileName));
What I felt was not that intuitive is that in Ruby if is not a statment but is an expression similar to the ?: conditional expression in C/C++/C#. So for conditional assignment of values in Ruby you can write code as in
ageGroup = if age < 2
"Infant"
elsif age < 19
"Teen"
elsif age < 30
"Middle aged"
else
"old"
end
In C# this'd become
string ageGroup; if (age < 2) ageGroup = "Infant"; else if (age < 19) ageGroup = "Teen"; else if (age < 30) ageGroup = "Middle aged"; else ageGroup = "old";