|
-
April 16th, 2008, 01:22 PM
#1
class in a class?
Code:
namespace ScratchDetection
{
class ImageProcessing
{
public class hough
{
}
}
}
Can I have a class within a class?
If so how do I access the methods?
-
April 16th, 2008, 03:26 PM
#2
Re: class in a class?
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 :
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);
Get it ?
Darwen.
-
April 16th, 2008, 03:29 PM
#3
Re: class in a class?
@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.
-
April 16th, 2008, 06:01 PM
#4
Re: class in a class?
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.
-
April 16th, 2008, 06:36 PM
#5
Re: class in a class?
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?
Last edited by JustSomeGuy; April 16th, 2008 at 08:27 PM.
-
April 17th, 2008, 12:56 AM
#6
Re: class in a class?
 Originally Posted by JustSomeGuy
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.
- Make it run.
- Make it right.
- Make it fast.
Don't hesitate to rate my post. 
-
April 17th, 2008, 07:24 AM
#7
Re: class in a class?
Yup, nested classes are instantiated the exact same way as all the others. For instance:
Code:
public class Class1
{
public class NestedClass1
{
}
}
You can instantiated NestedClass1 this way:
Code:
Class1.NestedClass1 c = new Class1.NestedClass1()
Or, if you're inside Class1, you can instantiate it this way:
Code:
NestedClass1 c = new NestedClass1();
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|