Getting an instance's properties without reflection?

J

Joe

It seems that if given an instance of a class, there should be some
inherited property (from "object" perhaps) that is a collection of the
properties of that instance.

I know you can get to it by using reflection, but that seems to be a
convoluted and costly way to go about doing it, since I have the
instance already.

For example:

public class Foo
{
public string Name;
public int Age;

public Foo()
{
// potential code that I'm hoping exists...
foreach (PropertyInfo p in this.[?????])
{
// whatever
}
}
}

Again, I know how to do this with reflection. I'm just looking for a
more efficient (and hopefully more straight-forward) way to do it.
 
M

Mattias Sjögren

Joe,
I'm just looking for a
more efficient (and hopefully more straight-forward) way to do it.

There isn't any, Reflection is the way to go.



Mattias
 
M

Michael Lang

I've found a way to do this without reflection. I don't recommend it in
most situations, but it has it's uses. Create an enumeration inside the
class definition.

public class MyClass
{
public enum Fields{Field1, Field2, FieldN}
public string Field1{get;set;}
public int Field2{get;set;}
public object FieldN{get;set;}
}

This may save on performance, but it may also increase the memory footprint?
It is also more limited that Reflection. What about getting the type of the
property? Another enum?

Another drawback... If you are creating a method that takes an object
datatype then you can't be sure the instance passed in will be of a type
that has an enum called Fields. However, you could make the method
arguement be of type "IHasFieldEnum", where that interface means it contains
the "Fields" enum. This of coarse reduces the overall usefullness of your
class.

You can't use a foreach loop to iterate through an enum, so your use case
would not work. Overall, it is probably best to use reflection. You can
loop through an object's properties using reflection.

Here is how you would do you what you want with reflection:

public void Foo(object obj)
{
System.Reflection.PropertyInfo[] pi =
obj.GetType().GetProperties();
for (int i=0; i < pi.Length; i++)
{
string name = pi.Name;
//do whatever else ...
}
}

I'm not sure why you would iterate over the properties IN the same object as
the method you are are calling, or in the objects constructor? When writing
a method in an object, you know what properties are in that object!
However, if you want to do that you could use "this" in place of "obj" in
the sample method above.

Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top