How count number of objects created with a static class variable? - c#

I created 3 objects of a class and I want to display on the console how many objects I have created (using a static class variable) - How do I do this ?
I put public static int count = 0; in the class I created but I couldn't get it to increment (count++;) based on how many objects I created of the class. I created the 3 objects in the main method and gave them values for variables.
here is the class I created in my program :
public class Student
{
public static int count = 0;
// count++;
private string firstName;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
private string lastName;
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
private string birthDate;
public string BirthDate
{
get { return birthDate; }
set { birthDate = value; }
}
}
In the main method I created 3 objects of class Student:
static void Main(string[] args)
{
// Create 3 students
Student student1 = new Student
{
FirstName = "John",
LastName = "Wayne",
BirthDate = "26/05/1907"
};
Student student2 = new Student
{
FirstName = "Craig",
LastName = "Playstead",
BirthDate ="01/01/1967"
};
Student student3 = new Student
{
FirstName = "Paula",
LastName = "Smith",
BirthDate = "01/12/1977"
};
// Console.WriteLine("The course contains {1} students(s) " studentCounter );
I can't get the counter to ++ based on the way I created the objects.

Increment the count in the constructor:
public class Student
{
public static int count = 0;
public Student()
{
// Thread safe since this is a static property
Interlocked.Increment(ref count);
}
// use properties!
public string FirstName { get; set; }
public string LastName { get; set; }
public string BirthDate { get; set; }
}

You just need a constructor, there you can increment the count.
public Student()
{
count++;
}

You can increment the counter in the constructor
public Student()
{
count++;
}

To print the count variable
we should write some code like below
public static int GetCount()
{
return count;
}
and main class look like :
static void Main(string[] args)
{
// Create 3 students
Student student1 = new Student
{
FirstName = "John",
LastName = "Wayne",
BirthDate = "26/05/1907"
};
Student student2 = new Student
{
FirstName = "Craig",
LastName = "Playstead",
BirthDate ="01/01/1967"
};
Student student3 = new Student
{
FirstName = "Paula",
LastName = "Smith",
BirthDate = "01/12/1977"
};
//To print the count
Console.WriteLine(" Number of Objects is : "+Student.GetCount());
}
and if we have parameterized constructor then we also have to write count++ in that constructor.

Related

storing Instances of student into an array

Im trying to store these instances of student inside of this array.
Student:
public Student(string Value)
{
FirstName = Value;
LastName = Value;
StudentID = Value;
}
Here is the Array
string[] student = new string[4];
{ ElementarySchoolStudent, MiddleSchoolStudent, HighSchoolStudent, CollegeStudent }
Each constructor is like this and they use the Student method.
CollegeStudent(string value) : base(value) { }
How exactly would I go about storing these instances in the array? When I do it like that i get the error message:
college student is a type which is not valid in the given context.
What's the correct way to code it exactly?
From this and the last question, maybe you want something like this
Given
public class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string StudentID { get; set; }
}
Usage
var students = new Student[]
{
new Student(){FirstName = "bob",LastName = "blerg",StudentID = "23432"},
new Student(){FirstName = "dan",LastName = "flib",StudentID = "4564"},
new Student(){FirstName = "jib",LastName = "jab",StudentID = "564"},
};
foreach (var student in students)
Console.WriteLine($"{student.StudentID} : {student.FirstName}, {student.LastName}");
Output
23432 : bob, blerg
4564 : dan, flib
564 : jib, jab
Note : Add constructor or pepper and salt to taste

How to update list using linq in c#

I have a list of Students in cache, and I wants to update an item, how can i do that.
public class Student
{
int id;
string name;
string address;
}
public void updateStudent(Student st)
{
var student = _cache.Get(CacheVariable.cache_data_student) as List<Student>;
//How to update student.
}
Maybe you can do it with a small query.
First Find this updated student is who?
And Find this student's place from List
Then Change This Place with new Value
var student = _cache.Get(CacheVariable.cache_data_student) as List<Student>;
Student findStudent = student.FirstOrDefault(x=> x.Id == st.Id);
int id = student.IndexOf(y);
student[id] = st;
or if you want you can use another thing for last row like :
student[id] = new Student()
{
id = x,
name = "y",
address = "z"
};
Probably there is a better solution for this situation but I don't know. I think this could be helpfull
Since the ID should be the unique identifier, use LINQ to get the student to update:
public void updateStudent(Student st)
{
Student studentToUpdate = _cache.FirstOrDefault(s => s.id == st.id)
studentToUpdate?.Update(st);
}
To update your student you need to implement your own method. Just set the properties like
public class Student
{
public int id { get; }
public string name { get; set; }
public string address { get; set; }
public void Update(Student st)
{
this.name = st.name;
this.address = st.address;
}
}
public class Student
{
int id;
string name;
string address;
}
public void updateStudent(Student st)
{
var student = _cache.Get(CacheVariable.cache_data_student) as List<Student>;
//First look for the st in Student list, you need the id field or primary key
var s = student.Where(x => x.idField == st.idField).FirstOrDefault();
s = st;
//student = st;//student.Update(st); //Not working. Only pass the value
}

Type casting in C# .net

I am learning a MOOC course on c#. we had to create an Arraylist of type students and then using the foreach loop had to iterate over it and print the names. i have tried all casting methods but could not get through it. please help
c.students.Add(student1);
c.students.Add(student2);
c.students.Add(student3);
foreach(object o in students)
{
Student s = (Student)o;
Console.WriteLine(s.FirstName);
}
c is the course object. course is a class. students is the arraylist. Student is a class.
Not sure where you face the error. Check out my .NET Fiddle here. Code shown below as well. Hope it helps.
using System;
using System.Collections;
public class Program
{
public static void Main()
{
var students = new ArrayList();
students.Add(new Student() { FirstName = "John", LastName = "Doe" });
students.Add(new Student() { FirstName = "Richard", LastName = "Roe" });
foreach(Student s in students)
{
Console.WriteLine(s.FirstName);
}
}
}
public class Student
{
public string FirstName {get;set;}
public string LastName {get;set;}
}
foreach(object o in c.students)
this should do it, its probably a silly mistake
namespace stackOverflow
{
class Program
{
static void Main(string[] args)
{
course c = new course();
student student1 = new student("a");
student student2 = new student("b");
student student3 = new student("c");
c.students.Add(student1);
c.students.Add(student2);
c.students.Add(student3);
foreach (object o in c.students)
{
student s = (student)o;
Console.WriteLine(s.name);
}
}
}
class course
{
public List<student> students = new List<student>();
}
class student
{
public string name { get; set; }
public student(string s)
{
name = s;
}
}
}
ArrayList students = new ArrayList();
This line should be: c.students = new ArrayList(); as mentioned by Channs previously.
As you have written it, it is trying to create a new variable in your main function called students, it never accesses the students array inside your course object.
Although your initialisation of internal object variables should be done within the object itself.
So inside your course object do something more like this:
class Course
{
public ArrayList students;
public Course()
{
students = new ArrayList();
}
}
This way, whenever you declare a new object of type Course ( ie: Course c = new Course() ) it will initialise the array automatically.
Another issue I noticed was in your Student constructor declaration, you are always trying to take a parameter of string fname.
public Student(string fname)
Then in your code you never pass that data ie:
Student student1 = new Student();
So either pass the firstname variable in when you are initialising or change your constructor in Student to allow it to accept nothing as well as a firstname as shown below:
class Student
{
private string firstName;
private string lastName;
public Student(string fname = null)
{
this.FirstName = fname;
}
this way you don't have to pass the data, but if you do it will be copied over to the firstname of the student object.
You could always change the null to something like "John" or "No Name" so that you have printable data in the object. just a suggestion though.
Regards,
Slipoch
Here is your code fixed up. There were 2 things:
Your student class did not have a default constructor.
Your student array list was not initialized in the course class.
Hope this helps.
using System;
using System.Collections;
class Program
{
public static void Main(string[] args)
{
Student student1 = new Student();
student1.FirstName = "a";
student1.LastName = "w";
Student student2 = new Student();
student2.FirstName = "e";
student2.LastName = "s";
Student student3 = new Student();
student3.FirstName = "i";
student3.LastName = "o";
Course c = new Course();
ArrayList students = new ArrayList();
c.students.Add(student1);
c.students.Add(student2);
c.students.Add(student3);
foreach (Student o in c.students)
{
Student s = (Student)o;
Console.WriteLine(s.FirstName);
}
Console.ReadLine();
}
}
internal class Course
{
public ArrayList students = new ArrayList();
}
internal class Student
{
private string firstName;
private string lastName;
public Student()
{
}
public Student(string fname)
{
this.FirstName = fname;
}
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
}
}
}

Adding contents of object to list rather then parameter type?

Hopefully I am describing this correctly and clear enough. I am trying to save multiple details entered by a user and save them to list. However the current way I am doing so is only saving the object type/name rather then the data. Below is my code how would I save the objects data rather then the name of the object?
Student stud = new Student();
stud.Enter_Student();
_studentList.Add(stud);
Enter Student
class Student : Person
{
public string StudentId { get; private set; }
public string Subject { get; private set; }
//string[] _studentdb = new string[4];
public Student()
{
StudentId = "abc123";
Subject = "Building Subject";
}
public void Enter_Student()
{
this.Person_Prompt_Print(); //Prompts for user
this.Address_Prompt_Print();
this.Contact_Prompt_Print();
Console.SetCursorPosition(4, 18);
Console.WriteLine("Student ID:");
this.Enter_Person(); // Inputs from user
this.Enter_Address();
this.Enter_Contacts();
StudentId = Console.ReadLine();
Console.SetCursorPosition(30, 18);
}
}
Date sample from person class
class Person
{
Tidyup tidy = new Tidyup();
public string FirstName { get; private set; }
public string Surname { get; private set; }
public string MiddleName { get; private set; }
public string AddressLine1 { get; private set; }
public string AddressLine2 { get; private set; }
public string Town { get; private set; }
public string Postcode { get; private set; }
public string Email { get; private set; }
public string Telephone { get; private set; }
public Person()
{
FirstName = "Name";
Surname = "Surname";
MiddleName = "Middle Name";
AddressLine1 = "Address";
AddressLine2 = "Address Ln2";
Town = "Town";
Postcode = "<xxx>/<xxx>";
Email = "name#buildright.ac.uk";
Telephone = "0800 0000000";
}
public void Person_Prompt_Print()
{
// Program Frame
tidy.Line_Top();
tidy.Line_Base();
tidy.Sides_Left();
tidy.Sides_Right();
Console.SetCursorPosition(4, 2); //Prompts for user
Console.WriteLine("FirstName:");
Console.SetCursorPosition(4, 4);
Console.WriteLine("Surname:");
Console.SetCursorPosition(4, 6);
Console.WriteLine("Middle Name:");
}
public void Address_Prompt_Print()
{
Console.SetCursorPosition(4, 8); //Prompts for user
Console.WriteLine("House Number/Name:");
Console.SetCursorPosition(4, 10);
Console.WriteLine("Street:");
Console.SetCursorPosition(4, 12);
Console.WriteLine("Town:");
Console.SetCursorPosition(4, 14);
Console.WriteLine("Post Code:");
}
public void Contact_Prompt_Print()
{
Console.SetCursorPosition(4, 16);
Console.WriteLine("Email:");
Console.SetCursorPosition(4, 18);
Console.WriteLine("Telephone:");
}
public void Enter_Person()
{
Console.SetCursorPosition(30, 2); // Inputs from user
FirstName = Console.ReadLine();
Console.SetCursorPosition(30, 4);
Surname = Console.ReadLine();
Console.SetCursorPosition(30, 6);
MiddleName = Console.ReadLine();
}
public void Enter_Address()
{
Console.SetCursorPosition(30, 8); // Inputs from user
AddressLine1 = Console.ReadLine();
Console.SetCursorPosition(30, 10);
AddressLine2 = Console.ReadLine();
Console.SetCursorPosition(30, 12);
Town = Console.ReadLine();
Console.SetCursorPosition(30, 14);
Postcode = Console.ReadLine();
}
public void Enter_Contacts()
{
Console.SetCursorPosition(30, 16);
Email = Console.ReadLine();
Console.SetCursorPosition(30, 18);
Telephone = Console.ReadLine();
}
} // End of Class
And finally I am printing out via a simple nested foreach loop
public void Print_all_student()
{
Console.Clear();
foreach (Student t in _studentList)
{
// print another list items.
foreach (Student t1 in _studentList)
{
Console.WriteLine("/" + t + "/" + t1);
}
}
Console.ReadKey();
}
If anyone can help me understand what I am missing and how to access the data to print out I would be grateful. Thank you in advance for any help you can give.
There are lots of issues here, but in your Console.WriteLine call, you are only displaying the Student type, so the ToString method on the Student type will be invoked, which by default will display the type name.
You want to display the individual properties of the Student type, e.g.
foreach (Student student in studentList)
{
Console.WriteLine(student.FirstName);
Console.WriteLine(student.Surname);
// etc
}
Remember that Student derives from Person, so all of the public properties are accessible from a Student reference, because Student is a Person.
Also:
You have a redundant loop - you only need one loop which enumerates the studentList
There is a real mixture of concerns here. Your Student and Person types should not be concerned with UI (i.e. anything to do with Console calls)
Stick with PascalCase (aka UpperCamelCase) for your method names, no underscores

Adding a list to a dictionary

In my program I have a list of marks and a dictionary which stores the studentId. I want that the user enters the studentId and according to that id it will point to the list of marks. I think I am implementing it incorrectly. Can someone help me in implementing it. Thanks
public class Student() {
private string name;
private string surname;
private string dob;
private string address;
private int id;
public Student()
{
}
public Student(string year,string name, string surname, string dob, string address)
{
this.name = name;
this.surname = surname;
this.dob = dob;
this.address = address;
this.year = year;
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Surname
{
get { return surname; }
set { surname = value; }
}
public string DOB
{
get { return dob; }
set { dob = value; }
}
public string Addr
{
get { return address; }
set { address = value; }
}
public int Id
{
get { return id; }
set { id = value; }
}
private string year;
public string Year
{
get { return year; }
set { year = value; }
}
public Student(string s)
{
string[] splitted = s.Split(',');
name = splitted[0];
surname = splitted[1];
dob = splitted[2];
address = splitted[3];
// id = splitted[4];
}
public Dictionary<int,List<Marks>> dictionary= new Dictionary<int,List<Marks>>();
public List<Marks> Mathematics = new List<Marks>();
public List<Marks> English = new List<Marks>();
public List<Marks> Maltese = new List<Marks>();
public List<Marks> ReligiousStudies = new List<Marks>();
public List<Marks> SocialStudies = new List<Marks>();
public Dictionary<int, List<Marks>> dictionar = new Dictionary<int, List<Marks>>();
public void AddMarks(int hyexam, int anexam)
{
{
Console.WriteLine("enter id of student to input marks to:");
string id = Console.ReadLine();
if (dictionar.ContainsKey(Id).Equals(id))
{
Mathematics.Add(new Marks(hyexam, anexam));
English.Add(new Marks(hyexam, anexam));
Maltese.Add(new Marks(hyexam, anexam));
ReligiousStudies.Add(new Marks(hyexam, anexam));
SocialStudies.Add(new Marks(hyexam, anexam));
dictionar.Add(id, (Mathematics)); //dont know how to implement it
}
else
{
Console.WriteLine("id not found");
}
}
}
public class Marks
{
private int hyexam;
private int anexam;
private string id;
public int HYEXAM
{
get { return hyexam; }
set { hyexam = value; }
}
public int ANEXAM
{
get { return anexam; }
set { anexam = value; }
}
public string Id
{
get { return id; }
set { id = value; }
}
public Marks(int hyexam, int anexam)
{
this.hyexam = hyexam;
this.anexam = anexam;
}
public Marks(string id)
{
this.id = id;
}
public double OverallExam()
{
return (0.4 * hyexam) + (0.6 * anexam);
}
}
}
I'd say the main problem is your modelling. You've included the Dictionary<int, List<Marks>> as a field within Student. That means that each Student object has a dictionary. That makes no sense - because the key for the dictionary is meant to be the student ID, right?
It probably makes sense for each Student object to the lists of marks as you've currently got (although not as public fields, IMO). Given that information, do you really need a Dictionary going to the marks at all? Wouldn't it be cleaner to have a Dictionary<int, Student> somewhere (not in the Student class - maybe in a School class?) mapping each student ID to a Student, and you can get the marks from the Student?
Think hard about what you're trying to achieve, and where the data really belongs. In my experience, when you've got the data modelling right, the code usually follows in a clean way.
(I'd also question your Marks class, both in terms of name and design. What are those properties meant to represent? Isn't it really a single mark in an exam? Perhaps ExamResult would be clearer? Does it really need to be mutable?)
I'd agree with Jon that this is definitely a modeling issue (based on the OP's other posts). If you're new to object oriented programming, the first thing you need to do is determine what objects you'll need to create to answer the problem.
What is a Student? A student has a name, id, dob, class year, etc. For every attribute a student has, you need to set up a field or property.
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime DoB { get; set; }
... etc ...
}
What is a Mark? From your descriptions, a Mark has a subject, a mid-exam score, and an annual-exam score.
public class Mark
{
public string Subject { get; set; }
public int MidScore { get; set; }
public int FinalScore { get; set; }
}
What is the relationship between a Student and a Mark? A student has a list of marks associated with them. This is best described with a List<> object.
public class Student() // continued
{
public List<Mark> Marks { get; set; }
}
Once you have the basics set up for your objects, it will be easier to filter out what you DON'T need, and make it much easier to answer your question. :)
My proposal:
Your "Mark" class must have something that identifies the subject (could be an enum called Subject, or an string, or an int with the ID of the subject if you have it stored in database)
Then you could have:
Console.WriteLine("enter id of student to input marks to:");
string id = Console.ReadLine();
var marks = new Dictionary<int, List<Mark>>();
if (UserExists(id))
{
Console.WriteLine("mark for subject1:");
string s1 = Console.ReadLine();
Console.WriteLine("mark for subject2:");
string s2 = Console.ReadLine();
var list = new List<Mark>();
list.Add(new Mark { Subject = SubjectEnum.Subject1, Value = Convert.ToDecimal(s1), });
list.Add(new Mark { Subject = SubjectEnum.Subject2, Value = Convert.ToDecimal(s2), });
marks.Add(Convert.ToInt32(id), list)
}
else
{
Console.WriteLine("id not found");
}
Hope this helps.

Categories