O'Reilly logo

C# 5.0 Pocket Reference by Ben Albahari, Joseph Albahari

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

A class is the most common kind of reference type. The simplest possible class declaration is as follows:

class Foo
{
}

A more complex class optionally has the following:

Preceding the keyword class

Attributes and class modifiers. The non-nested class modifiers are public, internal, abstract, sealed, static, unsafe, and partial.

Following YourClassName

Generic type parameters, a base class, and interfaces

Within the braces

Class members (these are methods, properties, indexers, events, fields, constructors, overloaded operators, nested types, and a finalizer)

Fields

A field is a variable that is a member of a class or struct. For example:

class Octopus
{
  string name;
  public int Age = 10;
}

A field may have the readonly modifier to prevent it from being modified after construction. A read-only field can be assigned only in its declaration or within the enclosing type’s constructor.

Field initialization is optional. An uninitialized field has a default value (0, \0, null, false). Field initializers run before constructors, in the order in which they appear.

For convenience, you may declare multiple fields of the same type in a comma-separated list. This is a convenient way for all the fields to share the same attributes and field modifiers. For example:

static readonly int legs = 8, eyes = 2;

Methods

A method performs an action in a series of statements. A method can receive input data from the caller by specifying parameters and output data back to the caller by specifying a return type

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