1

Is there a better way to determine the underlying type of an object even when the current value of the object is null?

The following code doesn't work when someObject is indeed of type string but currently holding a null value.

public void doWork(object someObject)
{
    var objAsString = someObject as string;
    if (objAsString != null)
    {
            // do work, return
            // work involves string specific logging/manupulation
    }

    var objAsByteArr = someObject as byte[];
    if (objAsByteArr != null)
    {
            // do work, return 
            // work involves byte specific logging/manupulation
    }

    throw new Exception("Unknown type encountered");
}
  • What is the type of `someObject`? Is it `object`? – John Saunders Oct 27 '13 at 16:32
  • 4
    You have an empty drawer. Somebody hands you an empty box and asks you to put all the hammers from the box into the drawer. You do that, which does not take very long since there are no hammers in the empty box. Afterwards the drawer is still empty. Your question is now: how can I tell that the empty drawer is empty because it contains no hammers? **That's a crazy question**. An empty drawer that contains no hammers is *the same* as an empty drawer that contains no apples. You can't tell them apart. – Eric Lippert Oct 27 '13 at 16:44
  • Wow ... John and Eric on my first SO question! I did something right this morning to summon the C# gods :) –  Oct 27 '13 at 17:20
  • @user100003: one C# god, one acolyte who pays attention. – John Saunders Oct 27 '13 at 19:09

1 Answers1

3

There is no way to do that: null object references have no type associated with them. Arguably, this shouldn't matter: processing of a string that happens to be null should not differ from processing of byte[] that happens to be null.

// Add this check upfront
if (someObject == null) {
    // do work for null, return
}
// Then continue with your existing code:
var objAsString = someObject as string;
if (objAsString != null)
{
    // do work, return
}

var objAsByteArr = someObject as byte[];
if (objAsByteArr != null)
{
    // do work, return 
}

throw new Exception("Unknown type encountered");

If you need to know the type, you should pass the type manually, or use a generic type parameter to determine it statically (i.e. at compile time).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523