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.
Object type as universal base in 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.
object variable.object myNumber = 42;object variable.object myText = "Hello!";object variable.object myBool = true;object variable.object myList = new List<int>() {1, 2, 3};
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.
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); } } }
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.
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.