5 C# features that most probably you didn’t know about
Lately, I’ve looked over the new “things” that appeared in the latest version of C# and will appear in the next one. By clicking from one link to another, I realized that a lot of features were introduced even in C# 8, but we don’t use them/know about them and they might help some of us. Based on this presumption, I want to present to you a few examples of features that we don’t use on day to day basis
Ranges and Indexes
The range operator needs the start and the end index from a range of elements.
The “Hat” Operator
It is used as a prefix to count indexes starting from the end of a list. The index is stored as System.Index type.
If you want you can use both operators, but in my opinion, it would look strange.
Default implementations for interfaces
The interface can be extended without breaking any classes that are using it.
Nested namespaces
I don’t know why would you ever do that, but you can. Maybe only in that case in which you want to have different classes with the same name inside the same “main” namespace, but it’s still a strange corner case for me.
Exception filters
Those were added long before C# 8 but they are still nice (and not used on daily basis). The basic idea is that by using those you can add conditions to your catch block. The “magic” is that you may use the same exceptions in multiple catch blocks.
Struct — random knowledge
This is not a new feature, it’s more like random information, that you should know about.
- You cannot give initial values to a struct unless you make it static or const. You’ll get a compile error otherwise.
- A struct cannot inherit another struct or class and can’t be a “base”. From here appeared all those interview questions like: “What are the access modifiers of a struct?”. Based on my first statement, of course, struct can’t be declared as protected, private protected pr protected internals. As a side note, since we are talking about keywords, struct cannot be marked as virtual.
- Even if they can’t support inheritance, they can implement interfaces (contracts) as classes.
- A struct needs less memory than a class, so if you’re working on something in which you really care about memory…you should always use structs over classes (of course, where it makes sense).