Data Types and Variables in C# Programming


Introduction

C# is a statically typed language, meaning the type of a variable is determined at compile-time. In this tutorial, we'll explore data types and variables in C#, including value types, reference types, and nullable types.

Value Types

Value types directly store data in their memory allocation. Common value types include int, float, double, char, and bool.

Example

    using System;     class Program
    {
        static void Main()
        {
            int number = 42;
            float price = 19.99f;
            double pi = 3.14159;
            char initial = 'C';
            bool isActive = true;             Console.WriteLine("Integer: " + number);
            Console.WriteLine("Float: " + price);
            Console.WriteLine("Double: " + pi);
            Console.WriteLine("Character: " + initial);
            Console.WriteLine("Boolean: " + isActive);
        }
    }
        

Reference Types

Reference types store references to their data (objects), which are stored in the heap. Common reference types include object and string.

Example

    using System;     class Program
    {
        static void Main()
        {
            object obj = 42; // Can store any data type
            string name = "John Doe";             Console.WriteLine("Object: " + obj);
            Console.WriteLine("String: " + name);
        }
    }
        

Nullable Types

Nullable types allow a value type to be null. This is useful for representing the absence of a value.

To declare a nullable type, use the ? symbol after the type.

Example

    using System;     class Program
    {
        static void Main()
        {
            int? nullableInt = null; // Nullable integer
            Console.WriteLine("Nullable integer: " + nullableInt);             nullableInt = 42;
            Console.WriteLine("Nullable integer after assignment: " + nullableInt);             if (nullableInt.HasValue)
            {
                Console.WriteLine("Value: " + nullableInt.Value);
            }
            else
            {
                Console.WriteLine("Value is null.");
            }
        }
    }
        

Conclusion

Understanding data types and variables is fundamental in C#. Value types store data directly, reference types store references to objects, and nullable types enable value types to hold a null value. Experiment with the examples above to strengthen your understanding.




Advertisement