Convert null value to string in C#
Attempting to convert a System.DBNull object to System.String will usually result in an error, which usually occurs when retrieving data from the database. The original code attempts to cast the DBNull value directly to a string, causing the exception.
To resolve this issue, the code was modified to check for DBNull before converting to string:
<code class="language-csharp">if (accountNumber is DBNull) { return string.Empty; } else { return accountNumber.ToString(); }</code>
However, there is a more elegant solution using generic functions:
<code class="language-csharp">return ConvertFromDBVal<string>(accountNumber);</code>
The function is defined as follows:
<code class="language-csharp">public static T ConvertFromDBVal<T>(object obj) { if (obj == null || obj == DBNull.Value) { return default(T); // 返回该类型的默认值 } else { return (T)obj; } }</code>
This function elegantly handles the conversion of a DBNull value to the desired type, returning the default value for that type if needed.
The above is the detailed content of How to Safely Cast DBNull Values to Strings in C#?. For more information, please follow other related articles on the PHP Chinese website!