This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
difference between Convert.ToInt32 and (int)
Whats the main difference between int.Parse() and Convert.ToInt32
C#
Are there any differences between the type.Parse() methods and the methods at ConvertTo class?
No there is no substantial difference between Int32.Parse and Convert.ToInt32(string). The latter just forwards it's call to Int32.Parse
One minor difference though is that if you pass null to Convert.ToInt32 it will return 0, while Int32.Parse will through an ArgumentNullException
One notable difference is TypeConverter.ConvertTo(object) doesn't throw an exception when object is null, but type.parse does throws an exception when its contents are null
Most Important Difference is:
-Convert.ToInt32(s) doesn't throw an exception when s is null, but Parse()
does
If you're collecting input from a
user, you'd generally user
Int32.TryParse()
Int32.Parse() and Int32.TryParse()
can only convert strings.
Convert.ToInt32() can take any class
that implements IConvertible.
Basically in all truth, When you look
at the source from TryParse it
actually has no exception handling at
all - just character manipulation and
bit shifting
For Performance details, read this
post:
http://blogs.msdn.com/b/ianhu/archive/2005/12/19/505702.aspx
There are some differences, e.g. Convert can convert to Int32 from many objects (Int16, string, SByte, etc.). Also, Int32.Parse can accept NumberStyles, which Convert.ToInt32 cannot.
Other than that, Reflector (http://reflector.red-gate.com) has this to say:
class Convert:
public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value, CultureInfo.CurrentCulture);
}
AFAIK, int.Parse() is inherited from the Number class, where it's defined. Convert.ToIn32() implements the IConvertable interface and gets the type of the object you pass before handling the conversion.
Either way I think it ends up at Int32.Parse anyway.
Here's the code retrieved using Reflector.
Int32.Parse:
public static int Parse(string s)
{
return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
internal static unsafe int ParseInt32(string s, NumberStyles style,
NumberFormatInfo info)
{
byte* stackBuffer = stackalloc byte[1 * 0x72];
NumberBuffer number = new NumberBuffer(stackBuffer);
int num = 0;
StringToNumber(s, style, ref number, info, false);
if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
{
if (!HexNumberToInt32(ref number, ref num))
{
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
return num;
}
if (!NumberToInt32(ref number, ref num))
{
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
return num;
}
Convert.ToInt32:
public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value, CultureInfo.CurrentCulture);
}
So, Convert anyway calls methods of Int32. Using of Int32.Parse will be more efficiently, but you need take into account that it can throw exception on passing null argument.
Converting or direct casting can cause data loss. You should consider making use of "is" and "as" over casting or converting. In addition to protection against data loss, these are both more efficient at runtime.
As Austin stated, if you are going to parse, use tryparse and handle failures accordingly.
Related
This question already has answers here:
Is casting the same thing as converting?
(11 answers)
Closed 9 years ago.
I have been working on some code for a while. And I had a question: What's the difference among casting, parsing and converting? And when we can use them?
Casting is when you take a variable of one type and change it to a different type. You can only do that in some cases, like so:
string str = "Hello";
object o = str;
string str2 = (string)o; // <-- This is casting
Casting does not change the variable's value - the value remains of the same type (the string "Hello").
Converting is when you take a value from one type and convert it to a different type:
double d = 5.5;
int i = (int)d; // <---- d was converted to an integer
Note that in this case, the conversion was done in the form of casting.
Parsing is taking a string and converting it to a different type by understanding its content. For instance, converting the string "123" to the number 123, or the string "Saturday, September 22nd" to a DateTime.
Casting: Telling the compiler that an object is really something else without changing it (though some data loss may be incurred).
object obj_s= "12345";
string str_i = (string) obj; // "12345" as string, explicit
int small = 12345;
long big = 0;
big = small; // 12345 as long, implicit
Parsing: Telling the program to interpret (on runtime) a string.
string int_s = "12345";
int i = int.Parse(int_s); // 12345 as int
Converting: Telling the program to use built in methods to try to change type for what may be not simply interchangeable.
double dub = 123.45;
int i = System.Convert.ToInt32(dub); // 123 as int
These are three terms each with specific uses:
casting - changing one type to another. In order to do this, the
types must be compatible: int -> object; IList<T> -> IEnumerable<T>
parsing - typically refers to reading strings and extracting useful parts
converting - similar to casting, but typically a conversion would involve changing one type to an otherwise non-compatible type. An example of that would be converting objects to strings.
A cast from one type to another requires some form of compatibility, usually via inheritance or implementation of an interface. Casting can be implicit or explicit:
class Foo : IFoo {
// implementations
}
// implicit cast
public IFoo GetFoo() {
return Foo;
}
// explicit cast
public IFoo GetFoo() {
return Foo as IFoo;
}
There are quite a few ways to parse. We read about XML parsing; some types have Parse and TryParse methods; and then there are times we need to parse strings or other types to extract the 'stuff we care about'.
int.Parse("3") // returns an integer value of 3
int.TryParse("foo", out intVal) // return true if the string could be parsed; otherwise false
Converting may entail changing one type into another incompatible one. This could involve some parsing as well. Conversion examples would usually be, IMO, very much tied to specific contexts.
casting
(casting to work the types need to be compatible)
Converting between data types can be done explicitly using a cast
static void _Casting()
{
int i = 10;
float f = 0;
f = i; // An implicit conversion, no data will be lost.
f = 0.5F;
i = (int)f; // An explicit conversion. Information will be lost.
}
parsing (Parsing is conversion between different types:)
converts one type to another type can be called as parsing uisng int.parse
int num = int.Parse("500");
traversing through data items like XML can be also called as parsing
When user-defined conversions get involved, this usually entails returning a different object/value. user-defined conversions usually exist between value types rather than reference types, so this is rarely an issue.
converting
Using the Convert-class actually just helps you parse it
for more please refer http://msdn.microsoft.com/en-us/library/ms228360%28VS.80%29.aspx
This question is actually pretty complicated...
Normally, a cast just tells the runtime to change one type to another. These have to be types that are compatible. For example an int can always be represented as a long so it is OK to cast it to a long. Some casts have side-effects. For example, a float will drop its precision if it is cast to an int. So (int)1.5f will result in int value 1. Casts are usually the fastest way to change the type, because it is a single IL operator. For example, the code:
public void CastExample()
{
int i = 7;
long l = (long)i;
}
Performs the cast by running the IL code:
conv.i8 //convert to 8-byte integer (a.k.a. Int64, a.k.a. long).
A parse is some function that takes in once type and returns another. It is an actual code function, not just an IL operator. This usually takes longer to run, because it runs multiple lines of code.
For example, this code:
public void ParseExample()
{
string s = "7";
long l = long.Parse(s);
}
Runs the IL code:
call int64 [mscorlib]System.Int64::Parse(string)
In other words it calls an actual method. Internally, the Int64 type provides that method:
public static long Parse(String s) {
return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
And Number.Parse:
[System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static Int64 ParseInt64(String value, NumberStyles options, NumberFormatInfo numfmt) {
Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
Int64 i = 0;
StringToNumber(value, options, ref number, numfmt, false);
if ((options & NumberStyles.AllowHexSpecifier) != 0) {
if (!HexNumberToInt64(ref number, ref i)) {
throw new OverflowException(Environment.GetResourceString("Overflow_Int64"));
}
}
else {
if (!NumberToInt64(ref number, ref i)) {
throw new OverflowException(Environment.GetResourceString("Overflow_Int64"));
}
}
return i;
}
And so on... so you can see it is actually doing a lot of code.
Now where things get more complicated is that although a cast is usually the fastest, classes can override the implicit and explicit cast operators. For example, if I write the class:
public class CastableClass
{
public int IntValue { get; set; }
public static explicit operator int(CastableClass castable)
{
return castable.IntValue;
}
}
I have overridden the explicit cast operator for int, so I can now do:
public void OverridedCastExample()
{
CastableClass cc = new CastableClass {IntValue = 7};
int i = (int)cc;
}
Which looks like a normal cast, but in actuality it calls my method that I defined on my class. The IL code is:
call int32 UnitTestProject1.CastableClass::op_Explicit(class UnitTestProject1.CastableClass)
So anyway, you typically want to cast whenever you can. Then parse if you can't.
Casting: or Parsing
A cast explicitly invokes the conversion operator from one type to another.
Casting variables is not simple. A complicated set of rules resolves casts. In some cases data is lost and the cast cannot be reversed. In others an exception is provoked in the execution engine.
int.Parse is a simplest method but it throws exceptions on invalid input.
TryParse
int.TryParse is one of the most useful methods for parsing integers in the C# language. This method works the same way as int.Parse.
int.TryParse has try and catch structure inside. So, it does not throw exceptions
Convert:
Converts a base data type to another base data type.
Convert.ToInt32, along with its siblings Convert.ToInt16 and Convert.ToInt64, is actually a static wrapper method for the int.Parse method.
Using TryParse instead of Convert or Cast is recommended by many programmers.
source:www.dotnetperls.com
Different people use it to mean different things. It need not be true outside .net world, but here is what I have understood in .net context reading Eric Lippert's blogs:
All transformations of types from one form to another can be called conversion. One way of categorizing may be
implicit -
a. representation changing (also called coercion)
int i = 0;
double d = i;
object o = i; // (specifically called boxing conversion)
IConvertible o = i; // (specifically called boxing conversion)
Requires implicit conversion operator, conversion always succeeds (implicit conversion operator should never throw), changes the referential identity of the object being converted.
b. representation preserving (also called implicit reference conversion)
string s = "";
object o = s;
IList<string> l = new List<string>();
Only valid for reference types, never changes the referential identity of the object being converted, conversion always succeeds, guaranteed at compile time, no runtime checks.
explicit (also called casting) -
a. representation changing
int i = 0;
enum e = (enum)i;
object o = i;
i = (int)o; // (specifically called unboxing conversion)
Requires explicit conversion operator, changes the referential identity of the object being converted, conversion may or may not succeed, does runtime check for compatibility.
b. representation preserving (also called explicit reference conversion)
object o = "";
string s = (string)o;
Only valid for reference types, never changes the referential identity of the object being converted, conversion may or may not succeed, does runtime check for compatibility.
While conversions are language level constructs, Parse is a vastly different thing in the sense it's framework level, or in other words they are custom methods written to get an output from an input, like int.Parse which takes in a string and returns an int.
Sometimes i wonder, when converting strings to other types, for example int32, is one way better than the other, or is it just a matter of taste?
Convert.ToInt32("123")
or
Int32.Parse("123")
or
Some other way?
Not considering the case if it's not a valid int in this question.
The Convert.ToInt32 is actually implemented the following way...
int.Parse(value, CultureInfo.CurrentCulture);
...which is the same as your stated alternative except it takes into account the culture settings. The int.Parse method is itself implemented the following way...
Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
...where Number is an internal class that you cannot call directly. The Number.ParseInt32 method is marked with the following attribute...
[MethodImpl(MethodImplOptions.InternalCall)]
...showing that it is implemented inside the CLR itself.
Main difference between Conver.ToInt32 and Int32.Parse is how the treat null strings. Convert.ToInt32 returns default value in this case:
public static int ToInt32(string value)
{
if (value == null)
return 0;
return Int32.Parse(value, CultureInfo.CurrentCulture);
}
I don't like that. I think only "0" should be parsed to 0. This behavior initially was designed for Visual Basic programmers:
This is a set of conversion methods for programmers migrating from Visual Basic 6 to Visual Basic .NET that mirrored the behavior of the
existing Visual Basic 6 conversion methods. The assumption was that C#
programmers would be more comfortable with casting operators, whereas
Visual Basic had traditionally used conversion methods for type
conversion.
So, as non-VB programmer, I'd go with Int32.Parse and Int32.TryParse.
When converting from string to int I always use int.TryParse. Because you are not always sure you can convert a string to an int. Like this:
string temp="222";
int intValue;
if(int.TryParse(temp,out intValue))
{
//Something
}
As V4Vendetta suggested it is better to use TryParse to avoid exceptions related to converting.
int result = 0;
a = "3";
string b = "b";
string c = "2147483648"; //int32 max value + 1
int.TryParse(a, out result); // returns true result=3
int.TryParse(b, out result); // returns false result=0
int.TryParse(c, out result); // returns false result=0
I have a method that converts a number from string to the T, e.g int
public static T GetItemIdFromUrl<T>(string itemName)
{
try
{
...
int ad_id = int.Parse(stringNumber);
return (T)(object)ad_id;
}
catch
{
return (T)(object)-1;
}
}
but as a result I have a hex code 0xffffffa5 instead of 91. Why ?
Well, it's hard to know for sure why it's returning 0xffffffa5 without knowing the input string, but your code is going to throw an exception if T is anything other than either int or a enum with an underlying base type of int. For example, it will throw if T is double. Your method isn't really generic - the value it's trying to return is always an int. Why is your method not just declared to return int? If you want to convert from int to some other type (double, long, whatever) just let that conversion be done on assignment. The unboxing conversion in your code will not work unless T is int or an appropriate enum (the latter of which seems unlikely).
One thing to note is that 0xffffffa5 is the bit pattern for -91. Is it possible that you've only seen that result in the debugger, and the result is meant to be -91 rather than 91?
Even if your intention is to genericize the handling of different numeric types (e.g., double, decimal, etc.), this isn't the way to do it. When you box to object, and then unbox to T, it will only work if the boxed type actually is T. In other words, it will not perform a type conversion for you.
The only way (that I know of) to do the type conversion from object to whatever you want is by using the Convert class:
return (T)Convert.ChangeType(ad_id, typeof(T));
Even this is fragile, obviously (as it won't work if T is any non-numeric type); but at least it won't throw exceptions in pretty much all cases you're trying to cover. (Your method as it is currently implemented will throw for every T except int.)
I think you have a fundamental misunderstanding of what generics are and how they're supposed to be used. The whole point of generics is to have the benefit of working on different types while not losing type safety which is what happens when you cast to object
That being said Jon Skeet is probably correct that it's probably the way the debugger is displaying the result.
I think you are doing something else where you show the ellipses (...):
try
{
...
int ad_id = int.Parse(stringNumber);
return (T)(object)ad_id;
}
because I tried your sample and I get a return int.
You really don't have any way, currently, of ensuring your return is going to work. You method will rely on very specific information. Provide a bit more info where you have the ellipses and a better solution can be recommended. As Jon mentions, a nullable int? would be better. Test for the condition and if it isn't a correct return, you can check for myInt.HasValue.
I have been pondering a complete solution this problem and came up with the following:
static List<Type> numerics = new List<Type>();
static void Main(string[] args)
{
numerics.Add(typeof(Decimal));
numerics.Add(typeof(Double));
numerics.Add(typeof(Int16));
numerics.Add(typeof(Int32));
numerics.Add(typeof(Int64));
numerics.Add(typeof(Single));
numerics.Add(typeof(UInt16));
numerics.Add(typeof(UInt32));
numerics.Add(typeof(UInt64));
Console.WriteLine("StringNumber 55: {0} {1}", typeof(int), GetItemIdFromUrl<int>("55"));
Console.WriteLine("StringNumber 5B99: {0} {1}", typeof(int), GetItemIdFromUrl<int>("5B99"));
Console.ReadKey();
}
public static T GetItemIdFromUrl<T>(string stringNumber)
{
try
{
if (numerics.Contains(typeof(T)))
return (T)Convert.ChangeType(stringNumber, typeof(T));
else
return default(T);
}
catch (ArgumentException argEx)
{
Console.WriteLine("Exception\r\n{0}", argEx);
return default(T);
}
catch (FormatException formatEx)
{
Console.WriteLine("Exception\r\n{0}", formatEx);
return default(T);
}
}
From the 2nd WriteLine you will be able to see what happens if an invalid numeric is passed. Of course, I included the Exception messages just so you could see what they would return. It might not be a glamorous solution, but I think it is viable.
I also came up with this:
public static class GetNumeric<T>
{
public static Func<string, T> Value = stringValue => (T)Convert.ChangeType(stringValue, typeof(T));
}
Although I would still wrap the call in a try/catch block.
What is the difference between Convert.ToString() and .ToString()?
I found many differences online, but what's the major difference?
Convert.ToString() handles null, while ToString() doesn't.
Calling ToString() on an object presumes that the object is not null (since an object needs to exist to call an instance method on it). Convert.ToString(obj) doesn't need to presume the object is not null (as it is a static method on the Convert class), but instead will return String.Empty if it is null.
In addition to other answers about handling null values, Convert.ToString tries to use IFormattable and IConvertible interfaces before calling base Object.ToString.
Example:
class FormattableType : IFormattable
{
private double value = 0.42;
public string ToString(string format, IFormatProvider formatProvider)
{
if (formatProvider == null)
{
// ... using some IOC-containers
// ... or using CultureInfo.CurrentCulture / Thread.CurrentThread.CurrentCulture
formatProvider = CultureInfo.InvariantCulture;
}
// ... doing things with format
return value.ToString(formatProvider);
}
public override string ToString()
{
return value.ToString();
}
}
Result:
Convert.ToString(new FormattableType()); // 0.42
new FormattableType().ToString(); // 0,42
Lets understand the difference via this example:
int i= 0;
MessageBox.Show(i.ToString());
MessageBox.Show(Convert.ToString(i));
We can convert the integer i using i.ToString () or Convert.ToString. So what’s the difference?
The basic difference between them is the Convert function handles NULLS while i.ToString () does not; it will throw a NULL reference exception error. So as good coding practice using convert is always safe.
You can create a class and override the toString method to do anything you want.
For example- you can create a class "MyMail" and override the toString method to send an email or do some other operation instead of writing the current object.
The Convert.toString converts the specified value to its equivalent string representation.
The methods are "basically" the same, except handling null.
Pen pen = null;
Convert.ToString(pen); // No exception thrown
pen.ToString(); // Throws NullReferenceException
From MSDN :
Convert.ToString Method
Converts the specified value to its equivalent string representation.
Object.ToString
Returns a string that represents the current object.
object o=null;
string s;
s=o.toString();
//returns a null reference exception for string s.
string str=convert.tostring(o);
//returns an empty string for string str and does not throw an exception.,it's
//better to use convert.tostring() for good coding
I agree with #Ryan's answer. By the way, starting with C#6.0 for this purpose you can use:
someString?.ToString() ?? string.Empty;
or
$"{someString}"; // I do not recommend this approach, although this is the most concise option.
instead of
Convert.ToString(someString);
In Convert.ToString(), the Convert handles either a NULL value or not but in .ToString() it does not handles a NULL value and a NULL reference exception error. So it is in good practice to use Convert.ToString().
For Code lovers this is the best answer.
.............. Un Safe code ...................................
Try
' In this code we will get "Object reference not set to an instance of an object." exception
Dim a As Object
a = Nothing
a.ToString()
Catch ex As NullReferenceException
Response.Write(ex.Message)
End Try
'............... it is a safe code..............................
Dim b As Object
b = Nothing
Convert.ToString(b)
Convert.ToString(strName) will handle null-able values and strName.Tostring() will not handle null value and throw an exception.
So It is better to use Convert.ToString() then .ToString();
ToString() can not handle null values and convert.ToString() can handle values which are null, so when you want your system to handle null value use convert.ToString().
ToString() Vs Convert.ToString()
Similarities :-
Both are used to convert a specific type to string i.e int to string, float to string or an object to string.
Difference :-
ToString() can't handle null while in case with Convert.ToString() will handle null value.
Example :
namespace Marcus
{
class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
class Startup
{
public static void Main()
{
Employee e = new Employee();
e = null;
string s = e.ToString(); // This will throw an null exception
s = Convert.ToString(e); // This will throw null exception but it will be automatically handled by Convert.ToString() and exception will not be shown on command window.
}
}
}
Here both the methods are used to convert the string but the basic difference between them is: Convert function handles NULL, while i.ToString() does not it will throw a NULL reference exception error. So as good coding practice using convert is always safe.
Let's see example:
string s;
object o = null;
s = o.ToString();
//returns a null reference exception for s.
string s;
object o = null;
s = Convert.ToString(o);
//returns an empty string for s and does not throw an exception.
Convert.ToString(value) first tries casting obj to IConvertible, then IFormattable to call corresponding ToString(...) methods. If instead the parameter value was null then return string.Empty. As a last resort, return obj.ToString() if nothing else worked.
It's worth noting that Convert.ToString(value) can return null if for example value.ToString() returns null.
See .Net reference source
i wrote this code and compile it.
class Program
{
static void Main(string[] args)
{
int a = 1;
Console.WriteLine(a.ToString());
Console.WriteLine(Convert.ToString(a));
}
}
by using 'reverse engineering' (ilspy) i find out 'object.ToString()' and 'Convert.ToString(obj)' do exactly one thing.
infact 'Convert.ToString(obj)' call 'object.ToString()' so 'object.ToString()' is faster.
Object.ToString Method:
class System.Object
{
public string ToString(IFormatProvider provider)
{
return Number.FormatInt32(this, null, NumberFormatInfo.GetInstance(provider));
}
}
Conver.ToString Method:
class System.Convert
{
public static string ToString(object value)
{
return value.ToString(CultureInfo.CurrentCulture);
}
}
Convert.Tostring() function handles the NULL whereas the .ToString() method does not. visit here.
In C# if you declare a string variable and if you don’t assign any value to that variable, then by default that variable takes a null value. In such a case, if you use the ToString() method then your program will throw the null reference exception. On the other hand, if you use the Convert.ToString() method then your program will not throw an exception.
Convert.Tostring() basically just calls the following value == null ? String.Empty: value.ToString()
(string)variable will only cast when there is an implicit or explicit operator on what you are casting
ToString() can be overriden by the type (it has control over what it does), if not it results in the name of the type
Obviously if an object is null, you can't access the instance member ToString(), it will cause an exception
This is probably trivial, but I can't think of a better way to do it. I have a COM object that returns a variant which becomes an object in C#. The only way I can get this into an int is
int test = int.Parse(string.Format("{0}", myobject))
Is there a cleaner way to do this? Thanks
You have several options:
(int) — Cast operator. Works if the object already is an integer at some level in the inheritance hierarchy or if there is an implicit conversion defined.
int.Parse()/int.TryParse() — For converting from a string of unknown format.
int.ParseExact()/int.TryParseExact() — For converting from a string in a specific format
Convert.ToInt32() — For converting an object of unknown type. It will use an explicit and implicit conversion or IConvertible implementation if any are defined.
as int? — Note the "?". The as operator is only for reference types, and so I used "?" to signify a Nullable<int>. The "as" operator works like Convert.To____(), but think TryParse() rather than Parse(): it returns null rather than throwing an exception if the conversion fails.
Of these, I would prefer (int) if the object really is just a boxed integer. Otherwise use Convert.ToInt32() in this case.
Note that this is a very general answer: I want to throw some attention to Darren Clark's response because I think it does a good job addressing the specifics here, but came in late and wasn't voted as well yet. He gets my vote for "accepted answer", anyway, for also recommending (int), for pointing out that if it fails (int)(short) might work instead, and for recommending you check your debugger to find out the actual runtime type.
The cast (int) myobject should just work.
If that gives you an invalid cast exception then it is probably because the variant type isn't VT_I4. My bet is that a variant with VT_I4 is converted into a boxed int, VT_I2 into a boxed short, etc.
When doing a cast on a boxed value type it is only valid to cast it to the type boxed.
Foe example, if the returned variant is actually a VT_I2 then (int) (short) myObject should work.
Easiest way to find out is to inspect the returned object and take a look at its type in the debugger. Also make sure that in the interop assembly you have the return value marked with MarshalAs(UnmanagedType.Struct)
Convert.ToInt32(myobject);
This will handle the case where myobject is null and return 0, instead of throwing an exception.
Use Int32.TryParse as follows.
int test;
bool result = Int32.TryParse(value, out test);
if (result)
{
Console.WriteLine("Sucess");
}
else
{
if (value == null) value = "";
Console.WriteLine("Failure");
}
Maybe Convert.ToInt32.
Watch out for exception, in both cases.
var intTried = Convert.ChangeType(myObject, typeof(int)) as int?;
I am listing the difference in each of the casting ways. What a particular type of casting handles and it doesn't?
// object to int
// does not handle null
// does not handle NAN ("102art54")
// convert value to integar
int intObj = (int)obj;
// handles only null or number
int? nullableIntObj = (int?)obj; // null
Nullable<int> nullableIntObj1 = (Nullable<int>)obj; // null
// best way for casting from object to nullable int
// handles null
// handles other datatypes gives null("sadfsdf") // result null
int? nullableIntObj2 = obj as int?;
// string to int
// does not handle null( throws exception)
// does not string NAN ("102art54") (throws exception)
// converts string to int ("26236")
// accepts string value
int iVal3 = int.Parse("10120"); // throws exception value cannot be null;
// handles null converts null to 0
// does not handle NAN ("102art54") (throws exception)
// converts obj to int ("26236")
int val4 = Convert.ToInt32("10120");
// handle null converts null to 0
// handle NAN ("101art54") converts null to 0
// convert string to int ("26236")
int number;
bool result = int.TryParse(value, out number);
if (result)
{
// converted value
}
else
{
// number o/p = 0
}
There's also TryParse.
From MSDN:
private static void TryToParse(string value)
{
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
}
Strange, but the accepted answer seems wrong about the cast and the Convert in the mean that from my tests and reading the documentation too it should not take into account implicit or explicit operators.
So, if I have a variable of type object and the "boxed" class has some implicit operators defined they won't work.
Instead another simple way, but really performance costing is to cast before in dynamic.
(int)(dynamic)myObject.
You can try it in the Interactive window of VS.
public class Test
{
public static implicit operator int(Test v)
{
return 12;
}
}
(int)(object)new Test() //this will fail
Convert.ToInt32((object)new Test()) //this will fail
(int)(dynamic)(object)new Test() //this will pass
You can first cast object to string and then cast the string to int;
for example:
string str_myobject = myobject.ToString();
int int_myobject = int.Parse(str_myobject);
this worked for me.
int i = myObject.myField.CastTo<int>();
This worked for me, returning 0 also when myobject contains a DBNull
int i = myobject.ToString().Cast<int>().FirstOrDefault();