Using C# indices and range syntax to access elements in a sequence

Microsofts Indices and Ranges page provides examples of the indices and range syntax available in C# (introduced in C#8). This syntax provides a succinct way to access single elements or ranges in a sequence. The first example below shows the ‘index from the end’ operator ^, which gives us a shorthand way of getting items relative … Continue reading Using C# indices and range syntax to access elements in a sequence

Using ToLower() or ToUpper() in C# to compare strings is not safe in all cultures

If you’re using Resharper, Roslynator or similar you’ll likely see string comparisons using ToLower() or ToUpper() flagged. Why are these C# string compare methods flagged? Well these string comparisons are not safe in all cultures. The canonical example is the ‘Turkish i problem‘ which relates to how in Turkish the dot is present on the … Continue reading Using ToLower() or ToUpper() in C# to compare strings is not safe in all cultures

Don’t use the C# var keyword everywhere in your code just to be consistent

Don’t use the var keyword everywhere in your code base just to be consistent. If using var removes clarity for certain assignments its best not to use it in these cases. Example 1 below shows some usages of var in which the type is very clear from the right hand side. In these cases var … Continue reading Don’t use the C# var keyword everywhere in your code just to be consistent

Easier immutability with Init only properties in C# 9

C# 9 shipped with .NET 5 in November. One change included is init only properties which allow us to have immutable (non-changeable) classes without some of the downsides associated with pre C# 9 approaches. As can be seen below in C# 8 we’d typically have getters with no setters which gives us immutability…great.. but it … Continue reading Easier immutability with Init only properties in C# 9

Converting numbers to strings without scientific notation in C#

C# will automatically convert numbers which are of type float, double or decimal and have a lot of precision (lots of numbers after the decimal point) to scientific notation. The means if you have a double which for example contains the value .00009 and attempt to convert it to a string C# will display it as 9E-05. Of course … Continue reading Converting numbers to strings without scientific notation in C#

Discouraging use of the var keyword and ternary if operator

I would always favour typing more code to make it more explicit, more readable and to ensure consistency in style throughout a software system. Minimising the bytes and lines needed to do something shouldn’t take preference over readability. My two pet hates in this regard are the var keyword and ternary (?) if operator. I know var … Continue reading Discouraging use of the var keyword and ternary if operator