C# Class Members

C# Class Members

Fields and methods inside a class are often referred to as Class Members.


Fields

You have already seen fields in previous examples. They are variables declared directly inside the class body.

Example: Fields

using System;

class Car { // Class members (fields) string color = "red"; int maxSpeed = 200;

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

You can also leave fields uninitialized (blank), and assign values to them when you create the object:

Example: Modifying Fields

using System;

class Car { public string color; public int maxSpeed;

static void Main(string[] args) { Car myCar = new Car(); // Accessing and modifying fields using dot syntax myCar.color = "blue"; myCar.maxSpeed = 250; Console.WriteLine("My car color is " + myCar.color); Console.WriteLine("Max speed is " + myCar.maxSpeed); } }

Notice we used the public keyword before the fields. We will discuss this in detail in the Access Modifiers lesson, but it simply allows the fields to be accessed from outside the class!


Object Methods

Methods are used to perform certain actions. Methods normally belong to a class, and they define how an object of that class behaves.

Just like with fields, you can access methods using the dot syntax (.).

Example: Object Methods

using System;

class Car { public string color = "red";

// A class method public void Honk() { Console.WriteLine("Beep beep!"); }

static void Main(string[] args) { Car myCar = new Car(); // Calling the method myCar.Honk(); } }

This code will output: Beep beep!


Exercise

?

What are variables declared directly inside a class commonly called?