Skip to main content

How to Store Any Value in an object Variable in C#

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

Most C# variables hold one type, but some values can be either: a size that's a name such as "medium" or a number of pixels such as 400. A variable of type object takes any value, and keeps track of what it really is.

Syntax​

Syntax
object <name> = <any value>;

if (<name> is <Type> <typedName>)
{
// use <typedName> as a <Type>
}

<Type> <typedName> = (<Type>)<name>;
PartWhat it does
object <name>A variable that can hold a value of any type
<name>.GetType()The type of the value it holds right now
is <Type> <typedName>Checks the type, and gives you the value as that type when it matches
(<Type>)<name>A cast: the value as <Type>, or an exception when it's another type

Microsoft's built-in reference types reference: "The object type is an alias for System.Object in .NET." And: "Assign values of any type (except ref struct, see ref struct) to variables of type object."

The Example​

A size variable holds the text "medium", then the number 400. The program prints each value with its type, then adds 100 to the number once it has it back as an int.

Prerequisites​

  • The .NET 10 SDK or newer, which runs a single .cs file with dotnet run. This guide uses .NET SDK 10.0.404.

Step 1: Write the Code​

Create a file named main.cs in an empty folder:

main.cs, which stores medium in an object variable named size and prints it with its type name, stores 400 in the same variable and prints it with its type name, then checks size is int pixels and prints pixels plus 100.

main.cs
object size = "medium";
Console.WriteLine($"{size} is a {size.GetType().Name}");

size = 400;
Console.WriteLine($"{size} is a {size.GetType().Name}");

if (size is int pixels)
{
Console.WriteLine($"As a number: {pixels + 100}");
}

Step 2: Run It​

Terminal
dotnet run main.cs
Output
medium is a String
400 is a Int32
As a number: 500

A zsh terminal where dotnet run main.cs prints medium is a String, 400 is a Int32 and As a number: 500.

  1. The same variable held a String, then an Int32, the .NET name of int.
  2. size is int pixels matched, so pixels was the number 400, and pixels + 100 was 500.

The command is the same in zsh, bash and PowerShell.

Getting the Value Back​

An object can't go straight into an int variable, even when it holds one:

main.cs
object size = 400;
int pixels = size;
Console.WriteLine(pixels);
Output
/Users/you/demo/main.cs(2,14): error CS0266: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?)

The build failed. Fix the build errors and run again.

The compiler only knows the variable's type, object. A cast says which type you expect:

main.cs
object size = 400;
int pixels = (int)size;
Console.WriteLine(pixels + 100);
Output
500

But a cast is a promise. When the variable holds something else, it fails while the program runs:

main.cs
object size = "medium";
int pixels = (int)size;
Console.WriteLine(pixels);
Output
Unhandled exception. System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32'.
at Program.<Main>$(String[] args) in /Users/you/demo/main.cs:line 2

That's why is, as in Step 1, is the safer way to read an object you aren't sure about.

Boxing​

Putting a number such as 400 into an object is called boxing, and taking it out with a cast is unboxing. Microsoft's Boxing and Unboxing guide: "Boxing is implicit; unboxing is explicit." That's the difference you saw: size = 400; needed nothing, and reading it back needed a cast.

Common Mistakes​

MistakeWhat happensDo this instead
Assigning an object to an interror CS0266: Cannot implicitly convert type 'object' to 'int'Use is int x, or a cast
Casting to the wrong typeInvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32'.Check with is first
Using object where one type would doEvery reader has to check the typeKeep object for values that really can be several types

Troubleshooting​

SymptomLikely causeFix
CS0266 ... from 'object' to ...An object assigned to a typed variableCast it, or use is
InvalidCastExceptionThe value isn't the type you cast toPrint GetType().Name to see what it is

FAQ​

Why does GetType say Int32 and not int?​

int is C#'s name for the .NET type System.Int32, and GetType().Name gives the .NET name. In the same way, string is System.String.

Is object the same as var?​

No. var lets the compiler pick one type from the first value, and the variable keeps it: var size = "medium"; followed by size = 400; stopped with error CS0029: Cannot implicitly convert type 'int' to 'string'. An object variable can hold a value of a different type later, as size did in Step 1.

Conclusion​

An object variable holds a value of any type, and GetType() tells you which. To use the value as its own type again, check it with is <Type> <name>, or cast it with (<Type>) when you're sure, because a wrong cast throws InvalidCastException.

Additional Resources​