How to declare and display variable in C#? - c#

I have a class library that has two constructor. The first constructor accepts two arguments and the second accepts three. Below is my class library code. Easier to put the code than try to explain it.
public class Student
{
public string name;
public string course;
public MyDate bday;
public Student(string name, string course)
{
this.name = name;
this.course = course;
}
public Student(string name, string course, MyDate bday)
{
this.name = name;
this.course = course;
this.bday = bday;
}
The MyDate library has another constructor that accepts three arguments which would be the date, month and year of the birthday. Now I have a form which contains 3 listbox and on the third listbox I will be displaying the birthdays. I declare the birthdays in the code (just like i showed below) now I'm having problem on how to display it.
MyDate[] bd = new MyDate[5] { new MyDate(29, 3, 1990),
new MyDate(30, 1, 1988),
new MyDate(9, 6, 1987),
new MyDate(2, 4, 1989),
new MyDate(17, 8, 1986),
};
Student[] s = new Student[5] { new Student("John", "BSCS"),
new Student("Paul", "BSIT"),
new Student("George", "BSCP"),
new Student("Jane", "BSCS"),
new Student("May", "BSIT")
};
Can anyone please tell me how i should do this? I tried this Student[] s = new Student[5] { new Student("John", "BSCS", bd[0]) and so on but it gives me error. I know this is a beginners question and I am a beginner. Thank you.
Edit:
The initialization was done in the form1.cs.

Based on the error, you're trying to initialize a field (member data) with the another non-static field; you can't do that. The simplest fix is to move your initialization code to the constructor.
So your code would be
partial class Form
{
MyDate[] bd = ...;
Student[] s;
public Form()
{
InitializeComponent();
s = ...;
}
}
You also should chain your Student constructors, and why do you have your own date class instead of using System.DateTime? You also should use automatic properties rather than public fields.
public class Student
{
public string name { get; set; }
public string course { get; set; }
public DateTime bday { get; set; }
public Student(string name, string course)
{
this.name = name;
this.course = course;
}
public Student(string name, string course, DateTime bday)
: this(name, course)
{
this.bday = bday;
}
}

You can see here:
You should set the field initializer under your constructor.
class TestClass
{
MyDate[] bd;
Student[] s;
public TestClass()
{
bd = new MyDate[5] { new MyDate(29, 3, 1990),
new MyDate(30, 1, 1988),
new MyDate(9, 6, 1987),
new MyDate(2, 4, 1989),
new MyDate(17, 8, 1986),
};
s = new Student[5] { new Student("John", "BSCS"),
new Student("Paul", "BSIT"),
new Student("George", "BSCP"),
new Student("Jane", "BSCS"),
new Student("May", "BSIT")
};
}
}
It's basically saying that you need to set this variable in the constructor.

Here's one way to do the same thing:
Student[] s = new Student[5];
s[0] = new Student("John", "BSCS", bd[0]);
s[1] = new Student("Bill", "BSCS", bd[1]);

I must be missing something here, because i am not able to recreate the error discussed here. The following code just works fine for me (.NET 4.0)
public class MyDate
{
public MyDate(int date, int month, int year)
{
this.date = date;
this.month = month;
this.year = year;
}
public int date;
public int month;
public int year;
}
public class Student
{
public string name;
public string course;
public MyDate bday;
public Student(string name, string course)
{
this.name = name;
this.course = course;
}
public Student(string name, string course, MyDate bday)
{
this.name = name;
this.course = course;
this.bday = bday;
}
}
..and i am able to initialize the objects like below..
MyDate[] bd = new MyDate[5]
{
new MyDate(29, 3, 1990),
new MyDate(30, 1, 1988),
new MyDate(9, 6, 1987),
new MyDate(2, 4, 1989),
new MyDate(17, 8, 1986),
};
Student[] s = new Student[5]
{
new Student("John", "BSCS", bd[0]),
new Student("Paul", "BSIT", bd[1]),
new Student("George", "BSCP", bd[2]),
new Student("Jane", "BSCS", bd[3]),
new Student("May", "BSIT", bd[4])
};
When exactly are you getting this error?

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

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;
}
}
}

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

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.

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.

Is it possible to bind an array to DataGridView control?

I have an array, arrStudents, that contains my students' age, GPA, and name like so:
arrStudents[0].Age = "8"
arrStudents[0].GPA = "3.5"
arrStudents[0].Name = "Bob"
I tried to bind arrStudents to a DataGridView like so:
dataGridView1.DataSource = arrStudents;
But the contents of the array do NOT show up in the control. Am I missing something?
As with Adolfo, I've verified that this works. There is nothing wrong in the code shown, so the problem must be in the code you aren't showing.
My guess: Age etc are not public properties; either they are internal or they are fields, i.e. public int Age; instead of public int Age {get;set;}.
Here's your code working for both a well-typed array and an array of anonymous types:
using System;
using System.Linq;
using System.Windows.Forms;
public class Student
{
public int Age { get; set; }
public double GPA { get; set; }
public string Name { get; set; }
}
internal class Program
{
[STAThread]
public static void Main() {
Application.EnableVisualStyles();
using(var grid = new DataGridView { Dock = DockStyle.Fill})
using(var form = new Form { Controls = {grid}}) {
// typed
var arrStudents = new[] {
new Student{ Age = 1, GPA = 2, Name = "abc"},
new Student{ Age = 3, GPA = 4, Name = "def"},
new Student{ Age = 5, GPA = 6, Name = "ghi"},
};
form.Text = "Typed Array";
grid.DataSource = arrStudents;
form.ShowDialog();
// anon-type
var anonTypeArr = arrStudents.Select(
x => new {x.Age, x.GPA, x.Name}).ToArray();
grid.DataSource = anonTypeArr;
form.Text = "Anonymous Type Array";
form.ShowDialog();
}
}
}
This works for me:
public class Student
{
public int Age { get; set; }
public double GPA { get; set; }
public string Name { get; set; }
}
public Form1()
{
InitializeComponent();
Student[] arrStudents = new Student[1];
arrStudents[0] = new Student();
arrStudents[0].Age = 8;
arrStudents[0].GPA = 3.5;
arrStudents[0].Name = "Bob";
dataGridView1.DataSource = arrStudents;
}
Or less redundant:
arrStudents[0] = new Student {Age = 8, GPA = 3.5, Name = "Bob"};
I'd also use a List<Student> instead of an array since it will have to grow most likely.
Is That what you're doing too?

Categories