10 KiB
Classes and Objects
Overview
Namespaces
Classes
Object Variables
Access Specifiers
Class Members
Constructors
Value & Reference Types
Enum
Namespaces
Using namespaces helps you to organize the scope of globally available data in your project, meaning that related objects in a well-named namespace makes it easy to import what you need
By default, when creating a new project and adding classes in Visual Studio, everything is contained within a namespace named after your project name
If you need a class or an enum to be accessible from anywhere, create it within that namespace and set it as public
// Note that namespaces can have
// subdirectories, as Models here
namespace MyAwesomeApp.Models
{
public class Student
{
}
}
// This is how you would use the
// Student class in other code
using MyAwesomeApp.Models
Classes
__Classes __ in C# are blueprints for a __type __ of object
We have already used a class named _Program _ when creating a new console application:
You could even create new instances of Program
- If we wanted, we could just write the entire program with thousands of lines of code on one page inside the main function
- This kind of program would of course be impossible to work with within a group or organization:
- No one should have to scroll through tens of thousands of lines of code to find that one line that causes problems…
- At least make them browse through hundreds of classes instead :)
- Classes provide __encapsulation __ which result in shorter files , less repetitive code and overall better readability
Creating a Class
You can create a new class by writing
class Student
{
}
Create variables inside a class just like before inside the Program class:
class Student
{
int id;
string name;
}
❕
Variables declared directly inside classes are called fields.
Referencing a Class
New instances of a class can be created with the __new __ keyword
All instances of a class have exactly the same fields and methods, but they can have different values
In the following example a few __objects __ of __type __ Student are created
However, these objects have no functionality yet
namespace MyAwesomeApp
{
class Student
{
}
class Program
{
static void Main(string[] args)
{
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
}
}
}
Object Variables
The variables inside of an object can be accessed with the '.' operator
However, the following syntax results in an error:
Student class: | Program class: |
---|---|
class Student{ int id;} | class Program{static void Main(string[] args){ Student student = new Student(); student.id = 12345678;}} |
Let's fix the previous example by changing the _ _ access specifier of the 'id' variable to public :
Student class: | Program class: |
---|---|
class Student{ public int id;} | class Program{static void Main(string[] args){ Student student = new Student(); student.id = 12345678;}} |
The value of the variable 'id' of the object 'student' is now 12345678
Access Specifiers
Access specifiers can be used to get additional level of protection inside classes
Variables specified with __private __ are accessible only inside the containing class
Variables specified with __public __ are accessible outside of the class
The __default __ access for any variable is private!
class Student
{
int id; // Accessible only inside the class
private string name; // Accessible only inside the class
public string address; // Accessible everywhere within the namespace
}
Continuing on the class in the previous slide, if we follow the 'student' variable with a dot, VS intellisense will only suggest the 'address' variable, because it was the only public variable of the 'Student' class
Classes - Example
class Student
{
public int id;
public string name;
}
class Program
{
static void Main(string[] args)
{
Student student1 = new Student();
Student student2 = new Student();
student1.id = 22225555;
student1.name = "Johannes Kantola";
student2.id = 44441111;
student2.name = "Rene Orosz";
Console.WriteLine(student1.name); // Outputs Johannes Kantola
}
}
Exercise 1
Create a console application that has a class User which contains two fields: string userName and string password
Create a main loop where the user is asked repeatedly for a new username and password. The values are stored to a new User instance and that instance is saved to a list of users
Print all stored usernames every time a new user is created
Class Methods
As mentioned in the previous lecture, we can create methods inside of our classes:
class Person
{
public string firstName;
public string lastName;
public string FullName()
{
return firstName + " " + lastName;
}
}
class Program
{
static void Main(string[] args)
{
Person someDude = new Person();
someDude.firstName = "Johannes";
someDude.lastName = "Kantola";
Console.WriteLine(someDude.FullName());
// Outputs Johannes Kantola
}
}
If the method is public, it can be called from outside of the class
Constructors
Constructors are class methods which are called once the object is initialized
Constructors are created by creating a class method with the same name as the class:
class User
{
public User()
{
Console.WriteLine
("New user created!");
}
}
class Program
{
static void Main(string[] args)
{
User user = new User();
// Outputs "New user created!"
}
}
❕
In Visual Studio, just write "ctor" and press tab twice to quickly create a constructor
Constructors with Parameters
You can pass in parameters to the constructor at initialization:
class Car
{
private string model;
private int year;
private int doors;
public Car(string modelName, int modelYear)
{
model = modelName;
year = modelYear;
doors = 5;
}
}
class Program
{
static void Main(string[] args)
{
Car lada = new Car("Niva", 1984);
Car ford = new Car("Focus", 2010);
// Both cars have 5 doors by default
}
}
Exercise 2
Create a console application with a class Animal, that contains
two strings: name and sound, and
a method Greet() that prints " name says sound !"
Create a few animals with different names and sounds
Call their greet methods from the main program
Properties
When working with C#, you will eventually see __properties __ being used at some point
Properties allow the manipulation of private fields from outside of the class:
class User
{
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
}
class Program
{
static void Main(string[] args)
{
User admin = new User();
admin.Id = 12345678;
Console.WriteLine(admin.Id);
// This outputs 12345678
}
}
Auto Properties
Auto properties are a shorthand version of the same:
class User
{
public int Id { get; set; }
}
class Program
{
static void Main(string[] args)
{
User admin = new User();
admin.Id = 12345678;
Console.WriteLine(admin.Id);
// This outputs 12345678
}
}
❕
In Visual Studio, just write "prop" and press tab twice to quickly create an auto property
Properties
- Why use properties if we could just use public fields?
- We don't always want to expose the exact same variable that is used inside of the class, to outside
- Properties allow class fields to be read-only or write-only :
- public int Id { get; } // This field is read-onlypublic int Password { private get; set; } // This field is write-only
- Properties are supported in interfaces , while fields are not
- We will cover interfaces later
- There are a bunch of other reasons, but they are outside the scope of this course
Lets say we have a variable in our class which is queued for calculating something important Now some other class changes that variable -> Problem
Value and Reference Types
- If this program is executed, what will be the output?
- int, double, char and other primitive data types are of value type
- The variable stores the actual data in memory
- Every copy of the variable will be stored in a separate location
- class Program{ static void Main(string[] args) { int user = 1; int otherUser = user; user = 2; Console.WriteLine( "Value of otherUser: " + otherUser); }}
- When this program is executed, what will be the output?
- Strings, Arrays and Classes are of __reference type __
- The variable stores the address of the data being stored in memory
- Every copy of the variable points to the same address
class Program
{
static void Main(string[] args)
{
User user = new User();
user.id = 1;
User otherUser = user;
user.id = 2;
Console.WriteLine(
"Value of otherUser.id: " + otherUser.id);
}
}
class User
{
public int id;
}
Location in memory
int userId = 42;
int otherUserId = userId;
42 |
---|
42 |
Changing the value in the object will affect all variables referencing it!
points to |
---|
points to |
User user = new User(42);
User otherUser = user;
user { id = 42 } |
---|
Exercise 3
Classes and enums can be created to a separate file. To quickly create a new class, right mouse click you project (not solution) name in solution explorer -> Add -> Class… Name your class "TestClass"
Back in your main method, create an instance of TestClass. The compiler should not give any errors.
Now rename the namespace that your TestClass is in, to "TestNamespace". Go back to your main method. The TestClass instantiation should not work anymore. Try to fix that without going back to TestClass.
Exercise 4
Modify previous solution by using methods and class.