What are the hidden features of C#?

C# contains several powerful but often overlooked features that can significantly improve code readability, safety, and efficiency. These hidden gems can make your C# programming more elegant and productive when used appropriately.

Lambda Expressions

A lambda expression is a concise way to write anonymous functions using the => operator (called the "goes to" operator). Lambda expressions are commonly used with LINQ operations and delegate assignments.

Syntax

(parameters) => expression
(parameters) => { statements; }

Example

using System;
using System.Linq;

class Program {
    public static void Main() {
        int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        
        // Lambda expression to find even numbers
        var evenNumbers = numbers.Where(x => x % 2 == 0);
        Console.WriteLine("Even numbers: " + string.Join(", ", evenNumbers));
        
        // Lambda expression with multiple statements
        var squaredEvens = numbers.Where(x => x % 2 == 0).Select(x => {
            Console.WriteLine($"Squaring {x}");
            return x * x;
        });
        Console.WriteLine("Squared evens: " + string.Join(", ", squaredEvens));
    }
}

The output of the above code is −

Even numbers: 2, 4, 6, 8, 10
Squaring 2
Squaring 4
Squaring 6
Squaring 8
Squaring 10
Squared evens: 4, 16, 36, 64, 100

Nullable Types

Nullable types allow value types to represent null in addition to their normal range of values. This is particularly useful when working with databases or APIs that may return null values.

Syntax

dataType? variableName = null;
// OR
Nullable<dataType> variableName = null;

Example

using System;

class Program {
    public static void Main() {
        int? nullableInt = null;
        double? nullableDouble = 3.14;
        
        Console.WriteLine("Nullable int: " + (nullableInt?.ToString() ?? "null"));
        Console.WriteLine("Nullable double: " + nullableDouble);
        
        // Check if nullable has value
        if (nullableInt.HasValue) {
            Console.WriteLine("Value: " + nullableInt.Value);
        } else {
            Console.WriteLine("nullableInt has no value");
        }
        
        // GetValueOrDefault method
        Console.WriteLine("Default value: " + nullableInt.GetValueOrDefault(100));
    }
}

The output of the above code is −

Nullable int: null
Nullable double: 3.14
nullableInt has no value
Default value: 100

Null Coalescing Operator (??)

The null coalescing operator ?? provides a concise way to handle null values by returning the left operand if it's not null, otherwise returning the right operand.

Syntax

result = leftOperand ?? rightOperand;

Example

using System;

class Program {
    public static void Main() {
        string name = null;
        string defaultName = "Guest";
        
        // Using null coalescing operator
        string displayName = name ?? defaultName;
        Console.WriteLine("Display name: " + displayName);
        
        // With nullable types
        int? nullableValue = null;
        int actualValue = nullableValue ?? 42;
        Console.WriteLine("Actual value: " + actualValue);
        
        // Chaining null coalescing operators
        string firstName = null;
        string lastName = null;
        string username = "user123";
        string result = firstName ?? lastName ?? username ?? "Anonymous";
        Console.WriteLine("Result: " + result);
    }
}

The output of the above code is −

Display name: Guest
Actual value: 42
Result: user123

The 'as' Keyword

The as keyword performs safe type conversions between compatible reference types and nullable types. Unlike casting with parentheses, as returns null if the conversion fails instead of throwing an exception.

Syntax

TargetType variable = sourceObject as TargetType;

Example

using System;

class Animal {
    public virtual void MakeSound() {
        Console.WriteLine("Some generic animal sound");
    }
}

class Dog : Animal {
    public override void MakeSound() {
        Console.WriteLine("Woof!");
    }
    public void Fetch() {
        Console.WriteLine("Fetching the ball!");
    }
}

class Program {
    public static void Main() {
        Animal animal1 = new Dog();
        Animal animal2 = new Animal();
        
        // Safe conversion using 'as'
        Dog dog1 = animal1 as Dog;
        if (dog1 != null) {
            dog1.Fetch();
        }
        
        Dog dog2 = animal2 as Dog;
        if (dog2 != null) {
            dog2.Fetch();
        } else {
            Console.WriteLine("animal2 is not a Dog");
        }
        
        // This would throw exception: Dog dog3 = (Dog)animal2;
        Console.WriteLine("Safe conversion completed");
    }
}

The output of the above code is −

Fetching the ball!
animal2 is not a Dog
Safe conversion completed

Comparison of Type Checking Features

Feature Purpose Behavior on Failure
as keyword Safe type conversion Returns null
(Type) casting Direct type conversion Throws InvalidCastException
is keyword Type checking Returns false

Conclusion

These hidden features of C# − lambda expressions, nullable types, null coalescing operator, and the as keyword − provide powerful tools for writing cleaner, safer, and more expressive code. Mastering these features will significantly enhance your C# programming capabilities and code quality.

Updated on: 2026-03-17T07:04:35+05:30

456 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements