I need to retrieve an extended attribute from Active Directory, for
which there is a private method in the ComputerPrincipal
class. I
understand I can only access the private method through a derived
class, so I've derived a class ComputerPrincipalEx
from the base
class. I've then created (defined?) a method in the derived class
which calls the private method in the base class. This part seems OK.
The problem comes when I try to use a (public) method of the base class to assign a value to a variable with the type of the derived class. Here's the code, then I'll try to explain more:
The derived class:
public class ComputerPrincipalEx : ComputerPrincipal
{
public ComputerPrincipalEx(PrincipalContext context) : base(context) { }
public ComputerPrincipalEx(PrincipalContext context, string samAccountName, string password, bool enabled) : base(context, samAccountName, password, enabled) { }
public string ExtensionGet(string extendedattribute)
{
return (string) base.ExtensionGet(extendedattribute)[0];
}
}
The problem code, which itself is a method of another class I've created:
public string GetExtendedAttribute(string attributeName) { PrincipalContext ctx = new PrincipalContext(ContextType.Domain); ComputerPrincipalEx cp = new ComputerPrincipalEx(ctx); cp = ComputerPrincipalEx.FindByIdentity(ctx, Name); return cp.ExtensionGet(attributeName); }
ExtensionGet
is the private method of the base class that I need to
expose, and I think I have this correct because once I create an
object of type ComputerPrincipalEx
, I can access ExtensionGet
, which
is otherwise inaccessible.
The problem is the type conversion in this line: cp = ComputerPrincipalEx.FindByIdentity(ctx, Name);
cp
is defined as ComputerPrincipalEx;
ComputerPrincipalEx.FindByIdentity
references the base
ComputerPrincipal.FindByIdentity
method, and returns a
ComputerPrincipal
. The compiler balks about an implicit conversion
between types. Casting ComputerPrincipal
to ComputerPrincipalEx
satisfies the compiler but the app crashes at runtime because it can't
perform the conversion.
Now, I pretty much understand all of that, but I'm assuming there has to be some way to call a method from the base class and return valid data to an object of the derived class' type, and that's what I'm hoping to find out how to do.