Q: Urgent: Dependable order of Fields and Properties via Reflection?

  • Thread starter Thread starter Sky
  • Start date Start date
S

Sky

Anybody have experience with the following problem, and have suggestions?

Q: When you use Reflection to enumerate a class's Fields and Properties, is
there a predefined order in which they will return?

For example:

public MyClass{
string b;
string c;
string x;
string d;
string a;
}

if I (typeof(MyClass).GetFields() the above, the fields are returned in the
order b, c, x, d,a I typed them...
which makes it very nice to then write a ClassToSQLMakeTableStatement so
that one can generate the "CREATE TABLE {0} ({1}) based off this
information...

My question is -- is this dependable? Will I always be as lucky? I ask
because, I just tried the following class -- with Properties this time --
and pushed it as a DataSrc of a DataGrid...and things were not as I
expected:

public class cTest{
public System.String aaa{get {return System.Guid.NewGuid().ToString();}}
public System.String BBB{get {return "Some longish note to see what
happens\n Does it work????";}}
public string Jack {get {return a.ToString();}}
public string Bob {get {return (a+500).ToString();}}
public int Steve {get {return (a+200);}}
public System.Guid Grunt{get {return System.Guid.NewGuid();}}
public System.String[] Sam {
get {
System.Collections.ArrayList oList = new
System.Collections.ArrayList();
oList.Add("One");
oList.Add("Two");
return (System.String[])oList.ToArray(typeof(System.String));
}
}


public System.Double T{get {return 0.003;}}


The DataGrid accepted this class as a DataSource (it was enherited from a
custom class, based on an ICollection)... but the fields were listed out as:

Jack, Steve, T, BBB, Bob, aaa

!!!

Ie, not Alphabetical, not Size related, no coherrent order that I can
foretell... This has gotten me worried a bit, because I was only 'lucky' in
my first investigations and the FieldInfo() came back in the order I typed
them in only by chance, this blows any caps of making SQL "Create Table"
statements from simply a classdef, without some form or Ordinal position
info being added in the form of Attributes or other device...

PS: the DataGrid skipped Grunt and Sam -- Q: due to both being non-basic
types? What exactly defines a field as being DataSrc ready, BTW ?

Any and all help, greatly appreciated!
 
Sky said:
Anybody have experience with the following problem, and have suggestions?

Q: When you use Reflection to enumerate a class's Fields and Properties, is
there a predefined order in which they will return?

While there is, it's not documented and may change to a different
predefined order. I would expect the order to remain stable between
calls, but again I wouldn't rely on it.
 
Back
Top