Click here to Skip to main content
15,867,594 members
Articles / Programming Languages / C# 3.5
Tip/Trick

Custom String to ValueType Converter

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
25 Jul 2014CPOL1 min read 10.7K   60   3   4
Methods which facilitate the conversion from string to value type

Introduction

Recently, I came across a situation in which we wanted to convert string value to ValueType. So, I thought of writing some custom converter code that simplifies the conversion without calling Convert.ToXXX().

Background

There were two scenarios:

  1. Convert the string into Nullable types: If conversion succeeds, return value, else return null.
  2. Convert the string into Value type: If conversion succeeds, return value, else return default value of that type.

Using the Code

Referring to the code, we solved the problem:

  1. Convert the string into Nullable types: If conversion succeeds, return value, else return null. Achieved through: ConvertStringToNullableValueType<T>
  2. Convert the string into Value type: If conversion succeeds, return value, else return default value of that type. Achieved through: ConvertStringToValueType<T>
C#
public static class Converter
{
    /// <summary>
    /// Converts string into required Structure Type
    /// </summary>
    /// <typeparam name="T">Structure Type</typeparam>
    /// <param name="str">input string</param>
    /// <returns>type if conversion succeeds, returns null if conversion fails</returns>
    public static T? ConvertStringToNullableValueType<T>(string str) where T : struct
    {
        try
        {
            if (!typeof (T).IsValueType)
                throw new Exception();
            var returnType = (T)Convert.ChangeType(str, typeof(T));
            return returnType;
        }
        catch (Exception)
        {
            return null;
        }
    }
    
    /// <summary>
    /// Converts string into required Structure Type
    /// </summary>
    /// <typeparam name="T">Structure Type</typeparam>
    /// <param name="str">input string</param>
    /// <returns>type if conversion succeeds, returns defaultvalue of type if conversion fails
    /// </returns>
    public static T ConvertStringToValueType<T>(string str) where T : struct
    {
        try
        {
            if (!typeof (T).IsValueType)
                throw new Exception();
            var returnType = (T)Convert.ChangeType(str, typeof(T));
            return returnType;
        }
        catch (Exception)
        {
            return default(T);
        }
    } 
}

Some basic test methods to check if the code works as expected:

C#
[TestMethod]
public void ConvertStringToNullableValueTypeTest_OnPassingValidIntegerString_ShouldReturnInteger()
{
    string str = "1000";
    var intval= Converter.ConvertStringToNullableValueType<Int32>(str);
    Assert.AreEqual(1000,intval);
}
[TestMethod]
public void ConvertStringToNullableValueTypeTest_OnPassingInvalidIntegerString_ShouldReturnNull()
{
    string str = "1000A";
    var intval = Converter.ConvertStringToNullableValueType<Int32>(str);
    Assert.AreEqual(null, intval);
}

[TestMethod]
public void ConvertStringToValueTypeTest_OnPassingValidIntegerString_ShouldReturnInteger()
{
    string str = "1000";
    var intval = Converter.ConvertStringToValueType<Int32>(str);
    Assert.AreEqual(1000, intval);
}
[TestMethod]
public void ConvertStringToValueTypeTest_OnPassingInvalidIntegerString_ShouldReturnZero()
{
    string str = "1000A";
    var intval = Converter.ConvertStringToValueType<Int32>(str);
    Assert.AreEqual(0, intval);
}

Points of Interest

To simplify it further, I hooked up these methods of CustomConverter class to String class using concept of extension methods. To know more about extension methods, please refer to the MSDN link:

C#
public static class StringExtension
{
    public static T? ConvertStringToNullableValueType<T>(this string str) where T : struct
    {
        try
        {
            if (!typeof (T).IsValueType)
                throw new Exception();
            var returnType = (T) Convert.ChangeType(str, typeof (T));
            return returnType;
        }
        catch (Exception)
        {
            return null;
        }
    }
    
    public static T ConvertStringToValueType<T>(this string str) where T : struct
    {
        try
        {
            if (!typeof (T).IsValueType)
                throw new Exception();
            var returnType = (T) Convert.ChangeType(str, typeof (T));
            return returnType;
        }
        catch (Exception)
        {
            return Activator.CreateInstance<T>();
        }
    }
}

And now, these methods can be invoked by using object of String class!

C#
[TestMethod]
public void ConvertStringToNullableValueType_OnPassingValidString_ShouldReturnValue()
{
    var str = "1234"; 
    var actual = str.ConvertStringToNullableValueType<Int32>();
    Assert.AreEqual(1234, actual);
}

[TestMethod]
public void ConvertStringToNullableValueTypeTest_OnPassingInvalidString_ShouldReturnNull()
{
    var str = "1234AA"; 
    var actual = str.ConvertStringToNullableValueType<Int32>();
    Assert.AreEqual(null, actual);
}

/// <summary>
///A test for ConvertStringToValueType
///</summary>
[TestMethod]
public void ConvertStringToValueType_OnPassingValidString_ShouldReturnValue()
{
    string str = "1234"; // TODO: Initialize to an appropriate value
    var actual = str.ConvertStringToValueType<Int32>();
    Assert.AreEqual(1234, actual);
}

[TestMethod]
public void onvertStringToValueTypeTest_OnPassingInvalidString_ShouldReturnZero()
{
    string str = "1234ABCD"; // TODO: Initialize to an appropriate value
    var actual = str.ConvertStringToValueType<Int32>();
    Assert.AreEqual(0, actual);
}

The source code contains the complete logic and few more sample tests!

Feel free to suggest some improvements. :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead iGATE Global Solutions
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionSignificant difference Pin
VallarasuS25-Jul-14 7:39
VallarasuS25-Jul-14 7:39 
GeneralRe: Significant difference Pin
PIEBALDconsult25-Jul-14 8:15
mvePIEBALDconsult25-Jul-14 8:15 
GeneralRe: Significant difference Pin
Kishor Deshpande29-Jul-14 0:24
professionalKishor Deshpande29-Jul-14 0:24 
AnswerRe: Significant difference Pin
Kishor Deshpande29-Jul-14 0:17
professionalKishor Deshpande29-Jul-14 0:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.