visit
^
^
specifies the index from the end of a sequence. It simplifies the calculation required to get the correct index from the start of the array. Now, you can directly specify the index from the end, which is easier to understand and shorter.e.g., Get the second last item of an arrayvar array = new[] {1,2,3,4,5};
// Before
array[array.Length - 2]; // 4
// Now this is also allowed
array[^2]; // 4
For more details, please take a look at my article on .
..
var array = new[] {1,2,3,4,5};
// Before
var newArray = new List<int>();
for (var i = 1; i < 3; i++)
{
newArray.Add(array[i]);
}
// Now this is also allowed
var newArray = array[1..3]; // 2,3
For more details, please take a look at my article on .
??=
??=
is a helpful little operator that allows you to assign a default value in case of a null.// Before
var possibleNullValue = possibleNullValue ?? "default value";
// Now this is also allowed
var possibleNullValue ??= "default value";
using
statements are handy to make sure to clean up disposable resources at the end of their used scope. However, when you have to chain multiple using
statements, your code needs to be indented, and it can get ugly pretty fast. It's a good practice to make sure that disposable resources don't outlive the scope of the method where they are instantiated. So why not just dispose of them at the end of the method's scope? It's what Microsoft did with the new
using var
. A subtle side effect is that the operator also gets rid of all the unnecessary parentheses and curly braces. Hurray!// Before
using (var stream = new FileStream("", FileMode.Open))
{
using (var sr = new StreamReader(stream))
{
...
}
}
// Now this is also allowed
using var stream = new FileStream("", FileMode.Open);
using var sr = new StreamReader(stream);
...
$@
@$
// Before
$@"This -> {nameof(this)}";
// Now this is also allowed
@$"This -> {nameof(this)}";
All code samples are available on
Previously published at //blog.miguelbernard.com/5-tips-to-improve-your-productivity-in-c-8-0/