C#
Summary - Classes
Combine fields, properties and methods to write a User class.
Classes summary
In five lessons you learned the C# class basics. class is the template, new creates an instance. Fields hold data, properties provide smart access with get/set. Methods define behavior, this refers to the current instance.
With an object initializer you can set multiple properties in one line. Now you will combine all of this in two mini tasks: first design a Task class, then update its status property.
Exercise Define the Task class
Define a Task class with public string Title { get; set; } and public bool Done { get; set; } auto-properties. Inside Main create an instance using an object initializer with Title = "Homework" and print Title.
Show example solution
Add Title and Done properties to Task. In Main write Task t = new Task { Title = "Homework" }; Console.WriteLine(t.Title);
Example solution:
using System;
class Task
{
public string Title { get; set; }
public bool Done { get; set; }
}
class Program
{
static void Main()
{
Task t = new Task { Title = "Homework" };
Console.WriteLine(t.Title);
}
}
Exercise Update the Task status
The Task class below is given. Inside Main create an instance with the initializer Title = "Homework", then set t.Done = true; and print Done.
Show example solution
Set the status with t.Done = true;. Print it with Console.WriteLine(t.Done);.
Example solution:
using System;
class Task
{
public string Title { get; set; }
public bool Done { get; set; }
}
class Program
{
static void Main()
{
Task t = new Task { Title = "Homework" };
t.Done = true;
Console.WriteLine(t.Done);
}
}
Classes complete
You now master the C# class basics. class is the template, new creates an instance. Fields hold data, properties provide smart access, methods define behavior. this saves you in shadowing, and the object initializer keeps code short.
In the next group you will learn constructors: special methods that run automatically when an object is created and set its starting values.
Test yourself
-
What is an object initializer?
- A class definition
- A syntax to set properties after new
- A method call
- A type of loop
Show answer
A syntax to set properties after new — Correct. An initializer has the form new Type { Property = value }.
-
Complete the assignment with this
public void SetTitle(string title) { this.title = ____; }
Show answer
public void SetTitle(string title) { this.title = title; }
Next lesson: Constructor