what is the difference between Convert.ToInt16(somenumber)
and ToInt16(somenumber)
and also vs. (ToInt16)somenumber
when do we have to use one over the other?
what is the difference between Convert.ToInt16(somenumber)
and ToInt16(somenumber)
and also vs. (ToInt16)somenumber
when do we have to use one over the other?
What is the type of somenumber
? Convert.ToXXX
is designed for use with databases and such where you might not know the exact type you're converting from, just that the data is numeric of some sort.
For more typical conversion of a numeric variable to a different size, a cast is better. But your cast syntax is a little off, it should be (Int16)somenumber
(no "To").
Finally ToInt16(somenumber)
looks for a function or delegate field ToInt16
in the current class (and its base classes), so it's unlikely to compiler properly.
Convert.Int16()
is a method (probably) in System.Convert
. It has a number of overloads that convert from a type to Int16
.ToInt16()
could be a method defined for a particular class, but most likely you are just referring to the exact same method. Read up on namespaces.
But if you have a class called Unicorn
and it has a ToInt16()
method, you obviously will have to use that as there is no overload in System.Convert
that supports Unicorn
.
I'd be willing to bet that are exactly the same thing. Perhaps you meant Convert.ToInt16(somenumber)
and Int16.Parse(somenumber).
In that case the method signature is Convert.ToInt16(Object somenumber)
and Int16.Parse(string somenumber)
.
The Convert stuff converts an object
to a specified type and the Parse stuff Parses a string
into a specified type.
Convert.ToInt16(somenumber)
Like said by others, Is a method that can be used to convert some types (string for example) to Int16
.
ToInt1(somenumber)
I have no idea what this is.
(ToInt16)somenumber
- No such thing, there is however (Int16)somenumber
that will cast an object the has an explicit operator overload that return Int16
(take a look here)