Andrew
Andrew

Reputation: 3663

Making a variable accessible to any object

Lets say I have a loop that runs through a list of objects,

foreach( object pawn in objectList )
{
   pawn.update();
}

This runs all the update codes, right? Simple because you don't have to pass any information into the update function to make all the objects run.

How can you access this array of objects in one of the objects that are apart of the list? Or any object for that matter? Kind of like how you can always get members from the Console.

For example, I can retrieve a value like Console.BackgroundColor in any object. How can I do this with the objects list?

this.value = Console.BackgroundColor // You can access it directly from the class.

Upvotes: 0

Views: 95

Answers (2)

Keith Nicholas
Keith Nicholas

Reputation: 44288

static public members of classes can be accessed

eg

public static class Blah 
{
   public static List<MyObject> Stuff = new List<MyObject>();
}

can be accessed from anywhere with Blah.Stuff;

HOWEVER.

This is generally a bad idea. Most often if you adjust your design a bit, you don't need global access like this. Its most useful for TRULY global resources.

For your situation you might want something like

   foreach( IChild pawn in objectList )
    {
       pawn.Parent = objectList;
       pawn.update();
    }

where

public interface IChild
{
   void update();
   List<IChild> Parent { get; set; }
}

Upvotes: 1

TGH
TGH

Reputation: 39248

This deals with instance vs static methods. Console.BackgroundColor is a static property, so it's available everywhere. Your loop calls instance methods, so it can only call methods on instances it has a direct reference to.

I recommend that you read some more about static vs instance methods.

http://cplus.about.com/od/howtodothingsinc/a/An-Overview-Of-Static-and-Instance-In-C.htm

Upvotes: 3

Related Questions