0

Situation:

ClassA
{
     static string c;
}

 ClassB
 {
     public List<ClassA> Collection;
}

....

ClassB b;

How can I get access to a static member of ClassA having object b of ClassB? Here it is string c.

3
  • 3
    Why not just ClassA.c? Commented Nov 12, 2014 at 12:29
  • Static members don't belong to an instance but to the class. Read: "Members of a class are either static members or instance members. Generally speaking, it is useful to think of static members as belonging to classes and instance members as belonging to objects (instances of classes)." Commented Nov 12, 2014 at 12:30
  • Simple answer .. you can't since it's a static member. Commented Nov 12, 2014 at 12:36

1 Answer 1

1

You can't get static members from a class instance (so you can't do b.Collection[0].c).

You do have the ability to use reflection to get the type member, but that wouldn't be the best option in my opinion.

I think you'd better create a non-static accessor for the static member:

public string C
{
    get
    {
        return c;
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Why would you want to do that at all? The static member does not belong to the instance, c is the same for all instances of ClassA in Collection.
Well, some times you have something that is static, since you want to share it across instances, but you also want to access it from an instance that is passed around.
But you can access it via class, you don't need the instance (and you can't use it from an instance anyway).
@TimSchmelter: Sorry, I think I understand you better now. c belongs to ClassA instead of ClassB, you are right.
Yes correct but that's not the suggested way to access a static member. Why would someone at all want to access a static member from a instance variable???
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.