4
votes

I have the following code which basically returns the display name for the user. I am utilizing the using keyword to correctly dispose the PrincipalContext and the UserPrincipal.

My question is that since the result points to user.DisplayName would result be pointing to a null or disposed object once the UserPrincipal is disposed. I don't think using disposing objects immediately it just marks for disposable and once it needs more memory it disposes the marked objects.

private string GetWindowsDisplayName()
{
    string result = string.Empty;

    using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
    {
        using (UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, principal.Identity.Name))
        {
            if (user != null) 
                result = user.DisplayName;
        }
    }

    return result;
}
1

1 Answers

1
votes

result points to user.DisplayName

No it doesn't.

The value stored in user.DisplayName is copied to result. What you're returning is just that value, which by then has nothing to do with the user object.

You can demonstrate this concept with something like this:

var first = "one";
var second = first;
second = "two";
// here, "first" still equals "one"