0
0
C Sharp (C#)programming~5 mins

Default values for types in C Sharp (C#)

Choose your learning style9 modes available
Introduction
Default values give a starting value to variables when you don't set one yourself. This helps avoid errors from using empty or unknown data.
When you declare a variable but don't assign a value yet.
When you want to reset a variable to its original state.
When creating arrays or lists and you want all elements to start with a known value.
When writing functions that return a default value if no input is given.
When working with structs or classes and you want to know their initial values.
Syntax
C Sharp (C#)
default(Type)
Replace Type with the data type you want the default value for.
For example, default(int) gives 0, default(bool) gives false.
Examples
Sets number to 0, the default for integers.
C Sharp (C#)
int number = default(int);
Sets isReady to false, the default for booleans.
C Sharp (C#)
bool isReady = default(bool);
Sets text to null, the default for reference types like strings.
C Sharp (C#)
string text = default(string);
Uses shorthand to set price to 0.0, the default for doubles.
C Sharp (C#)
double price = default;
Sample Program
This program shows the default values for int, bool, string, and double types using the default keyword.
C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        int defaultInt = default(int);
        bool defaultBool = default(bool);
        string defaultString = default(string);
        double defaultDouble = default(double);

        Console.WriteLine($"Default int: {defaultInt}");
        Console.WriteLine($"Default bool: {defaultBool}");
        Console.WriteLine($"Default string: {defaultString ?? "null"}");
        Console.WriteLine($"Default double: {defaultDouble}");
    }
}
OutputSuccess
Important Notes
Default values depend on the type: numbers are 0, bool is false, and reference types like string are null.
You can use the shorthand default without specifying the type if the compiler can figure it out.
Using default values helps avoid errors from uninitialized variables.
Summary
Default values give variables a safe starting point.
Use default(Type) or default to get these values.
Different types have different default values, like 0 for numbers and null for references.