Wednesday 1 June 2016

Convert the Non Nullable types to Nullable Types and Nullable Types to Non Nullable Types in C#

In this post we are going are going to see how to convert a Non Nullable Types and Nullable Types to Non Nullable Types in C#. Generally in C# programming there might be a chance that we have to assign a value from Non Nullable to Nullable or Nullable to Non Nullable , to do it easily now we are going to see an Extension Method , which can be useful very handy.


public static class Extensions
    {
        public static T ConvertTypeTo<T>(this object obj)
        {
            Type typ = typeof(T);
            Type Ntype = Nullable.GetUnderlyingType(typ);
                
             if (obj == null)
                    return default(T);
if (Ntype == null) { return (T)Convert.ChangeType(obj, typ); } else { return (T)Convert.ChangeType(obj, Ntype); } } public static T? ToNullable<T>(this object x) where T:struct { return x == null ? null : (T?)Convert.ChangeType(x, typeof(T)); } }



We can use this Extension class like below, this method will reflect in each and every object.


class Program
    {
        public static Nullable<bool> IsLogin { set; get; }

        static void Main(string[] args)
        {
            int total = 10;
            bool ischeck = false;
            

            Nullable<int> res1 = total.ConvertTypeTo<Nullable<int>>();
            int res3 = res1.ConvertTypeTo<int>();

            if (res1.HasValue)
            Console.WriteLine(res1);

            Console.WriteLine(res3);

            Nullable<bool> res2 = ischeck.ToNullable<bool>();

            Console.WriteLine(res2.Value);

            bool _login = IsLogin.ConvertTypeTo<bool>();

            Console.WriteLine(_login);

            Console.Read();

        }
    }



The output of this code is 



From this post you can see how to convert a Nullable to NonNullable Types, Non Nullable Types to Nullable 

No comments:

Post a Comment