C# Version Reference
Function returning multiple values via tuple
static (string Alpha, string Beta) GetLetters () {
return ("A", "B");
}
static void Main(string[] args) {
Console.WriteLine(GetLetters());
}
Result
(A, B)
Tracing function and parameter names
static void MyFunction(string myVariable) {
Console.WriteLine($" function: {nameof(MyFunction)}, variable: {nameof(myVariable)} = {myVariable} ");
}
static void Main(string[] args) {
MyFunction("Fred");
}
Result
function: MyFunction, variable: myVariable = Fred
Null-conditional operators
class Person {
public string FirstName { get; set;}
}
static void HandleNull(Person p)
{
var firstName = p?.FirstName; // return null if p or p.FirstName is null
Console.WriteLine(firstName);
}
static void Main(string[] args) {
HandleNull(new Person { FirstName = "Fred" });
HandleNull(null);
}
Result
Fred
Property Initializer
public static int BirthYear { get; set; } = 1974;
public static int BirthYear2 { get; } = 1974;
Out Variables
if (int.TryParse(input, out int result))
WriteLine(result);
else
WriteLine("Could not parse input");
Local Functions
public static int Add(string op, int i1, int i2)
{
switch(op)
{
case "add": return add(i1, i2);
case "sub": return sub(i1, i2);
default: throw new InvalidOperationException();
}
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
}
Numeric literal syntax improvements
static void Main(string[] args) {
const int four = 0b0100; // Binary notation support
const long hundredThousand = 100_000; // The digit separator can appear anywhere in the constant.
Console.WriteLine($"four:{four}");
Console.WriteLine($"hundredThousand:{hundredThousand}");
}
Result
4
100000
No comments:
Post a Comment