c# 12 - collection expression and lambda default
Collection expression
C#12 provides a simpler and more consistency way to initialize collections for array, character and lists. Please review the example here:-
// older ways to declare array int
int[] myintegers = new int[] { 1, 2, 3, 4, 5 };
// newer ways to to declare array int
int[] myintegersNew = [1,2,3,4,5];
// older ways to declare List<string>
List<string> myliststrings = new List<string> { "apple", "banana", "watermelon" };
// newer ways to to declare array int
List<string> myliststrings2 = ["apple", "banana", "watermelon"];
Lambda default and optional
With C#12, we can make use of default and optional parameters with lambda expression). For example,
var HelloWorld = (string greet = "hello", string user = "James") => $"{greet} {user}";
Console.WriteLine(HelloWorld());
Inline Array
First you need to use attribute and declare a struct with "[System.Runtime.CompilerServices.InlineArray(10)]". The underlying data type can be struct, class or just value type.
You just have to initialize the type without needed to specifying size.
// declaring array of size 10
[System.Runtime.CompilerServices.InlineArray(10)]
public struct InlineArrayDemo
{
private int _element;
}
// declaring array of size 10
[System.Runtime.CompilerServices.InlineArray(10)]
public struct InlineEmployeeDemo
{
private Employee _element;
}
class Employee
{
public string Name { get; set; }
public string Id { get; set; }
}
Inline array variable cannot be used with Linq and doesn't not have length property like you get in array.
Using simple inline array
// create instance
var x = new InlineArrayDemo();
// update array [10] to 1
x[9] = 1;
// updating array higher than 10 results in compile time error
// x[11] = 1;
Using class inline array
var emp = new InlineEmployeeDemo();
emp[1] = new Employee { Id = "abc", Name = "Jeremy" };
Console.WriteLine(x[9]);
Console.WriteLine(emp[1].Name);
Looping through the inline array
// looping through the inline array using foreach
foreach (var item in emp)
{
Console.WriteLine(item?.Name); // throws null if object not initialize
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine(emp[i]?.Name);
}
Comments