0
0
CsharpConceptBeginner · 3 min read

What is default keyword with generics in C#

In C#, the default keyword returns the default value of a generic type parameter. For reference types, it returns null, and for value types, it returns zero or equivalent (like 0 for numbers, false for bool). This helps safely initialize variables when the exact type is unknown.
⚙️

How It Works

Imagine you have a box that can hold any type of item, but you don't know what type it will hold until later. The default keyword in C# helps you get a safe starting value for that box, no matter what type it ends up holding.

When you use generics, the type is unknown at compile time. The default keyword returns the "empty" or "zero" value for that type. For example, if the type is a number, it returns 0; if it's a true/false value, it returns false; if it's an object or string, it returns null.

This way, you can write code that works with any type without worrying about uninitialized variables or errors.

💻

Example

This example shows a generic method that returns the default value of any type passed to it.

csharp
using System;

class Program
{
    static T GetDefaultValue<T>()
    {
        return default(T);
    }

    static void Main()
    {
        int defaultInt = GetDefaultValue<int>();
        string defaultString = GetDefaultValue<string>();
        bool defaultBool = GetDefaultValue<bool>();

        Console.WriteLine($"Default int: {defaultInt}");
        Console.WriteLine($"Default string: {defaultString ?? "null"}");
        Console.WriteLine($"Default bool: {defaultBool}");
    }
}
Output
Default int: 0 Default string: null Default bool: False
🎯

When to Use

Use the default keyword with generics when you need a safe initial value for a variable whose type you don't know yet. This is common in generic classes or methods that work with many types.

For example, when creating data structures like lists or trees, you might want to initialize nodes or elements with default values before assigning real data. It also helps avoid errors from uninitialized variables.

In real life, think of it like setting a placeholder in a form field before the user fills it in.

Key Points

  • default(T) returns the default value for any generic type T.
  • For reference types, the default is null.
  • For value types, the default is zero, false, or equivalent.
  • It helps avoid uninitialized variables in generic code.
  • Useful in generic methods, classes, and data structures.

Key Takeaways

The default keyword returns a safe initial value for any generic type in C#.
For reference types, default is null; for value types, it is zero or false.
Use default to avoid uninitialized variables in generic code.
It is essential for writing flexible and safe generic methods and classes.