user1189352
user1189352

Reputation: 3885

Passing a variable as a parameter to a class and changing that value of that variable in method within that class

forgive me if there's any typos i wrote this by hand.. i was just wondering if there's anyway i can pass a parameter to a class and change it's variable within a method of that variable.

i was thinking of passing by reference but i can't pass the variable through the Elapsed method property.. any suggestions?

public partial class MainWindow : Window
{
  private CustomTimerClass _customTimer;
  private int _varIWantToChange;

  public MainWindow()
  {
     _varIWantToChange = 1;
     _customTimer = new CustomTimerClass(_varIWantToChange);
  }
  ...
}

public CustomTimerClass()
{
  private System.Timers.Timer _timer;

  public CustomTimerClass(int varIWantToChange)
  {
    _timer = new Timer();
    ...
    _timer.Elapsed += _timer_Elapsed;  //i can't pass varIwantToChange as a parameter here
  }

  public void _timer_Elapsed(object sender, ElapsedEventArgs e)
  {
    //i want to be able to change the value of the variable "_varIWantToChange" here
  }
}

Upvotes: 1

Views: 89

Answers (3)

Xavier Leclercq
Xavier Leclercq

Reputation: 323

Any reason you are not using System.Threading.Timer instead of System.Timers.Timer? The Threading version has constructors that allow you to pass an object in the constructor that is then passed to the handler as an argument.

From MSDN: http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx

Upvotes: 1

LVBen
LVBen

Reputation: 2061

You could easily pass in a callback method:

   class Program
   {
      static private CustomTimerClass _customTimer;
      static private int _varIWantToChange = 1;
      static public void Main()
      {
         _customTimer = new CustomTimerClass(changeVar);
         while (_varIWantToChange == 1)
         {
            System.Threading.Thread.Sleep(1);
         }
      }

      static public void changeVar(object sender, ElapsedEventArgs e)
      {
         _varIWantToChange++;
         Console.WriteLine(_varIWantToChange);
      }
   }

   public class CustomTimerClass
   {
      private System.Timers.Timer _timer;
      public CustomTimerClass()
      {
      }

      public CustomTimerClass(ElapsedEventHandler callbackMethod)
      {
         _timer = new Timer();
         _timer.Elapsed += callbackMethod;  //i can't pass varIwantToChange as a parameter here
         _timer.Elapsed += _timer_Elapsed;
         _timer.Interval = 500;
         _timer.Start();
      }

      public void _timer_Elapsed(object sender, ElapsedEventArgs e)
      {
         // Do timer stuff
      }
   }

Upvotes: 2

Mike
Mike

Reputation: 807

create a public int property

make your property set _varIWantToChange and get _varIWantToChange if you need it

Upvotes: 1

Related Questions