Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

Introduction to classes

  • 2024-08-15
Feedback

In this article

Reference types

A type that is defined as aclass is areference type. At run time, when you declare a variable of a reference type, the variable contains the valuenull until you explicitly create an instance of the class by using thenew operator, or assign it an object of a compatible type created elsewhere, as shown in the following example:

//Declaring an object of type MyClass.MyClass mc = new MyClass();//Declaring another object of the same type, assigning it the value of the first object.MyClass mc2 = mc;

When the object is created, enough memory is allocated on the managed heap for that specific object, and the variable holds only a reference to the location of said object. The memory used by an object is reclaimed by the automatic memory management functionality of the CLR, which is known asgarbage collection. For more information about garbage collection, seeAutomatic memory management and garbage collection.

Declaring classes

Classes are declared by using theclass keyword followed by a unique identifier, as shown in the following example:

//[access modifier] - [class] - [identifier]public class Customer{   // Fields, properties, methods and events go here...}

An optional access modifier precedes theclass keyword. The default access for aclass type isinternal. Becausepublic is used in this case, anyone can create instances of this class. The name of the class follows theclass keyword. The name of the class must be a valid C#identifier name. The remainder of the definition is the class body, where the behavior and data are defined. Fields, properties, methods, and events on a class are collectively referred to asclass members.

Creating objects

Although they're sometimes used interchangeably, a class and an object are different things. A class defines a type of object, but it isn't an object itself. An object is a concrete entity based on a class, and is sometimes referred to as an instance of a class.

Objects can be created by using thenew keyword followed by the name of the class, like this:

Customer object1 = new Customer();

When an instance of a class is created, a reference to the object is passed back to the programmer. In the previous example,object1 is a reference to an object that is based onCustomer. This reference refers to the new object but doesn't contain the object data itself. In fact, you can create an object reference without creating an object at all:

Customer object2;

We don't recommend creating object references that don't refer to an object because trying to access an object through such a reference fails at run time. A reference can refer to an object, either by creating a new object, or by assigning it an existing object, such as this:

Customer object3 = new Customer();Customer object4 = object3;

This code creates two object references that both refer to the same object. Therefore, any changes to the object made throughobject3 are reflected in subsequent uses ofobject4. Because objects that are based on classes are referred to by reference, classes are known as reference types.

Constructors and initialization

The preceding sections introduced the syntax to declare a class type and create an instance of that type. When you create an instance of a type, you want to ensure that its fields and properties are initialized to useful values. There are several ways to initialize values:

  • Accept default values
  • Field initializers
  • Constructor parameters
  • Object initializers

Every .NET type has a default value. Typically, that value is 0 for number types, andnull for all reference types. You can rely on that default value when it's reasonable in your app.

When the .NET default isn't the right value, you can set an initial value using afield initializer:

public class Container{    // Initialize capacity field to a default value of 10:    private int _capacity = 10;}

You can require callers to provide an initial value by defining aconstructor that's responsible for setting that initial value:

public class Container{    private int _capacity;    public Container(int capacity) => _capacity = capacity;}

Beginning with C# 12, you can define aprimary constructor as part of the class declaration:

public class Container(int capacity){    private int _capacity = capacity;}

Adding parameters to the class name defines theprimary constructor. Those parameters are available in the class body, which includes its members. You can use them to initialize fields or anywhere else where they're needed.

You can also use therequired modifier on a property and allow callers to use anobject initializer to set the initial value of the property:

public class Person{    public required string LastName { get; set; }    public required string FirstName { get; set; }}

The addition of therequired keyword mandates that callers must set those properties as part of anew expression:

var p1 = new Person(); // Error! Required properties not setvar p2 = new Person() { FirstName = "Grace", LastName = "Hopper" };

Class inheritance

Classes fully supportinheritance, a fundamental characteristic of object-oriented programming. When you create a class, you can inherit from any other class that isn't defined assealed. Other classes can inherit from your class and override class virtual methods. Furthermore, you can implement one or more interfaces.

Inheritance is accomplished by using aderivation, which means a class is declared by using abase class from which it inherits data and behavior. A base class is specified by appending a colon and the name of the base class following the derived class name, like this:

public class Manager : Employee{    // Employee fields, properties, methods and events are inherited    // New Manager fields, properties, methods and events go here...}

When a class declaration includes a base class, it inherits all the members of the base class except the constructors. For more information, seeInheritance.

A class in C# can only directly inherit from one base class. However, because a base class can itself inherit from another class, a class might indirectly inherit multiple base classes. Furthermore, a class can directly implement one or more interfaces. For more information, seeInterfaces.

A class can be declared asabstract. An abstract class contains abstract methods that have a signature definition but no implementation. Abstract classes can't be instantiated. They can only be used through derived classes that implement the abstract methods. By contrast, asealed class doesn't allow other classes to derive from it. For more information, seeAbstract and Sealed Classes and Class Members.

Class definitions can be split between different source files. For more information, seePartial Classes and Methods.

C# Language Specification

For more information, see theC# Language Specification. The language specification is the definitive source for C# syntax and usage.

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo