Code:namespace ScratchDetection
{
class ImageProcessing
{
public class hough
{
}
}
}
Can I have a class within a class?
If so how do I access the methods?
Printable View
Code:namespace ScratchDetection
{
class ImageProcessing
{
public class hough
{
}
}
}
Can I have a class within a class?
If so how do I access the methods?
Oh yes. And a class in a class can access the 'parent' classes private members making it rather useful.Quote:
Can I have a class within a class?
Like this :Quote:
If so how do I access the methods?
Get it ?Code: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);
Darwen.
@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.
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.
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?
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.Quote:
Originally Posted by JustSomeGuy
Yup, nested classes are instantiated the exact same way as all the others. For instance:
You can instantiated NestedClass1 this way:Code:public class Class1
{
public class NestedClass1
{
}
}
Or, if you're inside Class1, you can instantiate it this way:Code:Class1.NestedClass1 c = new Class1.NestedClass1()
Code:NestedClass1 c = new NestedClass1();