BlueRay101
BlueRay101

Reputation: 1487

C# - Object Declaration and Usage

I've written this in C#:

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

namespace Object
{
    class Program
    {
        int hp;
        Program mob1 = new Program();
        Program player = new Program();
        static void Main(string[] args)
        {
            Program go = new Program();
            go.next();
        }
        public void next()
        {
            mob1.hp = 50;
            player.hp = 100;
            Console.WriteLine("Player's HP: " + player.hp);
            Console.ReadKey();
        }
    }
}

When I run this program, I get a Stack Overflow exception, and the program just crashes. The Exception happens at the declaration of the first object, mon.

Why is this? And how I can fix it?

Upvotes: 0

Views: 2994

Answers (4)

dcastro
dcastro

Reputation: 68750

You're generating infinite recursion.

Think about it this way: When you start the application, you're creating an instance of the type Program. That instance, will create two other instances: mob1 and player. Those two instances, will create two more each, and so on. Eventually, the program crashes.

You should create a specific class to hold a player's state and its hp - e.g., public class Player{}.

Edit

class Program
{
    Player mob1 = new Player(); // mob1 and player are now of type Player
    Player player = new Player();

    static void Main(string[] args)
    {
        Next();
    }

    static public void Next()
    {
        mob1.Hp = 50;
        player.Hp = 100;
        Console.WriteLine("Player's HP: " + player.Hp);
        Console.ReadKey();
    }
}

public class Player
{
    public int Hp {get; set;}
}

Upvotes: 13

BigM
BigM

Reputation: 687

You have the Class Program with 2 fields of the Type Program which each of has 2 fields of the type Program

You created a infinite Loop of Variables.

Upvotes: 1

helb
helb

Reputation: 7793

Your field declarations

Program mob1 = new Program();

etc. create an instance of Program every time an instance of Program is created...

This results in recurring creation of Program objects until there is no more memory on the stack.

Upvotes: 0

walther
walther

Reputation: 13598

It's crashing because you've just created an infinite loop - recursion, but without any means of ending. Every instance of your class creates new and new objects, eventually resulting in program crash.

Upvotes: 6

Related Questions