tags:

views:

126

answers:

4

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?

+4  A: 

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.

Ben Voigt
It's worth noting that if this were VB, you can include static classes as an `Imports` directive, allowing you to access static functions in this manner. I.E., if he had `Imports System.Convert` at the top of the file, you could call `ToInt16(num)`.
Adam Robinson
+4  A: 

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.

NullUserException
`Convert` is a class, not a namespace, so you can't bring its members into scope with `using` (although this feature has been requested many times for e.g. `System.Math`).
Ben Voigt
@Ben Yeah, I just realized that.
NullUserException
+2  A: 

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.

Shawn
+2  A: 

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)

Itay
sheket b'vakasha!
i am a girl
sababa jenny I'll be besheket :)
Itay