FlyBoy Posted October 14, 2004 Posted October 14, 2004 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? Quote
Administrators PlausiblyDamp Posted October 14, 2004 Administrators Posted October 14, 2004 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) Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
FlyBoy Posted October 14, 2004 Author Posted October 14, 2004 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 Quote
Administrators PlausiblyDamp Posted October 14, 2004 Administrators Posted October 14, 2004 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. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
*Experts* Bucky Posted October 15, 2004 *Experts* Posted October 15, 2004 For a cross-language solution, you can also use the static methods of the Convert class (i.e. Convert.ToInt32(), in this case). Quote "Being grown up isn't half as fun as growing up These are the best days of our lives" -The Ataris, In This Diary
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.