1

These days I am running into many strange scenarios :-)

I have tested the following two codes in ASP.Net application. Code 1 throws exception (as expected) whereas Code 2 does not throw exception (contrary to expectation) when the string value is null.

  1. Why is “EVAL” not throwing exception in this case?
  2. Will EVAL work always like this (i.e., “no exception”) or is it just a luck?
  3. Is there any MSDN reference that says 'Eval' returns empty string?

//Code 1: Causes Exception

 string test = Convert.ToString(subscriber.EncryptedSSN).Substring(0, Convert.ToString(subscriber.EncryptedSSN).Length >= 5 ? 5 : Convert.ToString(subscriber.EncryptedSSN).Length);

// Code 2: Does not throw Exception

 <%# Convert.ToString(Eval("EncryptedSSN")).Substring(0, Convert.ToString(Eval("EncryptedSSN")).Length  >= 5 ? 5 : Convert.ToString(Eval("EncryptedSSN")).Length)  %>

References:

  1. Eval check for DBNull doesnt work
  2. Convert.ToString behaves differently for "NULL object" and "NULL string"
  3. Datatype returned varies based on data in table
Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418

2 Answers2

6

Your scenario appears to be incorrect. The first does not give an exception for me on .NET 4:

object foo = null;

string test = Convert.ToString(foo).Substring(0, Convert.ToString(foo).Length >= 5 ? 5 : Convert.ToString(foo).Length);

This is because Convert.ToString() returns "The string representation of value, or String.Empty if value is null".

String.Empty is not null, it is a string of length 0, so it will not throw an exception when a method is called on it.

A bit of searching led me to this page, explaining databinding in ASP in general, and it explains that "At run time, the Eval method calls the Eval method of the DataBinder object". DataBinder.Eval() returns an object, so Convert.ToString(Eval(Something)) will at least return String.Empty, thus not throwing a NullReferenceException if you try to access its result's members or properties.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • Try with "string foo" instead of "object foo" – LCJ Nov 22 '12 at 13:54
  • @Lijo that is not a "strange scenario" as you call it, it is [documented](http://msdn.microsoft.com/en-us/library/1a2xyyx8.aspx): _"`Convert.ToString(String)` Returns the specified string instance; no actual conversion is performed"_. If you pass it `null`, it will return `null` and hence the exception will occur. Now that you know this, I hope you can see why a NullReferenceException occurs, what you can do to prevent it and why the `Eval()` one doesn't throw an exception (it must be returning a non-null string, or a non-string value or object). – CodeCaster Nov 22 '12 at 13:56
  • Is there any MSDN reference that says `Eval` returns empty string? – LCJ Nov 22 '12 at 15:38
1

What does your Eval evaluate to? Maybe it is String.Empty instead of null and in that case you won't get the exception.

Honza Brestan
  • 10,637
  • 2
  • 32
  • 43