WedTM
WedTM

Reputation: 2647

Simple C# Question: Nesting Classes, Accessibility

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!

Upvotes: 1

Views: 428

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500625

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.)

Upvotes: 5

womp
womp

Reputation: 116977

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.

Upvotes: 0

Related Questions