.Net:How to Get the Type of a Null Object

.NET : How do you get the Type of a null object?

So is there any way to get the type of an object that is set to null? I would think there would have to be a way to know what type a storage location is without it being assigned anything.

Not necessarily. The best that you can say is that it is an object. A null reference does not point to any storage location, so there is no metadata from which it can make that determination.

The best that you could do is change it to be more generic, as in:

public void GetParameterValue<T>(out T destination)
{
object paramVal = "Blah";
destination = default(T);
destination = Convert.ChangeType(paramVal, typeof(T));
}

The type of T can be inferred, so you shouldn't need to give a type parameter to the method explicitly.

Getting the underlying type of a null object

Imagine you have a library of books. Imagine you also have a box of cards, one card for each book. (Younger readers: libraries actually used to have such systems, before computers made them obsolete.)

Now imagine you have two trays. One tray is marked "Science Fiction" and the other tray is marked "Any book".

The SF tray is empty.

You tell your assistant librarian "Dump whatever is in the Any tray, then make a photocopy of whatever is in the SF tray and put the copy in the Any tray."

After dumping the Any tray it becomes empty, and since the SF tray is empty there is nothing to photocopy, therefore the Any tray stays empty.

The analogue of your question is now "what is the genre of the book whose card is in the Any tray?" and the answer is "there is no such genre because the Any tray is empty". It's not like the fact that the SF tray was empty somehow "infects" the Any tray to make it "empty but SF flavoured".

Does that make sense? Variables are just storage locations; null references are references that mean "this doesn't reference anything at all", and there is no flavour to "nothing at all".

For more on this distinction see my article on the subject:

http://blogs.msdn.com/b/ericlippert/archive/2009/10/29/i-have-a-fit-but-a-lack-of-focus.aspx

How to get the lowercase name of an object, even when null, in C#

Jeff is correct. That's like asking what kind of cake would have been in an empty box with no label.

As an alternative to Fortran's answer you could also do:

string TypeNameLower<T>(T obj) {
return typeof(T).Name.ToLower(CultureInfo.InvariantCulture);
}

string TypeNameLower(object obj) {
if (obj != null) { return obj.GetType().Name.ToLower(CultureInfo.InvariantCulture); }
else { return null; }
}

string s = null;
TypeNameLower(s); // goes to the generic version

That way, C# will pick the generic one at compile time if it knows enough about the type you're passing in.

.NET : How do you get the Type of a null object?

So is there any way to get the type of an object that is set to null? I would think there would have to be a way to know what type a storage location is without it being assigned anything.

Not necessarily. The best that you can say is that it is an object. A null reference does not point to any storage location, so there is no metadata from which it can make that determination.

The best that you could do is change it to be more generic, as in:

public void GetParameterValue<T>(out T destination)
{
object paramVal = "Blah";
destination = default(T);
destination = Convert.ChangeType(paramVal, typeof(T));
}

The type of T can be inferred, so you shouldn't need to give a type parameter to the method explicitly.

Get type of null reference object for Object reference not set to an instance of an object

Um... Because it's null.

In C#, a reference type is a pointer to something. A null pointer isn't pointing to anything. You are asking, "What type of thing would this point to if it was pointing to something". That's sort of like getting a blank sheet of paper, and asking, "What would this say if it had something written on it?"

UPDATE: If the framework can't know the type of a null pointer, can't it know what type it's supposed to be? Well, it might. Then again, it might not. Consider:

 MyClass myobj = null;
int hash = myobj.GetHashCode();

Unless you overrode it in MyClass, GetHashCode is defined in System.Object. Should you get a complaint that myobj needs to be a System.Object? Now, when we check ourselves, we're completely free to specify the required type.

  SomeFunc(MyClass myparam)
{
if (myparam == null)
throw new ArgumentNullException("myparam must be a MyClass object");
}

But now we are talking about application code, not CLR code. Which makes you "real" question "Why don't people write more informative exception messages?", which is, as we say here at SO "subjective and argumentative"

So, you basically want the system level exception to know the type information which is only known at the applications level, which we'd need so way to communicate. Something like:

  SomeFunc(MyClass myparam)
{
if (myparam == null)
throw new ArgumentNullException("myparam", typeof(MyClass));
}

But that's not really buying us much, and if you really want it, you could write it yourself:

  public class MyArgumentNullException : ArgumentNullException
{
public MyArgumentNullException(string name, Type type)
:base(name + "must be a " + type.Name + " object");
}

Checking if an object is null in C#

It's not data that is null, but dataList.

You need to create one with

public List<Object> dataList = new List<Object>();

Even better: since it's a field, make it private. And if there's nothing preventing you, make it also readonly. Just good practice.

Aside

The correct way to check for nullity is if(data != null). This kind of check is ubiquitous for reference types; even Nullable<T> overrides the equality operator to be a more convenient way of expressing nullable.HasValue when checking for nullity.

If you do if(!data.Equals(null)) then you will get a NullReferenceException if data == null. Which is kind of comical since avoiding this exception was the goal in the first place.

You are also doing this:

catch (Exception e)
{
throw new Exception(e.ToString());
}

This is definitely not good. I can imagine that you put it there just so you can break into the debugger while still inside the method, in which case ignore this paragraph. Otherwise, don't catch exceptions for nothing. And if you do, rethrow them using just throw;.

How to check object is null or empty in C#.NET 3.5?

The problem that you are running into is that your object is of type, well, object. In order to evaluate it with string.IsNullOrEmpty, you should pass your object in with the cast to (string)

like so:

static void Main(string[] args)
{
object obj = null;

double d = Convert.ToDouble(string.IsNullOrEmpty((string)obj) ? 0.0 : obj);
Console.WriteLine(d.ToString());
}

This will work fine since you are not explicitly calling .ToString on your (nonexistent) object.



Related Topics



Leave a reply



Submit