Click to See Complete Forum and Search --> : class in a class?


JustSomeGuy
April 16th, 2008, 01:22 PM
namespace ScratchDetection
{
class ImageProcessing
{
public class hough
{
}
}
}



Can I have a class within a class?
If so how do I access the methods?

darwen
April 16th, 2008, 03:26 PM
Can I have a class within a class?


Oh yes. And a class in a class can access the 'parent' classes private members making it rather useful.


If so how do I access the methods?


Like this :


public class Outer
{
private int _value;

public Outer(int value)
{
_value = value;
}

public class Inner
{
public int GetOuterValue(Outer value)
{
// gain access to the parent classes private member variable
return value._value;
}
}
}

// example code
Outer.Inner inner = new Outer.Inner();
Outer outer = new Outer(100);
int outerValue = inner.GetOuterValue(outer);


Get it ?

Darwen.

opedog
April 16th, 2008, 03:29 PM
@zdavis - I don't see any nested classes in your example. Maybe a misplaced bracket?

@JustSomeGuy - What I'd suggest here is to just try it out. Nested classes in C# are very useful for limiting the scope of classes and avoiding unnecessary namespace clutter.

zdavis
April 16th, 2008, 06:01 PM
opedog....thank you for notice. I should pay a little more attention next time with my brackets.

@justsomeguy - sorry if I confused with my misleading example.

JustSomeGuy
April 16th, 2008, 06:36 PM
Thanks all.. Never a problem.

A question about instantiation...
If The outer class is instantiated by the user...
When does the inner class get instantiated?

boudino
April 17th, 2008, 12:56 AM
When does the inner class get instantiated?
If you call a constructor of it with the new keyword. Don't miss it with Java, there is a difference. Inner classes in C# is primary a matter of scope. They have access to private members of outer class and are accessible only via their outer class, so they share their accessibility.

opedog
April 17th, 2008, 07:24 AM
Yup, nested classes are instantiated the exact same way as all the others. For instance:

public class Class1
{
public class NestedClass1
{
}
}

You can instantiated NestedClass1 this way:

Class1.NestedClass1 c = new Class1.NestedClass1()

Or, if you're inside Class1, you can instantiate it this way:

NestedClass1 c = new NestedClass1();