A class can have a member variable that is an instance of another class. this is called

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.

Members (C# Programming Guide)

  • Article
  • 09/17/2021
  • 2 minutes to read

In this article

Classes and structs have members that represent their data and behavior. A class's members include all the members declared in the class, along with all members (except constructors and finalizers) declared in all classes in its inheritance hierarchy. Private members in base classes are inherited but are not accessible from derived classes.

The following table lists the kinds of members a class or struct may contain:

MemberDescription
Fields Fields are variables declared at class scope. A field may be a built-in numeric type or an instance of another class. For example, a calendar class may have a field that contains the current date.
Constants Constants are fields whose value is set at compile time and cannot be changed.
Properties Properties are methods on a class that are accessed as if they were fields on that class. A property can provide protection for a class field to keep it from being changed without the knowledge of the object.
Methods Methods define the actions that a class can perform. Methods can take parameters that provide input data, and can return output data through parameters. Methods can also return a value directly, without using a parameter.
Events Events provide notifications about occurrences, such as button clicks or the successful completion of a method, to other objects. Events are defined and triggered by using delegates.
Operators Overloaded operators are considered type members. When you overload an operator, you define it as a public static method in a type. For more information, see Operator overloading.
Indexers Indexers enable an object to be indexed in a manner similar to arrays.
Constructors Constructors are methods that are called when the object is first created. They are often used to initialize the data of an object.
Finalizers Finalizers are used very rarely in C#. They are methods that are called by the runtime execution engine when the object is about to be removed from memory. They are generally used to make sure that any resources which must be released are handled appropriately.
Nested Types Nested types are types declared within another type. Nested types are often used to describe objects that are used only by the types that contain them.

See also

  • C# Programming Guide
  • Classes

Feedback

Submit and view feedback for

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.

Fields (C# Programming Guide)

  • Article
  • 07/30/2022
  • 4 minutes to read

In this article

A field is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type.

A class or struct may have instance fields, static fields, or both. Instance fields are specific to an instance of a type. If you have a class T, with an instance field F, you can create two objects of type T, and modify the value of F in each object without affecting the value in the other object. By contrast, a static field belongs to the type itself, and is shared among all instances of that type. You can access the static field only by using the type name. If you access the static field by an instance name, you get CS0176 compile-time error.

Generally, you should use fields only for variables that have private or protected accessibility. Data that your type exposes to client code should be provided through methods, properties, and indexers. By using these constructs for indirect access to internal fields, you can guard against invalid input values. A private field that stores the data exposed by a public property is called a backing store or backing field.

Fields typically store the data that must be accessible to more than one type method and must be stored for longer than the lifetime of any single method. For example, a type that represents a calendar date might have three integer fields: one for the month, one for the day, and one for the year. Variables that aren't used outside the scope of a single method should be declared as local variables within the method body itself.

Fields are declared in the class or struct block by specifying the access level of the field, followed by the type of the field, followed by the name of the field. For example:

public class CalendarEntry
{

    // private field (Located near wrapping "Date" property).
    private DateTime _date;

    // Public property exposes _date field safely.
    public DateTime Date
    {
        get
        {
            return _date;
        }
        set
        {
            // Set some reasonable boundaries for likely birth dates.
            if (value.Year > 1900 && value.Year <= DateTime.Today.Year)
            {
                _date = value;
            }
            else
            {
                throw new ArgumentOutOfRangeException("Date");
            }
        }
    }

    // public field (Generally not recommended).
    public string? Day;

    // Public method also exposes _date field safely.
    // Example call: birthday.SetDate("1975, 6, 30");
    public void SetDate(string dateString)
    {
        DateTime dt = Convert.ToDateTime(dateString);

        // Set some reasonable boundaries for likely birth dates.
        if (dt.Year > 1900 && dt.Year <= DateTime.Today.Year)
        {
            _date = dt;
        }
        else
        {
            throw new ArgumentOutOfRangeException("dateString");
        }
    }

    public TimeSpan GetTimeSpan(string dateString)
    {
        DateTime dt = Convert.ToDateTime(dateString);

        if (dt.Ticks < _date.Ticks)
        {
            return _date - dt;
        }
        else
        {
            throw new ArgumentOutOfRangeException("dateString");
        }
    }
}

To access a field in an instance, add a period after the instance name, followed by the name of the field, as in instancename._fieldName. For example:

CalendarEntry birthday = new CalendarEntry();
birthday.Day = "Saturday";

A field can be given an initial value by using the assignment operator when the field is declared. To automatically assign the Day field to "Monday", for example, you would declare Day as in the following example:

public class CalendarDateWithInitialization
{
    public string Day = "Monday";
    //...
}

Fields are initialized immediately before the constructor for the object instance is called. If the constructor assigns the value of a field, it will overwrite any value given during field declaration. For more information, see Using Constructors.

Note

A field initializer cannot refer to other instance fields.

Fields can be marked as public, private, protected, internal, protected internal, or private protected. These access modifiers define how users of the type can access the fields. For more information, see Access Modifiers.

A field can optionally be declared static. Static fields are available to callers at any time, even if no instance of the type exists. For more information, see Static Classes and Static Class Members.

A field can be declared readonly. A read-only field can only be assigned a value during initialization or in a constructor. A static readonly field is similar to a constant, except that the C# compiler doesn't have access to the value of a static read-only field at compile time, only at run time. For more information, see Constants.

A field can be declared required. A required field must be initialized by the constructor, or by an object initializers when an object is created. You add the System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute attribute to any constructor declaration that initializes all required members.

The required modifier can't be combined with the readonly modifier on the same field.

C# language specification

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

See also

  • C# Programming Guide
  • The C# type system
  • Using Constructors
  • Inheritance
  • Access Modifiers
  • Abstract and Sealed Classes and Class Members

Feedback

Submit and view feedback for

What are the variables that are shared by every instances of a class called?

Class variables, often referred to as static variables, are shared across all instances of a class. Every instance points to same value and any changes are seen by all.

What happens when we create an instance of a class?

you declare an instance variable. Every time you create an instance of a class, the runtime system creates one copy of each the class's instance variables for the instance. You can access an object's instance variables from an object as described in Using Objects.

Which type of function is not a member of a class but has access to the private members of the class?

A friend function is a function that isn't a member of a class but has access to the class's private and protected members.

What is the difference between a class and an instance of a class quizlet?

A class describes a data type. An instance of a class is an object of the data type that exists in memory.