Convert.toint32 trong c# là gì

25

New! Save questions or answers and organize your favorite content.
Learn more.

intID1 = Int32.Parse(myValue.ToString());
intID2 = Convert.ToInt32(myValue);

Which one is better and why?

asked Sep 15, 2010 at 0:57

1

They are exactly the same, except that Convert.ToInt32(null) returns 0.

Convert.ToInt32 is defined as follows:

    public static int ToInt32(String value) {
        if (value == null) 
            return 0;
        return Int32.Parse(value, CultureInfo.CurrentCulture);
    }

answered Sep 15, 2010 at 0:59

SLaksSLaks

849k174 gold badges1877 silver badges1946 bronze badges

2

Well, Reflector says...

public static int ToInt32(string value)
{
    if (value == null)
    {
        return 0;
    }
    return int.Parse(value, CultureInfo.CurrentCulture);
}

public static int Parse(string s)
{
    return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}

So they're basically the same except that Convert.ToInt32() does an added null check.

answered Sep 15, 2010 at 1:03

Adam PAdam P

4,5556 gold badges30 silver badges40 bronze badges

It depends on what you mean by "better" because "better" is subjective.

For instance - code readability. Some people prefer to see "Convert" in their code; others prefer to see "Parse".

In terms of speed, they're also both roughly equal according to these benchmarks.

Or do you always wants a value returned? As others have mentioned, ConvertTo returns a 0 (zero) for null values whereas you don't get that option with Parse.

answered Dec 6, 2018 at 8:12

  • Convert.toint32 trong c# là gì
  • Diễn đàn
  • LẬP TRÌNH VISUAL C#
  • Nhập môn lập trình C#, ASP.NET
  • lệnh convert trong c#. xin giúp đỡ??

  1. lệnh convert trong c#. xin giúp đỡ??

    Các bạn cho mình hỏi về lệnh câu lệnh convert này với:

    Code:

    age = DateTime.Now.Year - Convert.ToInt32(txtyear.Text);

    khi chạy thì hiện thông báo lỗi này:

    Convert.toint32 trong c# là gì

    mong các bạn chỉ giùm cách sửa lỗi..!!
    cám ơn bạn nhiều..!!

    và đây là toàn bộ bài làm của mình:

    Code:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace baitap1tuan678
    {
        public partial class Frmbai1 : Form
        {
            public Frmbai1()
            {
                InitializeComponent();
            }
    
            private void Frmbai1_FormClosing(object sender, FormClosingEventArgs e)
            {
                DialogResult r;
                r = MessageBox.Show("do you realy want to close?", "Ex1",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question,
                    MessageBoxDefaultButton.Button1);
                if(r==DialogResult.No)
                   e.Cancel=true;             
    
    
            }
    
            private void txtyear_TextChanged(object sender, EventArgs e)
            {
                Control ctr = (Control)sender;
                if (ctr.Text.Length > 0 && !char.IsDigit(ctr.Text[ctr.Text.Length - 1]))
                    this.errorProvider1.SetError(ctr, "this is not a valid number");
                else
                    this.errorProvider1.Clear();
            }
    
            private void btnshow_Click(object sender, EventArgs e)
            {
                int age;
                string s;
                s = "my name is:" + txtyourname.Text + "\n";
                age = DateTime.Now.Year - Convert.ToInt32(txtyear.Text);
                s = s + "age:" + age.ToString();
                MessageBox.Show(s);
    
    
            }
    
            private void btnexit_Click(object sender, EventArgs e)
            {
                this.Close();
    
            }
    
            private void txtyear_Click(object sender, EventArgs e)
            {
    
    
            }
    
            private void txtyourname_Leave(object sender, EventArgs e)
            {
                Control ctr = (Control)sender;
                if(ctr.Text.Trim().Length==0)
                    this.errorProvider1.SetError(ctr,"you must enter your name");
                else 
                    this.errorProvider1.Clear();
    
            }
    
            private void btnclear_Click(object sender, EventArgs e)
            {
                txtyourname.Clear();
                txtyear.Clear();
                txtyourname.Focus();
    
            }
        }
    }

    và bạn cho mình hỏi thêm 3 câu lênh cuối bị lỗi gì:(đây là hình ảnh lỗi)

    Convert.toint32 trong c# là gì

    cảm ơn các bạn nhìu..!!

    Đã được chỉnh sửa lần cuối bởi jshkseven : 07-03-2010 lúc 02:57 AM.


  2. cái txtyear, txtyourname có phải textbox ko hay là label. Và Text của txtyear bạn gán là gì (hoặc là chuỗi rỗng).

    Men talk of killing time, while time quietly kills them.
    Time is what we want most, but what we use worst.
    ------------------------------
    YinYang's Programming Blog


  3. Có 2 cách convert từ chuỗi sang số. Cách 1 là cách của bạn: Convert.ToInt32(s);
    Cách 2 là: Int32.Parse(s)
    Mình đã test cách 2 nhanh hơn cách 1 tí xíu (2144-2071). Nhưng cách 1 hay hơn vì nó trực quan và convert sang kiểu nào cũng được. Còn cách 2 có 4 hàm thôi thì phải. Chả hiểu .NET nó cho 2 cái để làm gì


  4. Cách 2 thì tất nhiên nhanh hơn, việc cung cấp 2 cách chuyển đổi này để phù hợp với từng mục đích sử dụng. Cách convert sẽ lâu hơn vì nó phải kiểm tra dữ liệu trước khi thực hiện chuyển đổi, tùy theo kiểu cần chuyển mà giá trị trả về của nó sẽ khác các Parse hay ko, ví dụ nếu Convert.ToInt32() một đối tượng null thì sẽ trả về 0, còn nếu dùng Parse() thì sẽ bị ném ra 1 exception.
    Ngoài cách dùng Parse bạn có thể dùng TryParse() để hạn chế exception, thay vì ném ra 1 exception thì phuơng thức TryParse() sẽ trả về false.

    Men talk of killing time, while time quietly kills them.
    Time is what we want most, but what we use worst.
    ------------------------------
    YinYang's Programming Blog


  5. Convert.toint32 trong c# là gì
    Nguyên bản được gửi bởi Yin Yang
    Convert.toint32 trong c# là gì

    nếu Convert.ToInt32() một đối tượng null thì sẽ trả về 0, còn nếu dùng Parse() thì sẽ bị ném ra 1 exception.
    Ngoài cách dùng Parse bạn có thể dùng TryParse() để hạn chế exception, thay vì ném ra 1 exception thì phuơng thức TryParse() sẽ trả về false.

    hay quá, cám ơn bạn đã chia sẻ


  6. lệnh convert trong c#. xin giúp đỡ??

    Cám ơn các bạn nhiều ha. Mình đã làm được rồi.


  7. Mấy bạn cho mình hỏi Convert.ToInt32(string, 16) vậy giá trị 16 là gì vậy?


  8. Có thể tham khảo ở đây, Convert.ToInt32 Method (String, Int32):
    https://msdn.microsoft.com/en-us/library/1k20k614(v=vs.110).aspx

    I am responsible for what I say, I am not responsible for what you understand.

    Trong trại súc vật, có những con vật tự cho mình cái quyền bình đẳng hơn những con vật khác.
    Phọt đâu xa 2017

    I am responsible for what I say, I am not responsible for what you understand.

    Trong trại súc vật, có những con vật tự cho mình cái quyền bình đẳng hơn những con vật khác.


Các đề tài tương tự

  1. Trả lời: 8

    Bài viết cuối: 03-02-2011, 08:15 AM

  2. Trả lời: 4

    Bài viết cuối: 26-09-2010, 05:43 PM

  3. Trả lời: 1

    Bài viết cuối: 16-06-2010, 10:29 AM

  4. Trả lời: 1

    Bài viết cuối: 03-06-2010, 07:33 PM

  5. Trả lời: 6

    Bài viết cuối: 21-05-2010, 08:38 AM

Convert.toint32 trong c# là gì
Quyền hạn của bạn

  • Bạn không thể gửi đề tài mới
  • Bạn không thể gửi bài trả lời
  • Bạn không thể gửi các đính kèm
  • Bạn không thể chỉnh sửa bài viết của bạn
  • Tìm hiểu luật lệ tham gia diễn đàn

  • BB code: On
  • Mặt cười: On
  • [IMG] code: On
  • [VIDEO] code is On
  • HTML code: Off