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;
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>();


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


Double click on the code to select all.