Andrés Esteban Rodríguez Jiménez
"Evolution of C#
C# 6
Auto Property Initializer
- Allows initializing a default value to a property within a class.
public string MyVar { get; set; } = "Hello world";
String Interpolation
- Provides a cleaner and more intuitive way to concatenate strings.
string MyString = "Hello world"; Console.WriteLine($"The message is: {MyString}");
Expression-bodied Function
- Enables faster function creation using the arrow operator (
=>), akin to JavaScript arrow functions.
public int Sum(int x, int y) => (x + y);
Null Conditional Operator
- Allows checking if a property is null before evaluation, avoiding the need for an if conditional.
DateTime? datetime = new DateTime();
// Using "?" to check if the value is null var YearOfDate = datetime?.Year;
Console.WriteLine(YearOfDate);
var YearOfDateConditional = datetime?.Year ?? 0;
C# 7
Local Functions
- Enables creating functions within functions, allowing functions within methods.
static void Main(string[] args) { int Sum(int x, int y) { return x + y; }
Console.WriteLine(Sum(10, 20)); Console.ReadKey(); }
Digit Separator
- Enables using the "_" character to separate numbers into groups of 3 for readability.
public const long BillionsAndBillions = 100_000_000_000;
Tuples
- Allows returning combinations of different values and types when returning both primitive types and composed values.
var named (first: "one", second: "two");
// Method returning a tuple (bool bresult, double dcalculation) = Tuples.CalculationTuple();
C# 8
Switch Expression
- Reduces the syntax of switch statements when only returning a value.
// Switch as expression int intValueForSwitch = 0;
var state = (intValueForSwitch) switch { (0) => "Zero", (1) => "One", (2) => "Two", (3) => "Three", _ => "NO valid number" }
C# 9
Top-Level Statements
- Allows running code directly in a code sheet without the need for a classic namespace.
Before:
using System;
namespace HelloWorld { internal class Program { static void Main(string[] args) { Console.WriteLine("Hello world"); } } }
After:
using System;
Console.WriteLine("Hello world");
C# 10
Global Using
- Enables using methods without explicitly importing libraries since the code automatically detects which libraries are used.
Before:
using System;
Console.WriteLine("Hello world");
After:
Console.WriteLine("Hello world");
These improvements represent significant advancements in C# over time, enhancing developer productivity and code readability."