Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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?

Posted
If the variable really does contain and int then you can simply do

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

  • Administrators
Posted

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.

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

  • *Experts*
Posted

For a cross-language solution, you can also use the static methods of the Convert

class (i.e. Convert.ToInt32(), in this case).

"Being grown up isn't half as fun as growing up

These are the best days of our lives"

-The Ataris, In This Diary

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...