Reputation: 167
Here the score, i am developing an application in c# I have hit a problem where I am trying to increment and integer but i seem to getting the same number back every time.
I have a class "class1" which contains the following:
public class class1
{
public int id;
public int Outid
{
get { return id; }
set { id = value; }
}
public string OutputName
{
get { return Outid.ToString("000"); }
set { this.Outid.ToString(); }
}
}
And another, which in short contains a method which cycles through a workbooks worksheets, in that method there are two lines which are relevant to my problem
class1.id++;
console.write(class1.id)
The write line is always 1, I have been playing around for a few hours now and cant see the woods for the trees. I would imagine it would have to be something to do with the properties in class1
.
Upvotes: 0
Views: 214
Reputation: 7105
I would rather suggest that you have something like
public class Class1
{
public int id { get; set; }
}
then you can call it like
var c = new Class1();
for(var i = 0; i < 10; i++)
{
c.id += 1;
}
Console.Writeline(c.id.ToString());
Upvotes: 0
Reputation: 2441
If you write class1
you say that you want to indicate a static field/property/method. You must create an instance of your class.
Upvotes: 0
Reputation: 149020
The value will always be 1 if you're re-instantiating the class every time, for example:
for(var i = 0; i < 10; i++)
{
Class1 class1 = new Class1();
class1.id++;
Console.WriteLine(class1.id);
}
This will output 1, ten times to the console, because on each iteration you're creating a new Class1
whose id
field always starts out at the default value, 0.
However, if you instantiate it once, and then reuse the class, the id
field will be updated as you expect:
Class1 class1 = new Class1();
for(var i = 0; i < 10; i++)
{
class1.id++;
Console.WriteLine(class1.id);
}
This will output the numbers 1 through 10 to the console. And of course, the same thing works if you use the property rather than the field:
Class1 class1 = new Class1();
for(var i = 0; i < 10; i++)
{
class1.Outid++;
Console.WriteLine(class1.Outid);
}
Upvotes: 3