Working with Classes and Objects
1namespace GradeBook
2{
3 class Book
4 {
5 public void AddGrade(double grade)
6 {
7 // do something with the passed grade
8 }
9 }
10}
1using System.Collections.Generic;
2
3namespace GradeBook
4{
5 class Book
6 {
7 public void AddGrade(double grade)
8 {
9 grades.Add(grade);
10 }
11
12 // field definition
13 List<double> grades = new List<double>(); // can't use var or implicit typing
14 }
15}
System.NullReferenceException: Object reference not set to an instance of an object.
You’re using a field or variable that has not been properly initialized
Constructor constructs objects.. It handles initialization of the object. It comes with every class by default, and you can change it’s behaviour by explicitly defining it
1// CONSTRUCTOR
2public Book()
3{
4 grades = new List<double>();
5}
1namespace GradeBook
2{
3 class Book
4 {
5 // CONSTRUCTOR
6 // it must be the same name as the class, must be public
7 public Book(string name)
8 {
9 grades = new List<double>();
10 this.name = name; //referring to our class field with this.name to differentiate it from parameter 'name'
11 }
12
13 // METHOD
14 public void AddGrade(double grade)
15 {
16 grades.Add(grade);
17 }
18
19 // FIELD
20 List<double> grades;
21 }
22}
Access modifier determine access to members of the class
public
means code outside of the Class can have access to this member (method, field)private
is default. can only be used inside the Class by other members of the ClassTypically, you don’t want to expose the state of the class to outside elements. This prevents invalid values and let’s you change the implementation details later, in the background.
Yep, this
is in C#, it’s and Object oriented language, duh. this
refers to values within the class. It’s implicitly used, so you only ever need to be specified if you’re using the same parameter name as your field name..
static
class and members can not be instantiated. They will not be passed on to the object instance. static
members are part of the Class, but not part of the resulting object.
Consequently, you can only reference static members using the type name and not via object reference (a variable reference to the object)
1var grades = new Book("Sam's Gradebook");
2
3book.AddGrade() // object reference
4Book.AddGrade() // static method referencing Class
changing static
values changes them on the Class itself. be very conservative when using them. kind of not needed much in OOP..
Console.WriteLine()
is static, since you don’t need to instantiate it in order to use it.