-1

I got an exercise from a book (there's no code correction) where I have to build a bet simulator.

I have a class Greyhound and 4 dogs from this class. I want to put them in an array of Greyhound, and initialize him at the very begininng of the code so they are in the scope of all methods of my form. Here's a piece of code, it will be clearer :

public partial class Form1 : Form
{
    Greyhound dog1 = new Greyhound();
    Greyhound dog2 = new Greyhound();
    Greyhound dog3 = new Greyhound();
    Greyhound dog4 = new Greyhound();

    Guy joe = new Guy() { name = "Joe", myBet = null, cash = 50};
    Guy bob = new Guy() { name = "Bob", myBet = null, cash = 75 };
    Guy al = new Guy() { name = "Al", myBet = null, cash = 45 };

    Greyhound[] dogs = new Greyhound[4] { dog1, dog2, dog3, dog4 }; //Here's the problem

    public Form1(){ .....

But when I try to initialize my arrays, it seems he can't find dog1, dog2 etc.

What is wrong ? Is there a simplier way to initialize these variable in order to be in the right scope for all methods ? I tried to use "public" and declare them in Form1(){} but it's not working neither...

DoT
  • 369
  • 2
  • 12
  • _"it seems he can't find"_ - don't give compiler errors your own interpretation, research them verbatim. Move the array initialization, which references other fields, into the constructor. – CodeCaster Nov 22 '17 at 15:29
  • @mituw You put his code into a method. His code is not in a method. Either way, this is a duplicate. – ProgrammingLlama Nov 22 '17 at 15:31
  • Ah, you're right @john .. I didn't notice that.. DoT... your assignment code should be in the constructor as others have already pointed out – mituw16 Nov 22 '17 at 15:32

1 Answers1

0

The place of declarations is correct. Try moving assignments to constructor.

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
  • Thanks for all the answers and sorry for duplicate. I looked a lot on Google and even here before posting thought. Ok shame time but... I know the concept of constructors but never used them before. I'll look at it :) Have a good day. – DoT Nov 22 '17 at 15:46