Object type to int,how?

FlyBoy

Centurion
Joined
Sep 6, 2004
Messages
106
i have the following code,which im trying (for educational purposes only) convert an object type to int...this is the code:
class test
{
public test(object obj)
{
int tmp;
try
{
tmp=Int32.Parse(obj);;
x=tmp;
}
catch (System.Exception ex)
{
}

}
.
.
.
.
.
.
it doesnt work..tried also : int.prase(obj). and still didnt work...any idea?
 
If the variable really does contain and int then you can simply do
C#:
int tmp = (int) obj;

This will only work if obj is really an int (not a string that contains a number etc)
 
PlausiblyDamp said:
If the variable really does contain and int then you can simply do
C#:
int tmp = (int) obj;

This will only work if obj is really an int (not a string that contains a number etc)


thats why im using error catch handlers....
this mathod called Casting right? (never figured what is the diffrence bwtween this,and the method i've tried.) :o
 
In .Net all data types are ultimately derived from object; therefore a variable declared as object can hold any datatype.
Casting is merely the process of taking a generic representation (i.e. object or a base class if inheritance is being used) and creating a more specific variable to represent it.

Things like int.Parse() will convert between two different types of variables i.e. a string that may contain an integer represented as a string andan actual integer.
 
For a cross-language solution, you can also use the static methods of the Convert
class (i.e. Convert.ToInt32(), in this case).
 
Back
Top