Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Guys

I hope I will be able to explain this problem. I have two classes class1 and class2

Pet and pet owner.

public class Petowner
    {
        private String Name;
        private int age;

        public Petowner()
        {
            Name = "Joppe";
            age = 100;

        }
    }

and
class Pet

    {
        private string name;
        private int hunger;

        public Pet()
        {
            name = "Pelle";
            hunger = 100;
        }

        public void SetHunger(int _hunger)
        {
            hunger = hunger - _hunger;
        }
    }


What I have tried:

I want to have one instance of each class

then while i run the program (doing stuff with the instanses pet and petowner). then I want to make the hunger field to degrease automaticly while the program is runing. Is this possible?

Thanks

Johan
Posted
Updated 14-Jun-17 22:51pm
v2

Hello, yes, there is a way, using timers.

There are several timer classes in C#, best to look on all of them and choose the one that suits your needs!
All about .NET Timers - A Comparison[^]

Update:
C#
private static Pet vov;

static void Main(string[] args)
{
    vov = new Pet();
    var myTimer = new System.Timers.Timer();
    myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
    myTimer.Interval = 1000;
    myTimer.Start();

    while (Console.Read() != 'q')
    {

    }
    Console.ReadKey();
}

public static void DisplayTimeEvent(object source, ElapsedEventArgs e)
{
    vov.SetHunger(10);
    Console.Write("\r{0}", DateTime.Now);
}
 
Share this answer
 
v2
Comments
Member 13189777 15-Jun-17 3:48am    
But I have no idea how to do it... im a newbie and I have been trying to do what you say before and I dont get how to make the thread metod to update the pet instance.
jimmson 15-Jun-17 3:56am    
You can store the pet instance in some private field. Then access it from the thread callback method and call SetHunger. Show me the code what have you tried, so I can help you with it.
Member 13189777 15-Jun-17 4:00am    
static void Main(string[] args)
        {
            pet Vov = new pet();
            Timer myTimer = new Timer();
                  myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
                myTimer.Interval = 1000;
                 myTimer.Start();
          
      while (Console.Read() != 'q')
                   {
               
            }
        }
        public static void DisplayTimeEvent(object source, ElapsedEventArgs e)
    {
      Console.Write("\r{0}", DateTime.Now);
            
    }


This is the code i done but I dont know how to do at all... Im stucked..
jimmson 15-Jun-17 4:19am    
I've updated my answer with code.
Member 13189777 15-Jun-17 4:29am    
thanks but I cant "see vov in the DisplayTimeEvent metod?
I get this error...

i didnt see
private static Pet vov;
but when I add it I get
CS0246 C# The type or namespace name could not be found (are you missing a using directive or an assembly reference?)
Further to Solution 1 you might want to maintain a list of pets rather than working on just one

public class Pet
{
    public string Name { get; set; }
    public int Hunger { get; private set; }
    public bool IsAlive { get; private set; }

    public Pet(string name)
    {
        Name = name;
        Hunger = 100;
        IsAlive = true;
    }

    public void SetHunger(int _hunger)
    {
        Hunger = Hunger - _hunger;

        if (Hunger <= 0)
        {
            IsAlive = false;
        }
    }
}


private static List<Pet> pets = new List<Pet>();

static void Main(string[] args)
{
    var myTimer = new System.Timers.Timer();
    myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
    myTimer.Interval = 2000;
    myTimer.Start();

    string line;

    // Type a pet name followed by [RETURN] to create a pet of that name
    while ((line = Console.ReadLine()) != "q")
    {
        Pet pet = CreatePet(line);
        // you can do something with pet here if you want
    }
}

public static Pet CreatePet(string name)
{
    Pet pet = new Pet (name);

    pets.Add(pet);

    return pet;
}

public static void DisplayTimeEvent(object source, ElapsedEventArgs e)
{
    foreach (Pet pet in pets)
    {
        pet.SetHunger(10);

        if (pet.IsAlive)
        {
            Console.WriteLine("Pet:{0} Hunger:{1}", pet.Name, pet.Hunger);
        }
        else
        {
            Console.WriteLine("{0} died", pet.Name);
        }
    }

    pets.RemoveAll(p => p.IsAlive == false);
}
 
Share this answer
 
Comments
Member 13189777 15-Jun-17 5:11am    
Its perfect exactly how I wanted it. The only thing is I get this error Severity Code Description Project File Line Suppression State
Error CS0123 No overload for 'DisplayTimeEvent' matches delegate 'ElapsedEventHandler'

on this row --> new ElapsedEventHandler(DisplayTimeEvent);
eg looking like this
myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
F-ES Sitecore 15-Jun-17 5:28am    
That code works ok for the .net version I am using (4.5) you might need to consult the docs for your version and adjust as necessary, or try just

myTimer.Elapsed += DisplayTimeEvent;

or type

myTimer.Elapsed +=

in visual studio and press TAB and it'll create the correct method signature for you
Member 13189777 15-Jun-17 7:31am    
Hmmmm.,... when i press TAB it makes this signature...
private static void MyTimer_Elapsed1(object sender, ElapsedEventArgs e)
i put this

{
foreach (Pet pet in pets)
{
pet.SetHunger(10);

if (pet.IsAlive)
{
Console.WriteLine("Pet:{0} Hunger:{1}", pet.Name, pet.Hunger);
}
else
{
Console.WriteLine("{0} died", pet.Name);
}
}

pets.RemoveAll(p => p.IsAlive == false);
}

It doesnt work :(
F-ES Sitecore 15-Jun-17 7:34am    
Update your original question to list all of the code you are currently using.
Member 13189777 15-Jun-17 7:36am    
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApptimertest2
{
class Pet
{

public string Name { get; set; }
public int Hunger { get; private set; }
public bool IsAlive { get; private set; }

public Pet(string name)
{
Name = name;
Hunger = 100;
IsAlive = true;
}

public void SetHunger(int _hunger)
{
Hunger = Hunger - _hunger;

if (Hunger <= 0)
{
IsAlive = false;
}
}
}
}




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;

namespace ConsoleApptimertest2
{
class Program
{
private static List<pet> pets = new List<pet>();
static void Main(string[] args)
{
var myTimer = new System.Timers.Timer();
myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
myTimer.Interval = 2000;
myTimer.Start();

string line;

// Type a pet name followed by [RETURN] to create a pet of that name
while ((line = Console.ReadLine()) != "q")
{
Pet pet = CreatePet(line);
// you can do something with pet here if you want
}
}

private static void MyTimer_Elapsed1(object sender, ElapsedEventArgs e)
{
foreach (Pet pet in pets)
{
pet.SetHunger(10);

if (pet.IsAlive)
{
Console.WriteLine("Pet:{0} Hunger:{1}", pet.Name, pet.Hunger);
}
else
{
Console.WriteLine("{0} died", pet.Name);
}
}

pets.RemoveAll(p => p.IsAlive == false);
}



public static Pet CreatePet(string name)
{
Pet pet = new Pet(name);

pets.Add(pet);

return pet;
}

public static void DisplayTimeEvent(object source, ElapsedEventHandler e)
{

Console.WriteLine("hej");
Console.ReadLine();
foreach (Pet pet in pets)
{
pet.SetHunger(10);

if (pet.IsAlive)
{
Console.WriteLine("Pet:{0} Hunger:{1}", pet.Name, pet.Hunger);
}
else
{
Console.WriteLine("{0} died", pet.Name);
}
}

pets.RemoveAll(p => p.IsAlive == false);
}
}
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900