O'Reilly logo

C# Essentials by Peter Drayton, Ben Albahari, Brad Merrill

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

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

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