How to keep the values of variables

BenTam 1,781 Reputation points
2021-10-08T04:11:56.727+00:00

Dear All,

I want to keep the values of variables in a method. The method will update the values. When the method is recalled the method will use these updated values. I find that static variables will keep their values and meet my requirement. Could any body show me an example?

TIA

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-10-09T09:42:27.717+00:00

    There is an option to use a singleton class. The following is a simple working example done in a windows form app.

    using System;  
      
    namespace SingletonExamples  
    {  
        public sealed class ApplicationJobs  
        {  
            private static readonly Lazy<ApplicationJobs> Lazy = new(()  
                => new ApplicationJobs());  
      
            public delegate void OnValueChanged(int value);  
            /// <summary>  
            /// Notify any listeners that <see cref="Value"/> has changed  
            /// </summary>  
            public static event OnValueChanged ValueChanged;  
      
            /// <summary>  
            /// Entry point  
            /// </summary>  
            public static ApplicationJobs Instance => Lazy.Value;  
      
            public int Value { get; set; }  
      
            public void Work()  
            {  
                for (int index = 0; index < 5; index++)  
                {  
                    Value += 1;  
                }  
      
                ValueChanged?.Invoke(Value);  
            }  
      
            /// <summary>  
            /// Increment <see cref="Value"/> by increaseBy  
            /// which defaults to one if no value is passed  
            /// </summary>  
            /// <param name="increaseBy"></param>  
            public void IncrementValue(int increaseBy = 1)  
            {  
                Value += increaseBy;  
                ValueChanged?.Invoke(Value);  
            }  
      
            /// <summary>  
            /// This is needed when there are many things to  
            /// reset  
            /// </summary>  
            public void Reset()  
            {  
                Value = 0;  
                ValueChanged?.Invoke(Value);  
            }  
      
            private ApplicationJobs()  
            {  
                // TODO any initialization that may be needed  
            }  
        }  
    }  
    

    Form code

    using System.Windows.Forms;  
      
    namespace SingletonExamples  
    {  
        public partial class Form1 : Form  
        {  
            public Form1()  
            {  
      
                InitializeComponent();  
      
                ApplicationJobs.ValueChanged += ApplicationSettingsOnValueChanged;  
                ApplicationJobs.Instance.IncrementValue();  
                  
            }  
      
            private void ApplicationSettingsOnValueChanged(int value)  
            {  
                textBox1.Text = ApplicationJobs.Instance.Value.ToString();  
            }  
      
            private void ExecuteButton_Click(object sender, System.EventArgs e)  
            {  
                ApplicationJobs.Instance.Work();  
            }  
      
            private void IncrementButton_Click(object sender, System.EventArgs e)  
            {  
                ApplicationJobs.Instance.IncrementValue(2);  
            }  
      
            private void ResetButton_Click(object sender, System.EventArgs e)  
            {  
                ApplicationJobs.Instance.Reset();  
            }  
        }  
    }  
      
    

    139121-figure1.png


2 additional answers

Sort by: Most helpful
  1. Timon Yang-MSFT 9,606 Reputation points
    2021-10-08T06:41:58.683+00:00

    You seem to mean to define a static field:

        class MyClass  
        {  
            static int Value;  
      
            public void DoSth ()  
            {  
                Console.WriteLine(Value);  
                Value++;  
            }  
        }  
    

    But you need to know that this field will be shared among all instances of this class.

    Static Members

    If it's just based on the needs you describe, an ordinary property is enough.

        class MyClass  
        {  
            public int Value { get; set; };  
            public void DoSth ()  
            {  
                Console.WriteLine(Value);  
                Value++;  
            }  
        }  
    

    Am I misunderstanding what you mean?

    If so, please describe your needs more clearly.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. AgaveJoe 30,126 Reputation points
    2021-10-09T13:25:55.447+00:00

    May I know how to fix it?

    The code indicates that you do not understand C# syntax or constructs. This makes providing assistance difficult.

    Below is my best guess of what you are trying to do. But the sample code requires that you understand the difference between a class instance, a static method/class, and a static member. It also assume you understand C# access modifiers.

        class Program
        {
            static void Main(string[] args)
            {
                MyClass c = new MyClass();
                Console.WriteLine("******************");
                Console.WriteLine(c.GetValue);
                Console.WriteLine("******************");
                Console.WriteLine();
    
                c.MyMethod();
                MyClass c1 = new MyClass();
    
                Console.WriteLine();
                Console.WriteLine("******************");
                Console.WriteLine(c1.GetValue);
                Console.WriteLine("******************");
    
            }
    
    
            class MyClass
            {
                static int Value;
    
                public int GetValue
                {
                    get { return Value; }
                }
                public void MyMethod()
                {
                    int i;
                    MyClass1 c1 = new MyClass1();
                    for (i=0; i<2; i++)
                    {
                        Console.WriteLine($"MyClass.Value = { Value++}");
                        c1.DoSth();
                    }
                }
            }
    
            class MyClass1
            {
                public int Value;
    
                public void DoSth()
                {
                    Console.WriteLine($"MyClass1.Value = {Value++}");
                }
            }
        }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.