473,898 Members | 3,120 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using Reflection With Nested Classes

I've almost completed building a Model-View-Controller but have run into a
snag. When an event is fired on a form control I want to automatically
updated the "connnected " property in the Model. This works fine if all of
the properties are at the top (root level) of the model but I'd like to keep
them in nested classes to organize them better.

So, for example, part of my data model looks like this (simplified) :

public class MainClass

public class NestedClass1

public bool Property1

public string Property2

public class NestedClass2
.... and so on.

Outside of the model I instantiate an object of MainClass and then inside
the contstructor of MainClass I instantiate an object of NestedClass. So,
for example, 'ObjectMain' would be an instance of MainClass and
'ObjectNested1' would be an instance of NestedClass1. That all seems to work
fine.

I'm now trying to build a method to retrieve the current value of a given
property. I pass to this method the instance of the model and the name of
the property. It first looks in the root of MainClass to see if the property
is there. If it isn't then it starts cycling through the various nested
classes to see if it's in one of them. Once it finds the correct nested
class then it retrieves the value of the property.

But here's the dilemma: I can explicitly specify the name of the nested
class to retrieve the property value, such as:

property.GetVal ue(ObjectMain.O bjectNested1, null)

That works great! But I'd much prefer to keep things more generic so that
this method would be completely resuable in the future. Yet I cannot figure
out how to use Reflection (or something else) to get the equivalent of
'ObjectMain.Obj ectNested1'

I realize this is a complicated issue but I hope I've explained it
succinctly and hope even more that someone has a solution!

Robert Werner
Vancouver, BC
Nov 17 '05 #1
8 16945
public static void Main()
{
Type type = typeof(System.E nvironment);

foreach (Type nested in type.GetNestedT ypes())
Console.WriteLi ne(nested.FullN ame);

// Outputs the following:
/*
System.Environm ent+SpecialFold er
Press any key to continue
*/
}

--
Dave Sexton
dave@www..jwaon line..com
-----------------------------------------------------------------------
"Robert W." <Ro*****@discus sions.microsoft .com> wrote in message news:1B******** *************** ***********@mic rosoft.com...
I've almost completed building a Model-View-Controller but have run into a
snag. When an event is fired on a form control I want to automatically
updated the "connnected " property in the Model. This works fine if all of
the properties are at the top (root level) of the model but I'd like to keep
them in nested classes to organize them better.

So, for example, part of my data model looks like this (simplified) :

public class MainClass

public class NestedClass1

public bool Property1

public string Property2

public class NestedClass2
... and so on.

Outside of the model I instantiate an object of MainClass and then inside
the contstructor of MainClass I instantiate an object of NestedClass. So,
for example, 'ObjectMain' would be an instance of MainClass and
'ObjectNested1' would be an instance of NestedClass1. That all seems to work
fine.

I'm now trying to build a method to retrieve the current value of a given
property. I pass to this method the instance of the model and the name of
the property. It first looks in the root of MainClass to see if the property
is there. If it isn't then it starts cycling through the various nested
classes to see if it's in one of them. Once it finds the correct nested
class then it retrieves the value of the property.

But here's the dilemma: I can explicitly specify the name of the nested
class to retrieve the property value, such as:

property.GetVal ue(ObjectMain.O bjectNested1, null)

That works great! But I'd much prefer to keep things more generic so that
this method would be completely resuable in the future. Yet I cannot figure
out how to use Reflection (or something else) to get the equivalent of
'ObjectMain.Obj ectNested1'

I realize this is a complicated issue but I hope I've explained it
succinctly and hope even more that someone has a solution!

Robert Werner
Vancouver, BC

Nov 17 '05 #2
I re-read your post and feel that I didn't answer your question with my initial response. Here is what I believe you were looking
for:

using System;

namespace TestConsole
{
public sealed class Startup
{
private Startup() {}

public static void Main()
{
ContainerClass obj = new ContainerClass( );

foreach (System.Reflect ion.PropertyInf o objProp in obj.GetType().G etProperties())
{
if (objProp.CanRea d)
{
object[] indexer = new object[0];
object nestedObj = objProp.GetValu e(obj, indexer);

foreach (System.Reflect ion.PropertyInf o nestedProp in nestedObj.GetTy pe().GetPropert ies())
{
if (nestedProp.Can Read)
{
Console.WriteLi ne("{0}.{1}={2} ",
nestedProp.Decl aringType.FullN ame, nestedProp.Name ,
nestedProp.GetV alue(nestedObj, indexer));
}
}
}
}

// Outputs the following:
/*
TestConsole.Con tainerClass+Nes tedClass.Proper ty=Hello World
Press any key to continue
*/
}
}

public class ContainerClass
{
public NestedClass NestedInstance { get { return instance; } }

private NestedClass instance = new NestedClass();

public class NestedClass
{
public string Property { get { return "Hello World"; } }
}
}
}

--
Dave Sexton
dave@www..jwaon line..com
-----------------------------------------------------------------------
"Robert W." <Ro*****@discus sions.microsoft .com> wrote in message news:1B******** *************** ***********@mic rosoft.com...
I've almost completed building a Model-View-Controller but have run into a
snag. When an event is fired on a form control I want to automatically
updated the "connnected " property in the Model. This works fine if all of
the properties are at the top (root level) of the model but I'd like to keep
them in nested classes to organize them better.

So, for example, part of my data model looks like this (simplified) :

public class MainClass

public class NestedClass1

public bool Property1

public string Property2

public class NestedClass2
... and so on.

Outside of the model I instantiate an object of MainClass and then inside
the contstructor of MainClass I instantiate an object of NestedClass. So,
for example, 'ObjectMain' would be an instance of MainClass and
'ObjectNested1' would be an instance of NestedClass1. That all seems to work
fine.

I'm now trying to build a method to retrieve the current value of a given
property. I pass to this method the instance of the model and the name of
the property. It first looks in the root of MainClass to see if the property
is there. If it isn't then it starts cycling through the various nested
classes to see if it's in one of them. Once it finds the correct nested
class then it retrieves the value of the property.

But here's the dilemma: I can explicitly specify the name of the nested
class to retrieve the property value, such as:

property.GetVal ue(ObjectMain.O bjectNested1, null)

That works great! But I'd much prefer to keep things more generic so that
this method would be completely resuable in the future. Yet I cannot figure
out how to use Reflection (or something else) to get the equivalent of
'ObjectMain.Obj ectNested1'

I realize this is a complicated issue but I hope I've explained it
succinctly and hope even more that someone has a solution!

Robert Werner
Vancouver, BC

Nov 17 '05 #3
Dave,

Perhaps there's an obvious assumption (ie. next step) you've made that I'm
not aware of but how does this solve my problem? What I need to do is find a
way in code to find the equivalent of: ObjectMain.Obje ctNested1

Robert

"Dave" wrote:
public static void Main()
{
Type type = typeof(System.E nvironment);

foreach (Type nested in type.GetNestedT ypes())
Console.WriteLi ne(nested.FullN ame);

// Outputs the following:
/*
System.Environm ent+SpecialFold er
Press any key to continue
*/
}

--
Dave Sexton
dave@www..jwaon line..com


Nov 17 '05 #4
My second post illustrates how you can dynamically access the values' of properties, of a property, of a given object. It does not
matter where the object reference of a property is declared:

"Object1" has property, "Property1" of type "Object2". Object2 can be nested, or not. It doesn't matter.

To get the value of a property of Object2, you need first an instance of Object1 that has Property1 set to an instance of Object2.
From here, you can enumerate the properties of Object2.

I'm not sure why you're having trouble with the fact that Property1 is of a type that is nested. It shouldn't matter if you have a
reference to Object1.
--
Dave Sexton
dave@www..jwaon line..com
-----------------------------------------------------------------------
"Robert W." <Ro*****@discus sions.microsoft .com> wrote in message news:B0******** *************** ***********@mic rosoft.com...
Dave,

Perhaps there's an obvious assumption (ie. next step) you've made that I'm
not aware of but how does this solve my problem? What I need to do is find a
way in code to find the equivalent of: ObjectMain.Obje ctNested1

Robert

"Dave" wrote:
public static void Main()
{
Type type = typeof(System.E nvironment);

foreach (Type nested in type.GetNestedT ypes())
Console.WriteLi ne(nested.FullN ame);

// Outputs the following:
/*
System.Environm ent+SpecialFold er
Press any key to continue
*/
}

--
Dave Sexton
dave@www..jwaon line..com

Nov 17 '05 #5
Dave,

Above & beyond the call. Thank you so much!!!

Being new to C# I need to thoroughly study your code more but I think my
problem lies in that my "connection " between the ContainerObject and the
NestedObject is much more limited than the way you did it.

For all I did was the equivalent of this:

public NestedClass NestedObject = new NestedClass();
But I'm not beginning to think that my approach really doesn't provide any
actual connection between the two classes. Your way does and I think
provides me a solid path to my solution.

Got to get some sleep now but will revisit tomorrow and respost here when I
know more.

Thank you again!

Robert W.


"Dave" wrote:
I re-read your post and feel that I didn't answer your question with my initial response. Here is what I believe you were looking
for:

using System;

namespace TestConsole
{
public sealed class Startup
{
private Startup() {}

public static void Main()
{
ContainerClass obj = new ContainerClass( );

foreach (System.Reflect ion.PropertyInf o objProp in obj.GetType().G etProperties())
{
if (objProp.CanRea d)
{
object[] indexer = new object[0];
object nestedObj = objProp.GetValu e(obj, indexer);

foreach (System.Reflect ion.PropertyInf o nestedProp in nestedObj.GetTy pe().GetPropert ies())
{
if (nestedProp.Can Read)
{
Console.WriteLi ne("{0}.{1}={2} ",
nestedProp.Decl aringType.FullN ame, nestedProp.Name ,
nestedProp.GetV alue(nestedObj, indexer));
}
}
}
}

// Outputs the following:
/*
TestConsole.Con tainerClass+Nes tedClass.Proper ty=Hello World
Press any key to continue
*/
}
}

public class ContainerClass
{
public NestedClass NestedInstance { get { return instance; } }

private NestedClass instance = new NestedClass();

public class NestedClass
{
public string Property { get { return "Hello World"; } }
}
}
}

--
Dave Sexton
dave@www..jwaon line..com


Nov 17 '05 #6
Hi Dave,

I was sick today and got absolutely nothing done work-wise. I meant to ask
you one other thing related to all this:

When I first learned about nested classes I just assumed that an inner class
was essentially the child of the outer class. What I mean is that once
defined and once the inner class is instantiated (in the simple way that I
did it) in the outer class's constructor, that a parent-child relationship is
set up.

This belief seemed to be reenforced when I learned how to use the FieldInfo
of Reflection to gather the structure of the class definition. So naturally,
I thought, if there's a relationship with the class definition then there'd
"obviously" be a relationship with the object created from these classes.

But after seeing your code (which I still do have to test thoroughly and
implement myself) I began to wonder if the whole nested classes concept was
more a matter of simple visual convenience than anything else.

For example, let's look at two scenarios:

Configuration 1:

class OuterClass
{
OuterClass() // constructor
{
InnerClass innerObject = new InnerClass();
}

class InnerClass
{
}
}

Configuration 1:

class OuterClass
{
OuterClass() // constructor
{
InnerClass innerObject = new InnerClass();
}
}
class InnerClass // Could even be in a separate file
{
}

After reviewing (and thinking about) your code I began to wonder if all of
my earlier assumptions were incorrect. In fact, in terms of an actual
parent-child relationship between the OuterObject and the InnerObject:
- There really is none, if configured as above, is there?
- There's really no difference between the two configurations above, is
there?

I apologize if all of these seem like dumb (read "obvious") questions but
the articles and other explanations I've found on nested classes aren't very
comprehensive.

Robert W.

"Robert W." wrote:
Dave,

Above & beyond the call. Thank you so much!!!

Being new to C# I need to thoroughly study your code more but I think my
problem lies in that my "connection " between the ContainerObject and the
NestedObject is much more limited than the way you did it.

For all I did was the equivalent of this:

public NestedClass NestedObject = new NestedClass();
But I'm not beginning to think that my approach really doesn't provide any
actual connection between the two classes. Your way does and I think
provides me a solid path to my solution.

Got to get some sleep now but will revisit tomorrow and respost here when I
know more.

Thank you again!

Robert W.


Nov 17 '05 #7
You are right that there is no instance-relationship between nested classes. If you instanciate a class that contains a nested
class, the nested class isn't automattically instanciated.

Think of classes as templates, and objects as a runtime instance of a template. If a template contains another template, then
that's just the location of the defination of the template as you explained in your post.

It is not recommended that you make classes nested except in cases where your nested classes will be private. This is useful for
when you need to hide a class implementation that will be consumed only by the containing "template". If you have to make a nested
class public, then it probably shouldn't be a nested class. If you notice in VS.NET intellisense/object browser there is little
support for nested classes. This is probably because it is assumed that nested classes are for private implementations only, even
though they can be made as public.

The code I gave you illustrates the relationship between a nested class and and object instance at runtime, i.e. there is none, or
it's no different than any other class relationship.

Reflection lets you look at the metadata for a class, i.e. it's members but not it's implementation. Therefore, in your code
examples, you must have a member of the same Type as the nested class in order for you to reflect in the object and gain information
about the nested class instance. (Like I commented in my code example, whether a member is of a nested class or not, Reflection
will be the same code.)

Check out my comments:
class OuterClass
{ // Now when you enumerate the fields of an instance of OuterClass
// you will find this field, which just so happens to be of a Type
// that is nested. Using an instance of OuterClass, you can obtain an
// instance of InnerClass through this field (if it is not set to null).
InnerClass innerObject = new InnerClass();
OuterClass() // constructor
{ // You won't be able to reflect this instance because it is confined to
// the implementation of the constructor. InnerClass innerObject = new InnerClass();
}

class InnerClass
{
}
}
Config 2:
class OuterClass
{ // Now when you enumerate the fields of an instance of OuterClass you will find this field,
// which just so happens to be of a Type that is NOT nested.
// Using an instance of OuterClass, you can obtain an instance of InnerClass through this field
// (if it is not set to null).
InnerClass innerObject = new InnerClass();
OuterClass() // constructor
{ // Same as the line in the constructor of config 1. InnerClass innerObject = new InnerClass();
}
}

// True, it may be declared in a seperate file :)
// I believe in 2.0 you can actually redeclare the same class in multiple files and the compiler
// will mix there implementation into one class template. I read that a while ago, so I'm not
// sure if 2.0 will actually allow it, but it's worth mentioning just in case. class InnerClass // Could even be in a separate file
{
}

--
Dave Sexton
dave@www..jwaon line..com
-----------------------------------------------------------------------
"Robert W." <Ro*****@discus sions.microsoft .com> wrote in message news:C2******** *************** ***********@mic rosoft.com... Hi Dave,

I was sick today and got absolutely nothing done work-wise. I meant to ask
you one other thing related to all this:

When I first learned about nested classes I just assumed that an inner class
was essentially the child of the outer class. What I mean is that once
defined and once the inner class is instantiated (in the simple way that I
did it) in the outer class's constructor, that a parent-child relationship is
set up.

This belief seemed to be reenforced when I learned how to use the FieldInfo
of Reflection to gather the structure of the class definition. So naturally,
I thought, if there's a relationship with the class definition then there'd
"obviously" be a relationship with the object created from these classes.

But after seeing your code (which I still do have to test thoroughly and
implement myself) I began to wonder if the whole nested classes concept was
more a matter of simple visual convenience than anything else.

For example, let's look at two scenarios:

Configuration 1:

class OuterClass
{
OuterClass() // constructor
{
InnerClass innerObject = new InnerClass();
}

class InnerClass
{
}
}

Configuration 1:

class OuterClass
{
OuterClass() // constructor
{
InnerClass innerObject = new InnerClass();
}
}
class InnerClass // Could even be in a separate file
{
}

After reviewing (and thinking about) your code I began to wonder if all of
my earlier assumptions were incorrect. In fact, in terms of an actual
parent-child relationship between the OuterObject and the InnerObject:
- There really is none, if configured as above, is there?
- There's really no difference between the two configurations above, is
there?

I apologize if all of these seem like dumb (read "obvious") questions but
the articles and other explanations I've found on nested classes aren't very
comprehensive.

Robert W.

"Robert W." wrote:
Dave,

Above & beyond the call. Thank you so much!!!

Being new to C# I need to thoroughly study your code more but I think my
problem lies in that my "connection " between the ContainerObject and the
NestedObject is much more limited than the way you did it.

For all I did was the equivalent of this:

public NestedClass NestedObject = new NestedClass();
But I'm not beginning to think that my approach really doesn't provide any
actual connection between the two classes. Your way does and I think
provides me a solid path to my solution.

Got to get some sleep now but will revisit tomorrow and respost here when I
know more.

Thank you again!

Robert W.

Nov 17 '05 #8
Dave,

Just wanted to thank you again!!! It has been a long day of programming but
I've now reached a major milestone and it's all thanks to you getting me past
that nested classes hurdle.

What I've been able to do is successfully (and completely) build a generic
bi-directional automated synchronization mechanism for an MVC
(Model-View-Controller) type application.

I have a data model (parent class and series of nested classes, each of
which contain several properties). And I also have a Windows form with
dozens upon dozens of controls on it.

Rather than individually coding the event mechanisms for each form control
and associated model properties, instead I now just need to enter into each
form control's tag the following: "Property=Prop_ name" For radio button
groupings I can also add a "Value=Button_v alue".

And once this is done, every control that is tagged this way then is
automatically bound to its associated model property. What's really great is
that the synchronization works both ways. So if some external code sets a
property called "CanPrint" to true then the "CanPrint" checkbox (or radio
button pair) is automatically set accordingly.

While it's true that not every control/property will be this
straightforward , a great number of them are! And like I said above, I've
built it generically (OOP) so that I can use the same objects in the future!!

This C# is soooooooooooo much more powerful than VB. I love it! And when I
get stuck on something there are great people like you to help me out.

Thank you so much!!!!

Robert Werner
www.mwtech.com
Vancouver, BC
Nov 17 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
10773
by: August1 | last post by:
A handful of articles have been posted requesting information on how to use these functions in addition to the time() function as the seed to generate unique groups (sets) of numbers - each group consisting of 6 numbers - with a total of 50 groups of numbers. A well-known girl that some publishing companies use to provide introductory level textbooks to various Junior Colleges in the U.S., not surprisngly, asks for this same exact...
2
2990
by: Robert W. | last post by:
I'm trying to write a utility that will use Reflection to examine any data model I pass it and correctly map out this model into a tree structure. When I say "any" , in fact there will only be 3 types of items in the very hierarchical data model: - Classes (and nested classes) - Collections - Properties I've successfully written the Reflection code to handle any combination of classes and properties but I'm confused about what to do...
5
4587
by: Anders Borum | last post by:
Hello! Whilst refactoring an application, I was looking at optimizing a ModelFactory with generics. Unfortunately, the business objects created by the ModelFactory doesn't provide public constructors (because we do not allow developers to instantiate them directly). Because our business objects are instantiated very frequently, the idea of using reflection sounds like a performance killer (I haven't done any tests on this, but the...
2
2541
by: prabhupr | last post by:
Hi Folks I was reading this article (http://www.dotnetbips.com/articles/displayarticle.aspx?id=32) on "Custom Attribute", written by Bipin. The only thing I did not understand in this article is the usage of "Custom Attribute" in real life project. Can somebody please help me understand where are these informations really helpful in Development Environment; may be a few example(s) will help me understand.
6
2948
by: ivan.leben | last post by:
I want to write a Mesh class using half-edges. This class uses three other classes: Vertex, HalfEdge and Face. These classes should be linked properly in the process of building up the mesh by calling Mesh class functions. Let's say they point to each other like this: class Vertex { HalfEdge *edge; }; class HalfEdge { Vertex* vert;
0
2039
by: ivan.leben | last post by:
I am writing this in a new thread to alert that I found a solution to the problem mentioned here: http://groups.google.com/group/comp.lang.c++/browse_thread/thread/7970afaa089fd5b8 and to avoid this topic getting lost before people interested in the problem notice it. The important tricks to the solution are two: 1) make the custom classes take a TEMPLATE argument which defines their BASE class 2) EMBED the custom classes in a "Traits"...
3
4114
by: Steve Amey | last post by:
Hi all I am using reflection to read the values of properties from a class. The class is returned from a Web Service so I have to access the class using FieldInfo (Using VS 2003 which converts the Properties into Fields when it comes out of the Web Service). I have this at the moment: Private _aDataSource As Object 'Person class
2
4896
by: bill | last post by:
All, Can anyone supply an example or reference to an example of using reflection to determine the data types contained in a nested stucture in C#? Once I get the list of MemberInfo and determine that MemberInfo.MemberType.ToString().Equals("NestedType"), I cannot figure out how to drill down from that point. TIA,
4
2205
by: Per Bolmstedt | last post by:
(This question has been asked previously in this group, but I don't think it was ever really properly answered.) I want to use reflection - preferably - to find all Web Forms in my web site that inherit my base page class (which in turn inherits System.Web.UI.Page). Behold the following code: For Each asm As System.Reflection.Assembly In System.AppDomain.CurrentDomain.GetAssemblies() For Each mdl As System.Reflection.Module In...
0
9840
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11259
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10857
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10948
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10483
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7187
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6076
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4706
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3305
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.