tags:

views:

169

answers:

2

I know this is probably simple, but I can't seem to figure out if it's possible to do this.

I have the following code:

public class A {    
thisMethod();  

 public class B {    
  someMethod();    
   }   
}


public class C {    
A myA = new A();    
A.B.someMethod();    
}

Why can't I access B if I've already instantiated A?

THanks for your help in advance!

A: 

You're trying to access it like it was a static method or a property of class A called "B". You still need to create an instance of it - it is a class declaration. I think you're looking for :

public class A {    

public A()
{
   myB = new B();
}

thisMethod();  
public B myB
{
 get; set;
}

 public class B {    
  someMethod();    
   }   
}


public class C {    
A myA = new A();    
A.myB.someMethod();    
}

Just to note though, it's not recommended to expose nested classes publicly.

womp
+5  A: 

You need an instance of A.B to call an instance method on A.B:

A.B foo = new A.B();
foo.SomeMethod();

In your example you weren't even trying to use the new instance you'd created.

If you come from a Java background, it may be worth pointing out that nested classes in C# are like static nested classes in Java. There's no implicit reference from an instance of the nested class to an instance of the container class. (The access is also the other way round - in Java an outer class has access to its nested class's private members; in C# the nested class has access to its outer class's private members.)

Jon Skeet
I guess the reason why I did it that way was just for logical grouping. So I'd have Player.Controls and Player.Library instead of all the methods in a huge class.
WedTM
But why nest them? Why not have completely separate classes to start with, just in a "Player" namespace?
Jon Skeet