-4

Possible Duplicate:
Why Would I Ever Need to Use C# Nested Classes

I'm doing it shorty, I have a class which looks like this:

namespace Blub { public class ClassTest { public void teest() { return "test"; } public class AnotherTest { public void blub() { return "test"; } } } } 

I can access to the function called "teest" like this, but how can I access to the function "blub" without doing another "new ClassTest.AnotherTest()"?

Accessing to the function teest:

Blub.ClassTest = new Blub.ClassTest(); ClassTest.teest(); //test will be returned 

My try (and how I want it to, to access on AnotherTest is this:

Blub.ClassTest = new Blub.ClassTest(); ClassTest.blub(); //test will be returned 

Which don't work, I can just access to AnotherTest like this, how I dont want it:

Blub.ClassTest2 = new Blub.ClassTest.AnotherTest(); ClassTest.blub(); //test will be returned 

Does someone know a solutions for this?

1
  • 2
    A related question is the following, which should help in understanding the benefit of nested classes: stackoverflow.com/questions/1083032/… Effectively, by nesting a class, you are making a design decision about when you are going to be constructing that class and who has access to it. Commented Aug 16, 2012 at 17:41

2 Answers 2

2

You're declaring AnotherTest inside ClassTest, that's why you have to browse for it using namespace.class.2ndClass.

However, I suppose that you're not much aware of OO concepts, are you? If you declare a method inside a class, it will only be available for objects of that class, unless you declare it as static, what means that it would be a class method rather than a instance method.

If you want ClassTest to have 2 methods (teest and blub) simply declare both at the body of the class, like:

public class ClassTest { public string teest() { return "test"; } public string blub() { return "test"; } } 

Also, note that if a method is declared as void it won't return anything (in fact, I think that your original code wouldn't even compile at all).

I'd recommend you to study OO a little deeper before trying to figure things out at your own.

Sign up to request clarification or add additional context in comments.

Comments

0

If you need access to another class you have to make it a property in the first class.

namespace Blub { public class AnotherTest { public void blub() { return "test"; } } public class ClassTest { public AnotherTest at = new AnotherTest(); public void teest() { return "test"; } } } 

Then access it like this:

 ClassTest x = new ClassTest(); x.at.blub(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.