Chapter 4. Classes and Objects
One of the most important topics in C# programming — in fact, the cornerstone of .NET development — is classes and objects.
Classes are essentially templates from which you create objects. In C# .NET programming, everything you deal with involves classes and objects. This chapter assumes that you already have a basic grasp of object-oriented programming. It tackles:
How to define a class
How to create an object from a class
The different types of members in a class
The root of all objects —
System.Object
Classes
Everything you encounter in .NET in based on classes. For example, you have a Windows Forms application containing a default form called Form1. Form1
itself is a class that inherits from the base class System.Windows.Forms.Form
, which defines the basic behaviors that a Windows Form should exhibit:
using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Project1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } } }
Within the Form1
class, you code in your methods. For example, to display a "Hello World
" message when the form is loaded, add the following statement in the Form1_Load()
method:
public partial class Form1 : Form { public Form1() { InitializeComponent(); } protected override void OnLoad(EventArgs e) { MessageBox.Show("Hello World!"); } }
The following sections walk you through the basics of defining your own class and the various members you can have in ...
Get C# 2008 Programmer's Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.