Jump to content


Check out our Community Blogs





- - - - -

C# Generic Type Converter

Posted by VNFox, 24 May 2013 · 6139 views

tutorial c# programming
I've seen many type converter in C#, but I haven't come to a generic one yet ... so I decide to write one. I hope this will help ... someone out there :)

This method provides a unified way of converting object of values to other types.
        /// <summary>
        /// Converts to the type that you like
        /// </summary>
        /// <author>www.pickmike.com</author>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static T convertToType<T>(object value, T defaultValue)
        {
            T result = defaultValue;
            try
            {
                if (value != null)
                {
                    bool tryToCast = true;
                    // Checks for the date
                    if (typeof(T) == typeof(DateTime)) { if (string.IsNullOrEmpty(value.ToString())) { tryToCast = false; } }

                    if (tryToCast) { result = (T)Convert.ChangeType(value, typeof(T)); }
                }
            }
            catch { }
            return result;
        }

Usage:
int myInt = convertToType<int>("10", 0);
DateTime? myDate = convertToType<DateTime?>("something invalid", null);

  • 0



aren't there one line ifs in c#?

    • 0

Not sure what do you mean by one line ifs ... I personally like to have {  } in if ... even if íts just one line .. íts best for debug

    • 0

Recent Entries

Recent Comments

My Picture

0 user(s) viewing

0 members, 0 guests, 0 anonymous users

Categories