O'Reilly logo

C# 2008 Programmer's Reference by Wei-Meng Lee

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required