C# class field

In this chapter you will learn:

  1. What is a class field
  2. Syntax to create a new field
  3. A class with fields
  4. How to declare more than one fields

Description

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

Syntax

The field definition has the following syntax.


class className{/*from w  ww.  j av  a2 s . c om*/

  fieldAccessor  fieldType fieldName;

}
  • fieldAccessor specifies the access,
  • fieldType specifies the type of variable, and
  • fieldName is the variable's name.

Example

A class with fields


class Person //from   w ww .  j a  v a 2 s . co m
{ 
   string name; 
   public int Age = 10; 
} 

Example 2

For the fields with the same type we can declare them together.


class Rectangle{
   int Width, Height;
}

They can share the same modifiers as well.


class Rectangle{
   public int Width, Height;

}

Next chapter...

What you will learn in the next chapter:

  1. Field initialization and default value
  2. Default value for each type
  3. Example for C# Field default value
Home »
  C# Tutorial »
    C# Types »
      C# Class Field
C# class field
C# Field default value
C# field initialization
C# Constant
C# Read only field
C# Static Fields