Home > Backend Development > C++ > How to Safely Cast DBNull Values to Strings in C#?

How to Safely Cast DBNull Values to Strings in C#?

Susan Sarandon
Release: 2025-01-25 10:07:10
Original
1004 people have browsed it

How to Safely Cast DBNull Values to Strings in C#?

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>
Copy after login

However, there is a more elegant solution using generic functions:

<code class="language-csharp">return ConvertFromDBVal<string>(accountNumber);</code>
Copy after login

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>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template