4

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;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
john doe
  • 9,220
  • 23
  • 91
  • 167

1 Answers1

1

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"
David
  • 208,112
  • 36
  • 198
  • 279
  • 1
    So strings in .NET are value objects? – john doe Dec 28 '15 at 20:11
  • @johndoe: That's actually a pretty interesting question, for which I don't have a canonical enough answer. In the case of setting values, it certainly *behaves* like a value. But the `String` class is an object, strings can be `null`, etc. – David Dec 28 '15 at 20:14
  • @johndoe: Looks like good info can be found here, though: http://stackoverflow.com/questions/636932/in-c-why-is-string-a-reference-type-that-behaves-like-a-value-type – David Dec 28 '15 at 20:15
  • 1
    @johndoe To elaborate on what David has said, the actual value of the string isn't what gets copied since `string` is a reference type. Also, because it's a reference type, the string value doesn't actually live inside your user object, the user object merely references it. Since you capture a copy of that reference via the `result` variable, the string stays alive. – Kyle Dec 28 '15 at 20:42
  • 1
    Additionally, `string` objects are immutable. When you assign a new value to string its a new string object every time. – vendettamit Dec 28 '15 at 21:14