Classes and Structs

Class declaration syntax:

attributes ? access-modifier ?
new? [ abstract | sealed ]?
class class-name [
: base-class | : interface + | : base-class , interface + ]?
{ class-members }

Struct declaration syntax:

attributes ? access-modifier ?
new?
struct struct-name [ : interface + ]?
{ struct-members }

A class or struct combines data, functions, and nested types into a new type, which is a key building block of C# applications. The body of a class or struct is comprised of three kinds of members: data, function, and type.

Data members

Includes fields, constants, events. The most common data members are fields. Events are a special case, since they combine data and functionality in the class or struct (see Section 2.14).

Function members

Includes methods, properties, indexers, operators, constructors, and destructors. Note that all function members are either specialized types of methods or are implemented with one or more specialized types of methods.

Type members

Includes nested types. Types can be nested to control their accessibility (see Section 2.8).

Here’s an example:

class ExampleClass {
   int x; // data member
   void Foo( ) {} // function member
   struct MyNestedType  {} // type member
}

Differences Between Classes and Structs

Classes differ from structs in the following ways:

  • A class is a reference type; a struct is a value type. Consequently, structs typically represent simple types, whereby value-type semantics are desirable (e.g., assignment copies a value ...

Get C# Essentials 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.