public
Authored by
Manu 


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.
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!
}
}
}
Please register or sign in to comment