Barak Yaari
Barak Yaari

Reputation: 418

How to keep track and manipulate a variable using multiple classes - c#

i am building a sort of program that generates a random list of word according to a database. I Made a class that deals with the word selecting and handling (a random select function, a connect to the database function etc..)

I have 3 variables that indicate the last 3 words chosen. how do I use a funcion on the form1 (button 1 press), to manipulate the same 3 variables, without creating them from scratch everytime (what happens now...)

To make myself clearer: accualy what I need is to know how to keep track of a variable between multiple classes.

I might be using the whole classes thing wrong... I am now triyng to get the grasp of it. Thank you very much, Barak.

Upvotes: 0

Views: 395

Answers (2)

Robert Schmidt
Robert Schmidt

Reputation: 699

I would avoid static or Singletons just for this purpose - they're not good habits to pick up for simple object oriented scenarios.

Encapsulate the state variables in a class, which you instantiate first, then pass by reference into the form and/or data fetch logic.

Key to this is understanding the concept of reference - your form and fetch logic will see the same instance of your state class, effectively sharing it.

If you implement the "variables" as properties on the state class, you can use events to notify other parts of your code when the word states change.

Consider also clearly defining the possible interactions (interfaces) on the state class. One aspect seems to be to add a word, another to pull out statistics based on the added words. The state class can accommodate all this, and provide a nice place for future extensions.

Try to think in terms of public interface methods/properties, while keeping "variables" (i.e. fields like counters or collections) private.

I also agree that your post should be improved with snippets of actual code - help us helping you.

And I hope your code is not being used to generate spam mails/posts... :-)

Upvotes: 0

Chris
Chris

Reputation: 27619

Your two options as I see it are:

1) an instance of a class that holds those variables that can be passed around

You may want to use the singleton pattern for this class if you want to make sure there is only ever one of them.

2) A static class with static members holding this information.

It may be that your entire random word class could be static. In this case you'd just call the methods and properties on that class to generate and access your words.

Also I would suggest that you may want to consider a collection to hold your words rather than three separate variables. It will of course depend on your implementation so I will mention it just inc ase you haven't thought of it and I'm not saying you definitely should. :)

Upvotes: 1

Related Questions