ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

ToNullableString()

Calling Value.ToString on a System.Nullable<T> type where the value is null will result in an "Nullable object must have a value." exception being thrown. This extension method can be used in place of .ToString to prevent this exception from occurring.

Source

public static string ToNullableString<T>(this System.Nullable<T> param) where T : struct 
{
	if (param.HasValue)
	{
        	return param.Value.ToString();
	}
        else
        {
        	return string.Empty;
	}
}

Example

System.Nullable<byte> value = GetValueFromDatabase();
Textbox1.Text = value.ToNullableString();

' GetValueFromDatabase is simulating retrieving a System.Nullable<byte> value from the database.

Author: Chris Rock

Submitted on: 31 mrt 2008

Language: C#

Type: System.Nullable<T>

Views: 5705