Mar 16th, 2012, 01:52 PM
So I'm new to generics. What I'm doing below is:
1) User creates a struct (or class...this example will only use struct)
public string FirstName;
public string LastName;
public string Department;
2) User instantiates class (not important)
3) User calls method:
UserInfo user = profile.GetInfo<UserInfo>();
4) Method takes the struct and, based on the names of the members of the struct, fills the struct with data from the object (in this particular instance UserProfile [Microsoft.Office.Server.UserProfiles])
/// Fills the class or stuct with information from the users profile.
///<exception cref="ArgumentException">Thrown if the struct or object datamember names are invalid.</exception>
public T GetInfo<T>() where T : new()
object returnValue = new T();
Type type = typeof(T);
FieldInfo fields = type.GetFields();
PropertyInfo properties = type.GetProperties();
if (fields.Length > 0)
foreach (FieldInfo field in fields)
else if (properties.Length > 0)
foreach (PropertyInfo property in properties)
property.SetValue(returnValue, this.Profile[property.Name].Value, null);
throw new System.ArgumentException("Struct or Class member names do not match the options available. Run ListPossibleMembers() to get a list of members");
Unknown members in code shown (class-level variables):
1. "profile" -- UserProfile that gets instantiated in the constructor
I built this because I've found myself constantly querying information about users in SharePoint. With this, all I need to do is create a struct or class with the datamembers, and then call the function.
Since this is my first foray into generics, I was hoping someone could take a look at the code and let me know if they see anything horribly wrong with this, or if they could give suggestions on a different way to accomplish it.
Click Here to Expand Forum to Full Width
Survey posted by VBForums.