public
Authored by avatar Manu :medal:

C# SQL Safe Get Value

Normally When getting a null value from the SqlDataReader throws an exception. This helper method implements a safe way to get values even if they are null.

Edited
SqlDataReaderExtensions.cs 769 bytes
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Utilities
{
    public static class SqlDataReaderExtensions
    {
        /// <summary>
        /// Checks if the value of the field is null. When it is null, the default value will be returned, when it is not null, the value of the field will be returned
        /// </summary>
        public static T SafeGetValue<T>(this SqlDataReader reader, string colName)
        {
            int colIndex = reader.GetOrdinal(colName);
            if (reader.IsDBNull(colIndex)) return default(T);
            else return (T)reader.GetValue(colIndex); // Bei Fehlermeldungen Datentyp Überprüfen!
        }
    }
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment