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

Object type as universal base in C Sharp (C#)

Choose your learning style9 modes available
Introduction

The object type in C# is like a big box that can hold any kind of value or data. It helps us treat different things in a common way.

When you want to store different types of data in the same place.
When you need to write a method that can accept any kind of input.
When you want to work with data but don't know its exact type yet.
When you want to pass values around without caring about their specific type.
Syntax
C Sharp (C#)
object variableName = value;

The keyword object is the base type for all types in C#.

You can assign any value to an object variable because everything inherits from object.

Examples
Stores an integer inside an object variable.
C Sharp (C#)
object myNumber = 42;
Stores a string inside an object variable.
C Sharp (C#)
object myText = "Hello!";
Stores a boolean value inside an object variable.
C Sharp (C#)
object myBool = true;
Stores a list of integers inside an object variable.
C Sharp (C#)
object myList = new List<int>() {1, 2, 3};
Sample Program

This program shows how object can hold different types of data. We store an integer, a string, a double, and a list inside object variables. To use the list, we cast it back to its original type.

C Sharp (C#)
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        object data1 = 100;
        object data2 = "C# is fun!";
        object data3 = 3.14;
        object data4 = new List<string> { "apple", "banana" };

        Console.WriteLine(data1);
        Console.WriteLine(data2);
        Console.WriteLine(data3);

        // To use the list, we need to cast it back
        var fruits = (List<string>)data4;
        foreach (var fruit in fruits)
        {
            Console.WriteLine(fruit);
        }
    }
}
OutputSuccess
Important Notes

When you store a value type (like int or double) in an object, it is 'boxed' which means wrapped inside an object.

To get the original value back, you need to 'unbox' it by casting.

Using object is flexible but can be slower and less safe than using specific types.

Summary

object is the base type for all data in C#.

You can store any value or reference type inside an object variable.

To use the original data, you often need to cast back to the original type.