Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused with C# 'using'

I have seen some code for working with AD in this stackoverflow question

I am getting confused about the using statement. I thought that it was just used for things that you are worried could become memory leak, like a WebClient, or similar...

Anyway:

using (var context = new PrincipalContext( ContextType.Domain )) 
 {
      using (var user = UserPrincipal.FindByIdentity( context, "username" ))
      {
          var groups = user.GetAuthorizationGroups();
          ...
      }
 }

when I reach the line var groups = user.GetAuthorizationGroups() - user is null, so that line fails with a NullReference. When I mouse over it debugging it shows null, then shows Static Members, and has all the values.

If I take the line out of using statement and just have var user = UserPrincipal.FindByIdentity( context, "username" ) user is populated as required.

So what's going on ???

Edit: I stuffed up and was sending a bogus username. Oddly though when I check the variables during debug, when you would expect user to be completely null if I sent the bogus userid, but it showed under user: null, static members, and there had values for what I was currently logged in as-so I thought it was to do with the using statement potentially. Cheers!

like image 503
baron Avatar asked Aug 05 '11 04:08

baron


2 Answers

What you're describing cannot happen. The specialness of a using statement doesn't happen until the block is completed, when the object gets disposed. So inside that block, the user variable is the same regardless of whether it's in a using statement or not.

like image 190
Joe Enos Avatar answered Sep 30 '22 09:09

Joe Enos


using is just syntactic sugar for try/finally and automatically calls Dispose on objects that implement IDisposable.

like image 31
Icarus Avatar answered Sep 30 '22 10:09

Icarus