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)
Example:
C# Code:
struct UserInfo
{
public string FirstName;
public string LastName;
public string Department;
}//end struct
2) User instantiates class (not important)
3) User calls method:
C# Code:
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])
C# Code:
/// <summary>
/// Fills the class or stuct with information from the users profile.
/// </summary>
///<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);
try
{
FieldInfo[] fields = type.GetFields();
PropertyInfo[] properties = type.GetProperties();
if (fields.Length > 0)
{
foreach (FieldInfo field in fields)
{
field.SetValue(returnValue, this.Profile[field.Name].Value);
}//end foreach
}
else if (properties.Length > 0)
{
foreach (PropertyInfo property in properties)
{
property.SetValue(returnValue, this.Profile[property.Name].Value, null);
}//end foreach
}//end if
}
catch (Microsoft.Office.Server.UserProfiles.PropertyNotDefinedException)
{
throw new System.ArgumentException("Struct or Class member names do not match the options available. Run ListPossibleMembers() to get a list of members");
}
catch (Exception)
{
throw;
}//end try/catch
return (T)returnValue;
}//end GetInfo
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.