What would be the best way to cast an object to an int?
object obj = new obj();
int i;
i = int.parse(obj.ToString()); this way??
or
i = (int)obj; or this way?
Cheers
Printable View
What would be the best way to cast an object to an int?
object obj = new obj();
int i;
i = int.parse(obj.ToString()); this way??
or
i = (int)obj; or this way?
Cheers
I'd say the last one.
The first one requires you to call the ToString method first and then parse it, I cant possibly see that as being better than (int).
But I could very well be wrong:D
Hi thanks,
Yes thats what I thought,.. but still not sure whats best
You can use the Convert or Parse methods, but i believe it is standard in C# to do it like the last method in your first post ;)
I'm sure underneath, (int)obj calls the int.parse(obj.ToString()) method. Either way, you'll get a crash if the obj isn't an int. (int)obj is less lines, so I'd probably just use that.
No, it doesn't. If the object provides an (int) cast operator then that will be called. If not, you'll get an invalid cast operation.Quote:
Originally Posted by MetalKid
Remember that casting and conversion are two separate things. Casting is used when the data can be equally well expressed using either type; conversion involves some loss of data. As such, the samples given in the lead post serve different purposes. The first produces some string representation of the object and then attempts to convert it to an integer. The second attempts to unbox an integer. Both are prone to failure since it is not guaranteed that the object will be of a type that allows either operation.
In 1.1, you'd have to wrap this in a try/catch to get solid casting.
In 2.0, you can use int.TryParse.
http://msdn2.microsoft.com/en-us/library/f02979c7.aspxCode:Object someObject= new Object("123");
int endResult = 0;
if (int.TryParse(someObject.ToString(), out endResult))
{
'you have a valid converted integer in endResult
}
else
{
'you have invalid conversion
}
There would be no need for an exception handler in .NET 1.1. You would just have use double.TryParse and specified the NumberStyle as Integer:Quote:
Originally Posted by nemaroller
Note also that what you're doing there is converting, not casting.Code:Object someObject= new Object("123");
int endResult = 0;
double temp;
if (double.TryParse(someObject.ToString(), System.Globalization.NumberStyles.Integer, null, out temp))
{
endResult = (int)temp;
// you have a valid converted integer in endResult
}
else
{
// you have invalid conversion
}
I was never aware of double.TryParse in .NET 1.1, or have long since forgotten it - a good lesson either way.
Yes, the proper term is 'conversion' and not 'casting'. As a side note, you should implement a preposition in your reply:
"You would just have to use ..."
Thanks, but what I actually meant was "You would just have used...".Quote:
Originally Posted by nemaroller