Red Swan
Red Swan

Reputation: 15545

clearance about "static" field in c#

I have commonFields class in my application. this is online asp.net mvc application of simple test/exam. suppose student have logged in with his credentials. he got select test, and said load it.it will load test in some controller, each test have set of questions. now with this test id i get the list of questions of that particular test. and stored in commonfield class's

 public static List<Question> questionList; 

object. due to static it will as it is for application. but if same time another student get logged in and performing the same or different test. then his selected test's question will stored into again in the questionList object (same as above).

same like say 100's of student performing test. then what impact will be on questionList? will it always need to instantiates? in commonField class? how to manage this? or due to static CLR will manage it ?

Upvotes: 1

Views: 132

Answers (4)

MeelStorm
MeelStorm

Reputation: 634

You should use Session instead of storing your questions in static fields.

List<Question> questionList=new List<Question>();
//fill the list with your questions
Session["Questions"] = questionList;

Then if you need questions of the current student use this:

List<Question> questionList=(List<Question>)Session["Questions"];

Upvotes: 1

Chingiz Musayev
Chingiz Musayev

Reputation: 2962

You need to put test id for user in the Session. Do not try save object state between user requests in class fields or whatever. Also you need to pay attention to the Cache ASP.NET object for quick access of last loaded questions for tests.

Upvotes: 1

Furqan Hameedi
Furqan Hameedi

Reputation: 4400

Being a static field, the

questionList

shall remain common for all students that are loggedIn. So you must instantiate a new instance of QuestionsList for each student and store it in that student's session.

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273264

You should store common data in the Application object and the per-student data in Session.

At some point, once per session:

  Session["questions"] = CreateQuestionList();

and then whenever you need it:

   questionList = (List<Question>)Session["questions"] ;

Your static variable is not reliable, won't scale to multiple servers and it certainly won't allow a different questionList for each student.

Upvotes: 5

Related Questions