Hi! I know this is going to be a basic question for you but I'm trying to create a code where a class called "Program2" would pass value to a class called "Holder" and Holder suppose to accumulate the value that was being transferred by Program2. And Once I retrieve the value from Holder, the value should be added by 1. I hope this makes sense. To better understand my goals for this code, I will include the current output and the desired output. I have also included the actual code for Program2 and Holder below. Take note, i'm really a beginner in coding so please bare with my explanation and coding terminologies.
My output right now is like this:
**********First Loop**********
Total loop: 3
This is the output produced from Holder Class: 3
Total loop passed 1st time: 4
**********Second Loop**********
This is the output produced from Holder Class: 3
Total loop passed 1st time: 4
What i want to happen is for the output to be like this:
**********First Loop**********
Total loop: 3
This is the output produced from Holder Class: 3
Total loop passed 1st time: 4
**********Second Loop**********
This is the output produced from Holder Class: 6
Total loop passed 1st time: 7
As you can see from my desired output, i want the Second Loop to add/accumulate the number of loops that the foreach loop produces. And hopefully it will just keep on stacking up the value as it goes on the Third or Fourth Loop.
What I have tried:
Below is the code for Program2:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestCode
{
class Program2
{
private static int x = 0;
static void Main()
{
int[] array = new int[] { 1,2,3};
foreach (int element in array)
{
x++;
}
Console.WriteLine("**********First Loop**********");
Console.WriteLine("Total loop: {0}", x);
Holder h1 = new Holder();
h1.setValue(x);
h1.display();
Console.WriteLine("Total loop passed 1st time: {0}",h1.getValue());
SecondLoop();
Console.ReadKey();
}
public static void SecondLoop()
{
Console.WriteLine();
Console.WriteLine("**********Second Loop**********");
Holder h1 = new Holder();
h1.setValue(x);
h1.display();
Console.WriteLine("Total loop passed 2nd time: {0}", h1.getValue());
}
}
}
Here is code for Holder:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestCode
{
public class Holder
{
private int x = 0;
public Holder()
{
}
public void setValue(int x1)
{
x = x1;
}
public int getValue()
{
return x+1;
}
public void display()
{
Console.WriteLine("This is the output produced from Holder Class: {0}",x);
}
}
}
Feel free to suggest better alternatives for this to produce the desired result that i have mentioned above. It can be a total different approach or you can basically build up the code that i have wrote.