Casting, Converting, Is, As, TryParse, Parse, GetType and typeof - High-Flying C# Coding Tips


Sponsored Links

73058_New Scooba® 230 Floor Washing Robot + Free Shipping!

 

Converting, Casting, Is, As, TryParse, Parse, GetType and typeof

Here we'll look at the different ways of Converting and Casting objects to different types of objects.  You may end up doing this quite frequently, and for various different reasons.  For instance you may need to take the contents of a textbox which is a string and convert the value as an integer to use it in a method for processing something.

You may want to convert or cast objects from the type of object which they are into a different type of object. This is quite useful and required on many projects quite frequently. There are several ways to convert and cast objects which are detailed below.


Converting

The different types in C# such as integers, booleans and strings have a Convert.To method such as for example Convert.ToIn32("3"), Convert.ToBoolean("true") and Convert.ToString(123).  There are different overloaded versions of the Convert methods such as Convert.ToString(bool value) and Convert.ToString(DateTime value).  However, you must be careful as if the conversion should fail then an error will occur.  The TryParse method mentioned further down this page is a good mechanism to prevent an application erroring should the conversion fail.

In this example, we have a string called '_number' with a value of '1234'. We then convert it into an integer using the Convert.ToInt32(string) method (provided that the string is actually a numeric value), called '_numberConversion'.  After this we convert the integer back into a string called '_conversionBack' using the .ToString() method.



// take a string containing a number
string _number = "1234";

// convert the string into an integer
int _numberConversion = Convert.ToInt32(_number);

// here we convert the integer into a string,
// the string contains the number
string _conversionBack = _numberConversion.ToString();


Casting

Casting attempts to cast one object to another type of object, or turn an object into another type of object.

Casting is not limited to the pre-defined Convert methods which come attached to the standard .NET types, you can attempt to cast any object to any other object, including the custom objects you create yourself.  However, just like the Convert methods, there will be an error if the cast fails.  Is and As are potential ways around this, both of which are mentioned below.

The following code sample shows some examples of casting.


// Cast a decimal to an integer but lose the decimal point.
decimal moneyAmount = 23.45M;
int loseDecimalPoint = (int)moneyAmount;

// Find control called Label1 and cast it from a Control to a Label so we
// can reference the Label in the code.
Label label1Reference = (Label)this.FindControl("Label1");


Is and As

Is allows you test at runtime whether an object can be cast to another type.

As will perform a cast, but it the cast fails, then it won't throw an exception but instead return null.


// Is
string s = "test";
object oTest = s;
if (oTest is String)
{
    // oTest is a string
}
else
{
    // oTest is not a string
}

// As
string testString = "test";
int testInt = 12;
object oTestString = testString;
object oTestInt = testInt;

// testStringResult = "test";
string testStringResult = oTestString as string;
// testIntResult = null;
string testIntResult = oTestInt as string;


Parse

Parse is similar to Convert in that it attempts to convert (or parse) the provided value into the type of object which calls the Parse, for instance Int32.Parse(stringNumber) will attempt to convert the string called stringNumber into an integer.  However should the parsing fail, then an error will occur.


// Parse a string into an integer.
string number = "123";
int test = Int32.Parse(number);


TryParse

TryParse is similar to the Parse method in that it attempts to Parse a value into the type of object which is making the TryParse call.  However, should the parsing fail in this case, there will not be an error, only the integer will have a value of 0 and code execution will continue.  So as long as you are aware the method could return a zero (0) when in fact the parsing has failed, then this method can help to prevent errors ocurring in your code.  For instance, Int32.TryParse(stringValue, out parsedInteger) will try to convert the string called stringValue into an integer as an out parameter called parsedInteger.


int test2 = 0;
Int32.TryParse(number, out test2);


Further to this, the outcome of the TryParse call can be assigned to a boolean so that you know in the code if the parse was successful or not.


bool parseAttempt = false;
parseAttempt = Int32.TryParse(number, out test2);
if (parseAttempt == true)
{
    // number parsed into an integer
    number = number + 1;
}


GetType and typeof

GetType and typeof can be combined to check to see if an object is of a certain type.


int testNumber = 5;

if (testNumber.GetType() == typeof(int))
{
    // testNumber is an integer
}