Re: Extending objects that get returned as generics

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



Keith Elder wrote:
I ran into a unique situation today whereby I have a core library that uses generics to return users from Active Directory. Example:

List<ADUser> users = ADUser.GetByName("First", "Last");

This works great. However, what I need to do is extend the ADUser object like so:

class DataGridUser : ADUser
{
    // add some new properties
    // add some new methods for databinding
}

I can't figure out how to extend it though since the GetByName() returns a List<ADUser>. Trying this doesn't work:

List<DataGridUser> users = DataGridUser.GetByName("First", "Last");

This throws an exception that GetByName cannot convert DataGridUser to ADUser. What am I missing or doing wrong? Anyone got any ideas?

-Keith

I took another stab at this a different way thinking I could solve the problem but I seemed to have run into a snafu with null exception and casting. Here is what I did to the base library class trying to come up with a more flexible solution. The problem lies within the GetUsersByName() where user is always null and cannot be converted. Anyone see something that I'm missing and a way to fix this?



class ADUser { public string FirstName; public string LastName;

public static List<T> GetUsersByName<T>(string firstName, string lastName) where T : ADUser
{
List<T> users = new List<T>();
using (DirectorySearcher ds = GetDirectorySearcher())
{
ds.SearchRoot = AD.DirectoryEntry;
ds.PageSize = 100;
ds.Filter = field;
try
{
using (SearchResultCollection result = ds.FindAll())
{
foreach (SearchResult singleResult in result)
{
// LINE BELOW IS THE ONE IN QUESTION
// IT ALWAYS RETURNS user as null
T user = new ADUser(singleResult) as T;
users.Add(user);
}
}
return users;
}
catch (Exception ex)
{
throw new Exception("Something blew up");
}
}
}
}


class DataGridUser : ADUser
{
private Bitmap photo = null;
public Bitmap Photo
{
get
{
if (photo == null) { this.photo Some.Lib.GetImageFromURL(this.PhotoURL); }
return this.photo;
}
}
}



class WinForm
{
WinForm()
{
List<DataGridUser> users = ADUser.GetUsersByName<DataGridUser>("frank", String.Empty);
}
}
.