
C# Advanced Features
Pattern matching, records, tuples, deconstruction, local functions, ref/out parameters
1What is a record in C#?
What is a record in C#?
回答
A record is an immutable reference type introduced in C# 9 that provides concise syntax for creating data types with value-based equality. Unlike regular classes which use reference equality, records compare the values of their properties. Use records for DTOs, value objects, and immutable types where value-based equality is desirable.
2What is the difference between out and ref in C#?
What is the difference between out and ref in C#?
回答
The out parameter does not require initialization before method call but must be assigned in the method, while ref requires initialization before call and may or may not be modified in the method. Both pass by reference but out is optimized for returning multiple values while ref is used to modify an existing variable. Use out for methods returning multiple results and ref when modification of an existing value is needed.
3What is pattern matching in C#?
What is pattern matching in C#?
回答
Pattern matching is a feature that allows testing a value against different patterns (types, values, properties) and executing code based on the matching pattern. Introduced in C# 7 and enhanced in later versions, it simplifies complex conditional structures with switch expressions, property patterns and type patterns. Use pattern matching to replace complex if-else chains and improve code readability.
What is a tuple in C# and how to declare it?
What is a local function in C#?
+17 面接問題