7

The only time I tried to use object was List<object> and I regretted it and rewrote it. I can never find an instance to use object rather than an interface. When does one use object in .NET?

9 Answers9

12

Frankly, it doesn't happen often that you REALLY need it. But when you do, it's pretty obvious. Reflection, generic type casting, serialization or tagging are among topic that ends up having object around.

It's like void*... which in essence is almost the same. You wonder what's the use for such "crude" item until you ends up in a corner with no way out, but to use it.

It's the lowest level you can find in managed code. Everything is an object, you cannot go deeper.

Generic Type casting:

public T AddComponents<T>()
{
    Component component = (Component)Activator.CreateInstance(typeof(T));

    if (component != null)
    {
        component.Parent = this;
        components.Add(component);
    }

    return (T)(object)component; //Cannot directly cast Component to T since we have no constraint between them.
}

"Tags" of the idea of assigning an item to a generic container who has no idea of the content:

public class DragDropWrapper
{
    private object tag;

    public object Tag
    {
        get { return tag; }
    }
}

What is dragged? No idea. Can be anything.

Or the very common Event Sender:

public void Message(object sender, string text)
{
    Entry entry = new Entry(sender, EntryType.Message, text);
    AddEntry(entry);
}

The sender can be anything.

Reflection to expand the property of an object:

public static List<InfoNode> ExpandObject(InfoGrid grid, InfoNode owner, object obj)
{
    List<InfoNode> nodes = new List<InfoNode>();

    if (obj == null)
        return nodes;

    PropertyInfo[] infos = obj.GetType().GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public);

    foreach (PropertyInfo info in infos)
        nodes.Add(new PropertyNode(grid, owner, obj, info));

    nodes = nodes.OrderBy(n => n.Name).ToList();

    return nodes;
}

And many many more possibilities.

LightStriker
  • 19,738
  • 3
  • 23
  • 27
2

Well, one very good example. Lets say you wanted to write a library, and this library needed to be able to take some arbitrary piece of data and store it. For example like in an ORM then you might write a function like so..

bool InsertObject(object item);

The same could be said for an object seralizer. think JSON.

Basically, you would 'use' object when you need to work in a very generic manner.

iamkrillin
  • 6,798
  • 1
  • 24
  • 51
1

You use object when you need to store a reference to any object type. If that's something you don't need to do, then feel free to not use it.

Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
1

One rarely uses object directly because it has so little functionality. It was used more frequently in V 1.0 (before generics), but now is rarely used for much more than the occasional doble cast like this:

(A)(object)someType;

to work around limitations of the cast operation.

The real purpose of object is to enforce the implementation of basic operations such as GetType() and ToString(), and provide a default implementation of those.

Pieter Geerkens
  • 11,775
  • 2
  • 32
  • 52
  • It sounds like you're saying compilers should use it but not me? –  Apr 14 '13 at 02:55
  • 1
    There is very little reason to use it in modern editions of the DOT NET framework. When (if?) you encounter a situation where you need to use `object` directly, I think it's need is likely to hit you over the head. – Pieter Geerkens Apr 14 '13 at 02:57
1

For example, i'd use it as a variable for lock in the class

evgenyl
  • 7,837
  • 2
  • 27
  • 32
1

Normally, you will primarily use the object type explicitly only when interacting with APIs that were written prior to generics being added to the C# language.

One use case that I do find fairly common is the following idiom:

 class NeedsToBeThreadSafe {

     private static object _lock = new object();

     void ThreadSafeOperation() {
          lock (_lock)
          {
              // Perform some useful work
          }
     }
 }

Here, we need the _lock object only to implement the locking; it doesn't need any members or value—so the object type is appropriate.

SAJ14SAJ
  • 1,698
  • 1
  • 13
  • 32
  • ah. Do you have any idea how it differs from `Mutex`? –  Apr 14 '13 at 02:54
  • 1
    See: http://stackoverflow.com/questions/301160/what-are-the-differences-between-various-threading-synchronization-options-in-c It is a lighter weight operation, and reads more cleanly in the code, but does not permit inter-process communication. – SAJ14SAJ Apr 14 '13 at 02:55
1

Object is the parent type for all the types.Every single type that you create or use from the .Net framework inherits from it.Prior to generics being introduced in .Net,most of the collection types (for e.g ArrayList under System.Collecrtions) are defined to accept Object types.What it means is you could add have a Mixed bag of different types.And you need to cast the items to a specific type while retrieving.This is an unneeded overhead.

To answer your question. You should avoid using object anywhere as it does not do any good to your code.The whole point of introducing generics was to get rid of object notation ,so you can avoid unneeded casts in your code.

Prabhu Murthy
  • 9,031
  • 5
  • 29
  • 36
1

As object can be used to reference any value, you use it when you need to do exactly that.

The String.Format method for example uses object parameters to be able to put any value in a string:

public string Format(string format, params object[] parameters)

That enables you to send any values into it, for example:

String.Format("{0} {1}", 1, "2");

Using it as a generic type, like in List<object>, is not so common as you usually have some more specific type that you can use. However, a List<object> would be the generic equivalent of the ArrayList class, which was frequently used before generics was introduced in .NET.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

Object can be used when the API you are creating do not care about the underlying type, or can accept everything. For example I want to create a library that serializes everything. In that case the library methods receives an instance of object, and can handle the rest through reflection.

Or imagine you want to create a refactor friendly method that recieves a member-access lambda expression, as in:

f(something, s => s.member);

And you don't care about what the member type could be, it could be anything. You can define the method like:

void f(SomeType something, Expression<Func<SomeType, object>>) ...

Other common use is to use it as a thread lock variable, which other people have mentioned.

Sina Iravanian
  • 16,011
  • 4
  • 34
  • 45