Well, I'm trying to create a app using Visual Studio 8. I'm new in the c# language...
The problem is that when I add items to a List of objects, and in the end when a do a foreach to see if everything is fine, the result is allways the same... Can anyone help me finding the "bug"?
Here is some code:
/**********************************/
List<Option> options = new List<Option>();
number=1;
do
{
Option option = new Option(number);
options.Add(option);
number++;
} while (number != 5);
foreach (Option o in options)
{
result += "\n" + o.number;
}
MessageBox.Show(result);
Well, I'm trying to create a app using Visual Studio 8. I'm new in the c# language...
The problem is that when I add items to a List of objects, and in the end when a do a foreach to see if everything is fine, the result is allways the same... Can anyone help me finding the "bug"?
Here is some code:
/**********************************/
List<Option> options = new List<Option>();
number=1;
do
{
Option option = new Option(number);
options.Add(option);
number++;
} while (number != 5);
foreach (Option o in options)
{
result += "\n" + o.number;
}
MessageBox.Show(result);
/*****************************/
This results in a MessageBox with:
4
4
4
4
the code si working except defining variable and classes.
Code:
struct Option
{
public int number;
public Option(int num)
{
number = num;
}
};
private void button1_Click(object sender, EventArgs e)
{
List<Option> options = new List<Option>();
string result = string.Empty;
int number = 1;
do
{
Option option = new Option(number);
options.Add(option);
number++;
} while (number != 5);
foreach (Option o in options)
{
result += "\n" + o.number;
}
MessageBox.Show(result);
}
i am receiving the message box with following content.
1
2
3
4
Last edited by ashukasama; July 1st, 2009 at 09:37 PM.
Reason: changed class to struct
Actually, this is list of objects, defined by the class :
/***********/
class Option
{
public int number;
public Option(int Num)
{
this.number= Num;
}
/*************/
List<Option> options = new List<Option>();
number=1;
do
{
Option option = new Option(number);
options.Add(option);
number++;
} while (number != 5);
foreach (Option o in options)
{
result += "\n" + int.Parse(o.number);
}
MessageBox.Show(result);
/***********************/
if you use int.Parse you will notice following error.
Error 1 The best overloaded method match for 'int.Parse(string)' has some invalid arguments
Error 2 Argument '1': cannot convert from 'int' to 'string'
if you change o.number to string then there will be lot of changes in code.... so please be sure before posting that your code is working...
I really don't understand... In my original app this code does not work...
But when a do a test using a new project, works just fine... with no errors and warnings.
I suppose the problem is somewhere else...
Has i have already said, I’m a newbie in c#. And in Lists also.
Bookmarks