Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should `Object` be used in C# 2.0 and newer? Do Generics replace all occurrences of Object?

My coworker made the claim that there is never a need to use Object when declaring variables, return parameters, etc in .NET 2.0 and newer.

He went further and said in all such cases, a Generic should be used as the alternative.

Is there any validity to this claim? Off the top of my head I use Object for locking concurrent threads...

like image 711
makerofthings7 Avatar asked May 25 '12 12:05

makerofthings7


1 Answers

Generics do trump object in a lot of cases, but only where the type is known.

There are still times when you don't know the type - object, or some other relevant base type is the answer in those instances.

For example:

object o = Activator.CreateInstance("Some type in an unreferenced assembly");

You won't be able to cast that result or maybe even know what the type is at compile time, so object is a valid use.

Your co-worker is generalising too much - perhaps point him at this question. Generics are great, give him that much, but they do not "replace" object.

like image 194
Adam Houldsworth Avatar answered Sep 21 '22 17:09

Adam Houldsworth