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

ToNullable

Converts a string to a primitive type or an enum type. Faster than tryparse blocks. Easier to use, too. Very efficient.

Source

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TodoList
{
    public static class ToNullableStringExtension
    {
        public static T? ToNullable<T>(this string p_self) where T : struct
        {
            if (p_self != null)
            {
                var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
                if (converter.IsValid(p_self))
                {
                    return (T)converter.ConvertFromString(p_self);
                }
            }

            return null;
        }
    }
}

Example

int? numVotes = "123".ToNullable<int>();
decimal price = tbxPrice.Text.ToNullable<decimal>() ?? 0.0M;
PetTypeEnum petType = "Cat".ToNullable<PetTypeEnum>() ?? PetTypeEnum.DefaultPetType;

string thisWillNotThrowException = null;
int? nullsAreSafe = thisWillNotThrowException.ToNullable<int>();

Author: Taylor Love

Submitted on: 6 apr. 2016

Language: C#

Type: string

Views: 4673