Search code examples
c#xnareference-counting

C# - How to access a static class variable given only the class type?


This is my first time posting on Stack Overflow, so hopefully I did everything right and you guys can help.

I'm wondering if in C# there's a way to access a static variable belonging to a class, when given only the type of the class. For example:

public class Foo
{
    public static int bar = 0;
}

public class Main
{
    public void myFunc(Type givenType)
    {
        int tempInt = ??? // Get the value of the variable "bar" from "Foo"
        Debug.WriteLine("Bar is currently :" + tempInt);
    }
}

// I didn't run this code through a compiler, but its simple enough
// that hopefully you should get the idea...

It's hard to describe the context of needing to know this, but I'm making a game in XNA and I'm trying to use reference counting to reduce the complexity of the design. I have objects in the game and power-ups that can apply an effect them (that stays on the objects). Power-ups can die but their effects can still linger on the objects, and I need to keep track of if any effects from a power-up are still lingering on objects (thus, reference counting). I plan to make a "PowerUpEffect" class (for each type of power-up) with a static integer saving the number of objects still affected by it, but the design of the rest of the game doesn't work well with passing the PowerUpEffect all the way down to the object for it to call a method of the PowerUpEffect class.

I'm hoping to pass only the PowerUpEffect's type (using something like "typeOf()") and use that type to reference static variables belonging to those types, but I have no idea how to do it or if it's even possible.

I'd be glad to even find work-arounds that don't answer this questions directly but solve the problem in a simple and elegant design. =)

Help! (and thanks!)


Solution

  • If you only have the Type handle, you can do this:

    var prop = givenType.GetProperty("bar");
    var value = prop.GetValue(null);