Creating a person life-cycle with C# events

I’ve made a basic simulation. It’s not overly complex, but I think it’s a pretty good use of the C# events. In my tiny simulation people are born, taxed, and die. It’s a bit of a morbid outlook on life, but then I suppose these aren’t real people so they can’t have any greater purpose or profound insight so I can dispose of them with a relatively easy mind.

I’m particularly proud of this because in my admittedly basic system everything basically handles itself. Each person class its own life-cycle which runs on its own background thread.

public Person(int PassedTaxes)
     Taxes = PassedTaxes;
     t = new Thread(LifeCycle);

public void LifeCycle()
     PersonBorn(this, new EventArgs());
     PersonTaxed(this, new EventArgs());
     PersonDied(this, new EventArgs());

This means that when it comes time to managing each of these people in my main program they can all be added or removed from the big list of people whenever the ‘PersonDied’ event had been triggered.

This is an admittedly simple example of using events, but since the person life-cycle is now essentially self contained, I can spend a lot more time fiddling with the more fun aspects of the program. For example, now that everything runs on its own clock and I don’t have to implement constant checks I can continually alter the the rate at which people are produced since I’m soundly assured that individual life-cycles are accounted for. I could probably implement variable lifespans too.

One of the best bits is that I can now add new functionality to every ‘person’ in my simulation by just adding new events to that life-cycle. For example, I’ve just implemented a 50/50 chance that my person will divorce somewhere between taxation and death (not the happiest 15 second life I know, maybe I’ll throw in a birthday party event if I start feeling altruistic).SimpleSimulationInterface

My simple simulator’s interface

As I say, hardly the most complex bits of software out there, but using my own life-cycle is probably something I’m going to do a good deal more of in future projects.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s