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();
}
}
}
You need to change
to
The reason for this is, if you were to look closer at
It can also be written as
In which total would be unassigned for the first usage.