int flbh =0; flbh =sql convertt.toint32(textTDK.text.t

c# - difference between Convert.ToInt32 and (int) - Stack Overflow
to customize your list.
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
J it only takes a minute:
Join the Stack Overflow community to:
Ask programming questions
Answer and help your peers
Get recognized for your expertise
the following syntax throws an compile time error like
Cannot convert type 'string' to 'int'
string name=(Session["name1"].ToString());
int i = (int)
whereas the code below compiles and executes successfully
string name=(Session["name1"].ToString());
int i = Convert.ToInt32(name);
I would like to know
why the compile time error occurs in
first code
what's the difference between the 2
code snippets
1,42362540
(int)foo is simply a cast to the Int32 (int in C#) type. This is built into the CLR and requires that foo be a numeric variable (e.g. float, long, etc.) In this sense, it is very similar to a cast in C.
Convert.ToInt32 is designed to be a general conversion function. It does a good de namely, it can convert from any primitive type to a int (most notably, parsing a string). You can see the full list of overloads for this method .
85.7k34200257
(this line relates to a question that was merged) You should never use (int)someString - that will never work (and the compiler won't let you).
However, int int.Parse(string) and bool int.TryParse(string, out int) (and their various overloads) are fair game.
Personally, I mainly only use Convert when I'm dealing with reflection, so for me the choice is Parse and TryParse. The first is when I expect the value to be a valid integer, and want it to throw an exception otherwise. The second is when I want to check if it is a valid integer - I can then decide what to do when it is/isn't.
596k13816552139
To quote from this :
Cast means two contradictory things: "check to see if this object really is of this type, throw if it is not" and "this object is n find me an equivalent value that belongs to the given type".
So what you were trying to do in 1.) is assert that yes a String is an Int.
But that assertion fails since String is not an int.
The reason 2.) succeeds is because Convert.ToInt32() parses the string and returns an int.
It can still fail, for example:
Convert.ToInt32("Hello");
Would result in an Argument exception.
To sum up, converting from a String to an Int is a framework concern, not something implicit in the .Net type system.
1,10811222
You're talking about a C# casting operation vs .NET Conversion utilities
C# Language-level
uses parenthesis - e.g. (int) - and conversion support for it is limited, relying on implicit compatibility between the types, or explicitly defined instructions by the developer via .
Many conversion methods exist in the .NET Framework, e.g. ,
to allow conversion between same or disparate data types.
(Casting) syntax works on numeric data types, and also on "compatible" data types. Compatible means data types for which there is a relationship established through inheritance (i.e. base/derived classes) or through implementation (i.e. interfaces).
Casting can also work between disparate data types that have
The System.Convert class on the other hand is one of many available mechanisms to convert things
it contains logic to convert between disparate, known, data types that can be logically changed from one form into another.
Conversion even covers some of the same ground as casting by allowing conversion between similar data types.
Remember that the C# language has its own way of doing some things.
And the underlying .NET Framework has its own way of doing things, apart from any programming language.
(Sometimes they overlap in their intentions.)
Think of casting as a C# language-level feature that is more limited in nature, and conversion via the System.Convert class as one of many available mechanisms in the .NET framework to convert values between different kinds.
16.3k1896186
A string cannot be cast to an int through explicit casting.
It must be converted using int.Parse.
Convert.ToInt32 basically wraps this method:
public static int ToInt32(string value)
if (value == null)
return int.Parse(value, CultureInfo.CurrentCulture);
5,42311538
There is not a default cast from string to int in .NET.
You can use int.Parse() or int.TryParse() to do this.
Or, as you have done, you can use Convert.ToInt32().
However, in your example, why do a ToString() and then convert it back to an int at all?
You could simply store the int in Session and retrieve it as follows:
int i = Session["name1"];
Just a brief extra: in different circumstances (e.g. if you're converting a double, &c to an Int32) you might also want to worry about rounding when choosing between these two. Convert.Int32 will use banker's rounding (); (int) will just truncate to an integer.
3,24411436
1) C# is type safe language and doesn't allow you to assign string to number
2) second case parses
the string to new variable.
In your case if the Session is ASP.NET session than you don't have to store string there and convert it back when retrieving
int iVal = 5;
Session[Name1] = 5;
int iVal1 = (int)Session[Name1];
30.1k16108146
Convert.ToInt32
return int.Parse(value, CultureInfo.CurrentCulture);
but (int) is type cast, so (int)"2" will not work since you cannot cast string to int. but you can parse it like Convert.ToInt32 do
The difference is that the first snippet is a cast and the second is a convert.
Although, I think perhaps the compiler error is providing more confusion here because of the wording.
Perhaps it would be better if it said "Cannot cast type 'string' to 'int'.
19.9k554104
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
The week's top questions and answers
Important community announcements
Questions that need answers
By subscribing, you agree to the
Stack Overflow works best with JavaScript enabledWhy Convert.ToInt32(null) returns 0 in c# - Stack Overflow
to customize your list.
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
J it only takes a minute:
Join the Stack Overflow community to:
Ask programming questions
Answer and help your peers
Get recognized for your expertise
I just came across this today, if you convert null to int32
Convert.ToInt32(null)
it returns 0
I was expecting an InvalidCastException...
Any idea why this happen?
1,74383671
Any idea why this happen?
Because that's the documented behaviour? Whether it's
or , the documentation states quite clearly:
(Under return value)
A 32-bit signed integer that is equivalent to the number in value, or 0 (zero) if value is null.
A 32-bit signed integer equivalent to value, or zero if value is null.
As always, if reality doesn't match expectations, the first thing you should do is check whether your expectations match the documented behaviour.
Personally I don't fully buy the "compatibility with VB6" argument shown by Gavin. I realize it comes from Microsoft, and it may well be the genuine reason why it behaves that way - but I don't think it's a good reason to behave that way. There are plenty of VB-specific conversion methods - so if the framework designers genuinely thought that returning zero was a non-ideal result, they should have done whatever they thought best, and provided a VB6 compatible conversion for use by VB6 programmers.
Obviously once the behavior was defined in .NET 1.0, it couldn't be changed for later versions - but that's not the same as saying it had to behave the same way as VB6.
858k44861227186
The URL above automatically reverts to the latest Framework version, where as the text below was specifically posted on version 4. See the revised URL below which shows the text.
It explains:
All of the string-to-numeric conversion methods in the Convert class return zero if the string is null. The original motivation for this behavior was that they would provide 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.
Traditionally, the .NET Framework has tried to maintain a high degree of compatibility from version to version. Effectively, this means that, absent an extremely compelling reason, once a method has been implemented in a particular way and that implementation is publicly exposed (as in a method returning 0 if the string parameter is null), it cannot be changed, since that would break code that depends on the established behavior. This makes both of your proposed solutions very problemmatic. In the first case, throwing an exception changes the implementation of a method for customers who are likely to depend on the method returning zero for a null string. In the second case, it is important to remember that the .NET Framework does not consider return type in overload resolution. This means that your method would have to replace the existing Convert.ToInt32(String value) method, and that all code that does not expect to handle a nullable type would now be broken.
This concern for compatibility is even stronger in the case of the string-to-numeric conversion methods in the Convert class, since Parse is the recommended method for performing string-to-numeric conversion for each of the primitive numeric types supported by the .NET Framework, and each Parse method behaves differently that its corresponding Convert method. Unlike the string-to-numeric conversion method in the Convert class, which return zero if the string to be converted is null, each Parse method throws an ArgumentNullException, which is the behavior that you are arguing for. The overloads of the numeric Parse methods, such as Int32.Parse and Double.Parse, also have the advantage of allowing much finer-grained control over the parsing operation.
3,39021423
Because that's
that it will return.
Perhaps you were thinking of (int)null, which would be an NullReferenceException (not InvalidCastException; I'm not sure why).
36.7k24380
Because the default value of an Int32 is zero. Int32's cannot be null as they are value types, not reference types, so you get the default value instead.
10.3k1891175
Because this is how the method is written in the Convert class . If the parameter value is null it is simply returning 0.
public static int ToInt32(object value)
if (value == null)
return ((IConvertible)value).ToInt32(null);
78.6k68233357
For you to have an InvalidCastException you have to make a non-controlled cast.
For example:
int i = (int)
If you execute it the exception should be raised.
The use of
Convert.ToInt32(var)
Is useful when you distrust the value in var, as when reading from a database.
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabled您所在的位置: &
C# Convert.ToInt32简介
C# Convert.ToInt32简介
这里介绍,(int)和C# Convert.ToInt32是两个不同的概念,前者是类型转换,而后者则是内容转换,它们并不总是等效的。
比如说有一个string型的3,要给它转换成int型的是用(int)3,还是用C# Convert.ToInt32(3);还是两个都可以用,为什么?
解答:这两个都是转换成整型的,只是它们的长度不同。int为16位的,而下面的那个是32位的
首先,我要指出的是,在C#中,int其实就是System.Int32,即都是32位的。
其次,(int)和C# Convert.ToInt32是两个不同的概念,前者是类型转换,而后者则是内容转换,它们并不总是等效的。我们很清楚C#提供类型检查,你不能把一个string强制转换成int,隐式转换就更加不可能,例如如下的代码就行不通了:string&text&=&"1412"; &int&id&=&(int)&&
因为string和int是两个完全不同并且互不兼容的类型。说到这里,你可能会问什么才算是兼容的呢?其实,能够使用(int)进行强类型转换的只能是数值类型了,例如long、short、double等,不过进行这种转换时你需要考虑精度问题。
然而,我们很清楚上面的代码中text实际上储存的是一个数值,我们希望把这个数值提取出来并以int的形式储存起来以便日后的运算使用,那么你就需要进行内容转换了。内容转换也叫内容解释,我们把上面的代码稍稍修改就可以达到目的了:string&text&=&"1412"; &int&id&=&Convert.ToInt32(text);&&
除此之外,你还可以使用Int32.Parse和Int32.TryParse来进行解释。
另外,你发现C# Convert.ToInt32有很多重载版本,例如C# Convert.ToInt32(doublevalue);,当我们用这个版本来把一个double转换成int时,ToInt32会检查被转换的数值是否能够用int表示,即是否会发生“越界”,如果是就会抛出OverflowException,否则就会为你转换,但使用(int)进行强制转换,如果被转换的数值大于Int32.MaxValue,那么你将得到一个错误的结果,例如下面的代码:double&d&=&Int32.MaxValue&+&0.1412; &int&i&=&(int)d;&&
不过无论你进行什么数值转换,精度问题都是必须考虑的。
【编辑推荐】
【责任编辑: TEL:(010)】
关于的更多文章
AngularJS是很多Web开发人员在打造单页面应用程序时的首选创建方
所以姑娘,让我们做一枚花见花开的程序媛。
讲师: 35人学习过讲师: 17人学习过讲师: 253人学习过
Jquery是继prototype之后又一个优秀的Javascript框架
又到周末了。昨天是感恩节,小编也是听同事说起,才想
离年末越来越近了,不知道各位有没有倦怠的感觉?本周
本书是在第1版的基础上全面更新、改版而成的,仍然是目前图书市场中唯一一本全面介绍硬件服务器的IT图书。本书针对近两年来所出
51CTO旗下网站sql语句int BookID = Convert.ToInt32(((Label)e.Item.FindControl(&Label4&)).Text);什么意思_百度知道
sql语句int BookID = Convert.ToInt32(((Label)e.Item.FindControl(&Label4&)).Text);什么意思
FindControl(&quot.ToInt32(((Label)e.Item.Text);Label4&quot,具体解释一下特别是后面的部分;));这个语句是什么意思,详细解释一下int BookID = Convert
我有更好的答案
语句的意思:在当前方法(比如gridview)中查找ID为:Label4的控件的Text文本,转换为整型
其他类似问题
为您推荐:
sql语句的相关知识
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁

我要回帖

更多关于 sql server convert 的文章

 

随机推荐