Question about objects  
Author Message
gmedia





PostPosted: Visual C# General, Question about objects Top

I am a novice c# programmer and have a rudamentary question.

I have a class to handle permissions, so to check permission you have to open an object. However, trying to consolitdate code in one spot, i have the class logging the person out if for some reason his/her userID is lost. In doing this, I am not closing out the object I created to check permissions. Will the object close automatically

here is some code:

permissions p = new permissions(intUserID, "cont", strDBConn);//if no userid, user is logged off

public class permissions

public permissions(int userID, string prefix, string dbConn)

{

if (userID <= 0) { logUserOut(); }

intUserID = userID;

strPrefix = prefix;

strDBConn = dbConn;

}

public void logUserOut()

{

FormsAuthentication.SignOut();

System.Web.Security.FormsAuthentication.RedirectToLoginPage();

}



Visual C#4  
 
 
TaylorMichaelL





PostPosted: Visual C# General, Question about objects Top

Open and close are not terms used with objects. The line

permissions p = new permissions(intUserID, "cont", strDBConn);//if no userid, user is logged off

will create a new instance of the permissions class. The object will remain in memory until it is no longer referenced. At some indeterminate future point it will be freed by the garbage collector. Since this class is so simple when it is deleted is unimportant.

For classes that represent limited resources or in which you are interested in knowing when they are deleted you should implement the IDisposable interface. This interface notifies clients that they should dispose of the object when they no longer need it. This is done for things like files, streams and database connections. In C# the using statement is used to automate this process.

using(StreamReader sr = new ...)
{
sr...;
};
//sr has been disposed

Note that even though the reader is disposed it is still in memory. However the reader's dispose implementation has internally released any resources it was using. At some future point the reader object itself will be removed from memory.

Michael Taylor - 12/1/06


 
 
gmedia





PostPosted: Visual C# General, Question about objects Top

Thanks. The class is small so I will take your advice and stick with the way it is implemented.