C# - Classes


When you define a class, you are essentially creating a blueprint for a data type. This does not define any data, but it does define the meaning of the class name.

That is, what a class object is made of and what operations can be performed on it. Objects are subclasses of a class. Members of a class are the methods and variables that make up the class.

A class definition begins with the keyword class, followed by the class name, and ends with a pair of curly brackets.

The general form of a class definition is as follows:

public class MyClass 
{ 
    // Fields (variables) 
    private int myField; 

    // Properties 
    public int MyProperty { get; set; } 

    // Constructor 
    public MyClass(int field, int property) 
    { 
        myField = field; 
        MyProperty = property; 
    } 

    // Methods 
    public void MyMethod() 
    { 
        // Code for the method 
    }
}

Fields

Fields are variables that are part of a class. They specify the qualities or data that an object of that class will contain. MyField is a private field in the example above.

Constructor

Constructors are special methods used for initializing objects of a class. They have the same name as the class and are invoked when an instance of the class is created.

A default constructor has no parameters but a constructor can have parameters if necessary. These constructors are known as parameterized constructors. As seen in the following example, this technique allows you to assign an object initial value at the time of its creation.

using System;
namespace LineApplication {
   class Line {
      private double length;   // Length of a line

      public Line() {
         Console.WriteLine("Object is being created");
      }
      
      static void Main(string[] args) {
         Line line = new Line();    

         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength());
         Console.ReadKey();
      }
   }
}

Access Modifiers

Access modifiers define the visibility of classes, fields, properties, and methods:

public: Accessible from any class.

private: Accessible only within the same class.

protected: Accessible within the same class or derived classes.

internal: Accessible within the same assembly.

protected internal: Accessible within the same assembly or derived classes.