C# Source Code: Dumping the properties of an object into a string array (excluding indexers)
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Dumping the properties of an object into a string array (excluding indexers)
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Thursday, August 05, 2004
Hits:
1041
Category:
Attributes/Reflection/Debugging
Article:
The routine below uses reflection to walk through all the properties of an object and returns the property names and values in a string array. Note, the routine ignores any indexers the object may expose. using System.Reflection; ///
/// Uses reflection to walk through all the properties of the specified object and outputs /// the results in a string array, in the format: [property1Name=property1Value] ///
///
The object to return the properties of. ///
A 1d string array contain a name value pair (seperated by "=")
///
Doesn't return any indexer values
public static string[] ObjectDumpToArray(object Object) { // Get the type Type type = Object.GetType(); // Get the default property (the indexer) string[] propValues = null; MemberInfo[] indexerMembers = type.GetDefaultMembers(); if ( indexerMembers != null ) { // Remove the space for indexer values propValues = new string[type.GetProperties().Length - indexerMembers.Length]; } else { // Doesn't have an indexer propValues = new string[type.GetProperties().Length]; } int countValid = -1; // Walk through each property storing the name value pair foreach (PropertyInfo info in type.GetProperties()) { MethodInfo methodInfo = info.GetGetMethod(false); if (methodInfo != null) { if ( indexerMembers != null && indexerMembers.Length > 0) { // Check to make sure this is not the indexer if ( info.Name != indexerMembers[0].Name ) { // Store the name value pair countValid++; propValues[countValid] = info.Name + "=" + info.GetValue(Object, null); } } else { // Object doesn't have an indexer, store the name value pair countValid++; propValues[countValid] = info.Name + "=" + info.GetValue(Object, null); } } } // Return results return propValues; }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet