Utilizor
Contact Us

C# Class Members

Fields and methods inside a class.

C# Class Members

Fields and methods inside classes are often referred to as "Class Members".

Use the dot syntax (.) to access methods and fields of a class.

Fields

Variables inside a class are called fields.

Methods

Methods used inside a class are called methods.

Examples

Class Members Example

Accessing fields and methods.

using System;

class MyClass
{
  // Class members
  public string color = "red";        // field
  public int maxSpeed = 200;          // field
  public void fullThrottle()   // method
  {
    Console.WriteLine("The car is going as fast as it can!");
  }

  static void Main(string[] args)
  {
    MyClass myObj = new MyClass();
    Console.WriteLine(myObj.color);
    Console.WriteLine(myObj.maxSpeed);
    myObj.fullThrottle();
  }
}

Multiple Objects Members

Objects hold distinct member values.

using System;

class Car
{
  public string model;
  public string color;
  public int year;

  public void Display()
  {
      Console.WriteLine(model + " " + color + " " + year);
  }

  static void Main(string[] args)
  {
    Car Ford = new Car();
    Ford.model = "Mustang";
    Ford.color = "red";
    Ford.year = 1969;

    Car Opel = new Car();
    Opel.model = "Astra";
    Opel.color = "white";
    Opel.year = 2005;

    Ford.Display();
    Opel.Display();
  }
}