Variables in C#

In C#, variables are explicitly declared and used by the compiler to check type-correctness of method calls.

using System;

class Program
{
    static void Main()
    {
        // var declares and initializes a variable
        var a = "initial";
        Console.WriteLine(a);

        // You can declare multiple variables at once
        int b = 1, c = 2;
        Console.WriteLine($"{b} {c}");

        // C# will infer the type of initialized variables
        var d = true;
        Console.WriteLine(d);

        // Variables declared without initialization are given
        // default values. For example, the default for int is 0.
        int e;
        Console.WriteLine(e);

        // In C#, we don't have a direct equivalent to Go's := syntax.
        // However, we can use var for similar concise declarations.
        var f = "apple";
        Console.WriteLine(f);
    }
}

To run the program, save it as Variables.cs and use the dotnet command:

$ dotnet run Variables.cs
initial
1 2
True
0
apple

In C#, variables are strongly typed, but the var keyword allows for type inference, similar to Go’s := syntax. However, var in C# must be used with an initializer, and once the type is inferred, it cannot be changed.

C# also has the concept of default values for variables. When a variable is declared but not initialized, it’s given a default value based on its type. For value types like int, the default is 0, while for reference types, it’s null.

Unlike Go, C# doesn’t have a built-in fmt package. Instead, it uses Console.WriteLine() for standard output. For more complex string formatting, C# offers string interpolation (as shown in the b and c example) and composite formatting.

C# is typically used within the .NET framework, which provides a rich set of libraries and tools for building various types of applications.