C# Programming
Advanced C#
Code Features
Programming Tips
Coding Language Secrets

Hidden Features of C#?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

C# is a modern, versatile programming language developed by Microsoft and used widely for building a wide spectrum of applications including but not limited to desktop applications, mobile apps, cloud-based services, and large-scale enterprise systems. Though many developers are familiar with its primary features, C# holds numerous hidden gems that can significantly improve coding efficiency, readability, or performance. Here, we explore some of these lesser-known features.

1. Caller Information Attributes

C# allows you to obtain information about the caller to a method, which can be quite handy for debugging or logging purposes without manually passing parameters about the call site.

  • CallerFilePathAttribute - path of the source file that contains the caller
  • CallerLineNumberAttribute - line number in the source file at which the method is called
  • CallerMemberNameAttribute - method or property name of the caller

Example

csharp
1public void LogMessage(string message, 
2    [CallerMemberName] string callerName = "",
3    [CallerFilePath] string filePath = "",
4    [CallerLineNumber] int lineNumber = 0)
5{
6    Console.WriteLine($"[{callerName} at line {lineNumber} in {filePath}] {message}");
7}

When you call LogMessage("Hello, World!"); from any method, the output includes the caller information automatically filled by the compiler.

2. Pattern Matching Enhancements

Introduced gradually from C# 7 onwards, pattern matching allows for more expressive and concise code, especially when dealing with type checking or extracting data from types.

Example

csharp
1public void ProcessOrder(object order)
2{
3    if (order is Order { Status: "Processed", Customer: { Name: string name } })
4    {
5    Console.WriteLine($"Order already processed for customer {name}.");
6    }
7}

This feature checks if an order object is of type Order, has a Status property equal to "Processed", and retrieves the customer's name if available.

3. Local Functions

Local functions, introduced in C# 7, enable you to define methods inside the scope of another method to encapsulate utility functions that are relevant only in that particular scope.

Example

csharp
1public int Fibonacci(int n)
2{
3    int Fib(int value) => value switch
4    {
5        1 => 1,
6        2 => 1,
7        _ => Fib(value - 1) + Fib(value - 2)
8    };
9
10    return Fib(n);
11}

This local function Fib is used to compute a Fibonacci number and is only accessible within the Fibonacci method.

4. Index and Range Operators

C# 8 introduced index ^ and range .. operators that simplify array or collection manipulations significantly.

Example

csharp
int[] numbers = { 1, 2, 3, 4, 5, 6 };
int lastElement = numbers[^1]; // ^1 represents the last element
int[] middleSection = numbers[2..^2]; // Range from the third to the second-last element

5. Expression-Bodied Members

Initially limited to methods and read-only properties, expression-bodied members were expanded in later versions to include constructors, finalizers, and more.

Example

csharp
1public class Person
2{
3    public string FirstName { get; }
4    public string LastName { get; }
5    
6    public Person(string first, string last) => (FirstName, LastName) = (first, last);
7
8    public override string ToString() => $"{FirstName} {LastName}";
9}

Summary Table of Hidden Features

FeatureSince VersionDescription
Caller InformationC# 5Attributes to get information about the caller.
Pattern MatchingC# 7Enhanced type checks and deconstruction.
Local FunctionsC# 7Methods within methods for encapsulated logic.
Index and RangeC# 8Simplified syntax for accessing data sequences.
Expression-Bodied MembersC# 6Syntax shortcut for defining members of a class.

Conclusion

These hidden features of C# not only provide syntactic sugar but also introduce more efficient ways to write and maintain code. They collectively contribute towards making C# a powerful, readable, and pleasant programming language for a vast array of applications. Whether you're building complex systems or simple utilities, understanding and leveraging these hidden features can significantly enhance your development capabilities in C#.


Course illustration
Course illustration

All Rights Reserved.