Home

Characteristics of Members of a Class

 

Constants

Unlike C/C++, in C#, you can create a constant variable in a class. As done in Lesson 2 when studying variables, to declare a constant variable, type the const keyword to the left of the variable. Once again, when declaring a constant, you must initialize it with an appropriate constant value.

this Instance

If a class contains fields and methods, the (non-static) field members are automatically available to the method(s) of the class, even fields that are private. When accessing a field or a method from another method of the class, to indicate that the member you are accessing belongs to the same class, you can precede it with the this member and the period operator. Here are examples:

public class House
{
    public char PropertyType;
    public uint Bedrooms;

    public void Display()
    {
        Console.WriteLine("=//= Altair Realty =//=");
        Console.WriteLine("Properties Inventory"); ;
        Console.Write("Property Type:  ");
        Console.WriteLine(this.PropertyType);
        Console.Write("Bedrooms:       ");
        Console.WriteLine(this.Bedrooms);
    }
}

When using the this member variable (in C/C++, it is a pointer), you can access any member of a class within any method of the same class. There are rules you must observe when using this:

  • The this member can never be declared: it is automatically implied when you create a class
  • this cannot be used in a class A to access a member of class B. The following will cause an error:
     
    class Program
    {
        static void Main()
        {
            House property = new House();
    
            property.PropertyType = 'S';
            property.Bedrooms = 4;
    
            this.property.Display();
        }
    }
  • this cannot be used in a static method

Practical Learning Practical Learning: Using this

  1. Access the DepartmentStore.cs file and, to use this, change the class as follows:
     
    using System;
    
    class DepartmentStore
    {
        public long StockNumber;
        public char Category;
        public string ItemName;
        public decimal UnitPrice;
    
        public void CreateItem()
        {
            this.StockNumber = 792475;
            this.Category = 'M';
            this.ItemName = "Lightweight Jacket";
            this.UnitPrice = 185.00M;
        }
    
        public void ShowItem()
        {
            Console.WriteLine("Department Store");
            Console.Write("Stock #:    ");
    	Console.WriteLine(this.StockNumber);
            Console.Write("Category:   ");
    	Console.WriteLine(this.Category);
            Console.Write("Name:       ");
    	Console.WriteLine(this.ItemName);
            Console.Write("Unit Price: ");
    	Console.WriteLine(this.UnitPrice);
        }
    }
  2. Execute the application to see the result
  3. Close the DOS window
 

Previous Copyright © 2006 FunctionX, Inc.