Reputation: 21
I have a class Foo in C# that has a string name and I want each one to have a unique name. What I wanted to do is get the name from creating a static int variable and then assigning it to a local instance int variable to which I add to the end of the string. This does not work though, how would I be able to get my desired result.
class Foo
{
static int count = 0;
int fooNum;
string name;
public Foo
{
++count;
fooNum = count;
name = "Foo" + fooNum;
Console.WriteLine(name);
}
}
int main()
{
for(int i = 0; i < 5; i++)
{
Foo test = new Foo();
}
}
Actual Output: Foo5 Foo5 Foo5 Foo5 Foo5
Desired Output: Foo0 Foo1 Foo2 Foo3 Foo4
Any help would be greatly appreciated
Thanks
Upvotes: 0
Views: 206
Reputation: 300529
This code works as expected:
namespace ConsoleApplication68
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Foo test = new Foo();
Console.WriteLine(test.name);
}
}
}
class Foo
{
private static int count = 0;
public string name;
public Foo()
{
int fooNum = ++count;
name = "Foo" + fooNum;
}
}
}
Please note that I've moved the Console.WriteLine()
to a more correct place in your code.
Upvotes: 0
Reputation: 33910
Mitch and Tudor have correct examples, but I would still point out why your code doesn't work:
Your code doesn't work because you are missing parentheses on your Foo
constructor, which causes the code to not compile. If you are ignoring this compiler error you are probably running a previous build which produces the output you are seeing. Fix the constructor and you'll see that your code will work as expected.
Upvotes: 1
Reputation: 253
Try collecting your Foos into a generic Collection, such as:
List<Foo> myFooList;
Then as you add in more Foos to your List, you can use the index number to identify it.
Upvotes: 0
Reputation: 62439
Your code doesn't compile. Correcting it to:
class Foo
{
static int count = 0;
int fooNum;
string name;
public Foo()
{
++count;
fooNum = count;
name = "Foo" + fooNum;
Console.WriteLine(name);
}
}
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Foo test = new Foo();
}
}
makes it compile and work like a charm. It prints
Foo1
Foo2
Foo3
Foo4
Foo5
Upvotes: 2