getting a use of unassigned variable error

◇◆丶佛笑我妖孽 提交于 2021-02-05 11:52:31

问题


i am making a program to add a list numbers separated by a comma ( , ) in a text box. example: 1,12,5,23 in my total += num; i keep getting a use of unassigned local variable with total;

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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string str = textBox1.Text;
        char[] delim = { ',' };
        int total;
        int num;
        string[] tokens = str.Split(delim);

        foreach (string s in tokens)
        {

           num = Convert.ToInt32(s);
           total += num;

        }
        totallabel.Text = total.ToString();


    }
   }
 }

回答1:


You need to change

int total;

to

int total = 0;

The reason for this is, if you were to look closer at

total += num;

It can also be written as

total = total + num;

In which total would be unassigned for the first usage.




回答2:


You don't assign an initial value to total, maybe you need:

int total = 0;



回答3:


The other answers are right, but I'll offer an alternative FWIW that doesn't require initializing the variable since it's only assigned to once. :)

var total = textBox1.Text
    .Split(',')
    .Select(n => Convert.ToInt32(n))
    .Sum();


来源:https://stackoverflow.com/questions/11681266/getting-a-use-of-unassigned-variable-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!