Home

Classes Combinations

 

Class Nesting

A class can be created inside of another class. A class created inside of another is referred to as nested. To nest a class, simply create it as you would any other. Here is an example of a class called Inside that is nested in a class called Outside:

public class Outside
{
	public class Inside
	{
	}
}

In the same way, you can nest as many classes as you wish in another class and you can nest as many classes inside of other nested classes if you judge it necessary. Just as you would manage any other class so can you exercise control on a nested class. For example, you can declare all necessary fields, properties, or methods in the nested class or in the nesting class. When you create one class inside of another, there is no special programmatic relationship between both classes:  just because a class is nested does not mean that the nested class has immediate access to the members of the nesting class. They are two different classes and they can be used separately as you judge it necessary. 

The name of a nested class is not "visible" outside of the nesting class. To access a nested class outside of the nesting class, you must qualify the name of the nested anywhere you want to use it. For example, if you want to declare an Inside variable somewhere in the program but outside of Outside, you must qualify its name. Here is an example:

using System;

public class Outside
{
	public class Inside
	{
		public Inside()
		{
			Console.WriteLine(" -= Inside =-");
		}
	}

	public Outside()
	{
		Console.WriteLine(" =- Outside -=");
	}
}

class Exercise
{
	static void Main()
	{
		Outside Recto = new Outside();
		Outside.Inside Ins = new Outside.Inside();
	}
}

This would produce:

=- Outside -=
 -= Inside =-

Because there is no programmatically privileged relationship between a nested class and its "container" class, if you want to access the nested class in the nesting class, you can use its static members. In other words, if you want, you can declare static all members of the nested class that you want to access in the nesting class. Here is an example:

using System;

public class Outside
{
	public class Inside
	{
		public static string InMessage;

		public Inside()
		{
			Console.WriteLine(" -= Insider =-");
			InMessage = "Sitting inside while it's raining";
		}

		public static void Show()
		{
	Console.WriteLine("Show me the wonderful world of C# Programming");
		}
	}

	public Outside()
	{
		Console.WriteLine(" =- The Parent -=");
	}

	public void Display()
	{
		Console.WriteLine(Inside.InMessage);
		Inside.Show();
	}
}

class Exercise
{
	static void Main()
	{
		Outside Recto = new Outside();
		Outside.Inside Ins = new Outside.Inside();

		Recto.Display();
	}
}

In the same way, if you want to access the nesting class in the nested class, you can go through the static members of the nesting class. To do this, you can declare static all members of the nesting class that you want to access in the nested class. Here is an example:

using System;

public class Outside
{
	public class Inside
	{
		public static string InMessage;

		public Inside()
		{
			Console.WriteLine(" -= Insider =-");
			InMessage = "Sitting inside while it's raining";
		}

		public static void Show()
		{
	Console.WriteLine("Show me the wonderful world of C# Programming");
		}

		public void FieldFromOutside()
		{
			Console.WriteLine(Outside.OutMessage);
		}
	}

	private static string OutMessage;

	public Outside()
	{
		Console.WriteLine(" =- The Parent -=");
		OutMessage = "Standing outside! It's cold and raining!!";
	}

	public void Display()
	{
		Console.WriteLine(Inside.InMessage);
		Inside.Show();
	}
}

class Exercise
{
	static void Main()
	{
		Outside Recto = new Outside();
		Outside.Inside Ins = new Outside.Inside();

		Recto.Display();
		Console.WriteLine();
		Ins.FieldFromOutside();
	}
}

This would produce:

=- The Parent -=
 -= Insider =-
Sitting inside while it's raining
Show me the wonderful world of C# Programming

Standing outside! It's cold and raining!!

Instead of static members, if you want to access members of a nested class in the nesting class, you can first declare a variable of the nested class in the nesting class. In the same way, if you want to access members of a nesting class in the nested class, you can first declare a variable of the nesting class in the nested class. Here is an example:

using System;

public class Outside
{
	// A member of the nesting class
	private string OutMessage;

	// The nested class
	public class Inside
	{
		// A field in the nested class
		public string InMessage;

		// A constructor of the nested class
		public Inside()
		{
			Console.WriteLine(" -= Insider =-");
			this.InMessage = "Sitting inside while it's raining";
		}

		// A method of the nested class
		public void Show()
		{
			// Declare a variable to access the nesting class
			Outside outsider = new Outside();
			Console.WriteLine(outsider.OutMessage);
		}
	} // End of the nested class

	// A constructor of the nesting class
	public Outside()
	{
		this.OutMessage = "Standing outside! It's cold and raining!!";

		Console.WriteLine(" =- The Parent -=");
	}

	// A method of the nesting class
	public void Display()
	{
		Console.WriteLine(insider.InMessage);
	}

	// Declare a variable to access the nested class
	Inside insider = new Inside();
}

class Exercise
{
	static void Main()
	{
		Outside Recto = new Outside();
		Outside.Inside Ins = new Outside.Inside();

		Ins.Show();
		Recto.Display();
	}
}

This would produce:

-= Insider =-
 =- The Parent -=
 -= Insider =-
 -= Insider =-
 =- The Parent -=
Standing outside! It's cold and raining!!
Sitting inside while it's raining

A Class as a Field

Just like any of the variables we have used so far, you can make a class or a structure a member variable of another class. To use a class in your own class, of course you must have that class. You can use one of the classes already available in C# or you can first create your own class. Here is an example of a class:

class Point
{
    public short x;
    public short y;
}

A field is a member variable created from another class instead of a primitive type. To use one class as a member variable of another class, simply declare its variable as you would proceed with any of the member variables we have declared so far. Here is an example:

public class Point
{
    public short x;
    public short y;
}

public class CoordinateSystem
{
    public Point Start;
}

After a class has been declared as a member variable of another class, it can be used regularly. Because the member is a class, declared as a reference, there are some rules you must follow to use it. After declaring the member variable, you must make sure you have allocated memory for it. You must also make sure that the variable is initialized appropriately before it can be used; otherwise you would receive an error when compiling the program.

Practical Learning Practical Learning: Using a Class as a Field

  1. Start a new Console Application and name it ElectonicStore1
  2. To create a new class, in the Solution Explorer, right-click the name of the project, position the mouse on Add and click Class...
  3. Set the Name to StoreItem and click Add
  4. Complete the file as follows:
     
    using System;
    
    namespace ElectronicStore1
    {
        public class StoreItem
        {
            private long nbr;
            private char cat;
            private string mk;
            private string mdl;
            private double price;
    
            public long GetItemNumber()
            {
            return nbr;
            }
    
            public void SetItemNumber(long number)
            {
                this.nbr = number;
            }
    
            public char GetCategory()
            {
                return cat;
            }
    
            public void SetCategory(char category)
            {
                this.cat = category;
            }
    
            public string GetMake()
            {
                return mk;
            }
    
            public void SetMake(string make)
            {
                this.mk = make;
            }
    
            public string GetModel()
            {
                return mdl;
            }
    
            public void SetModel(string model)
            {
                this.mdl = model;
            }
    
            public double GetUnitPrice()
            {
                return price;
            }
    
            public void SetUnitPrice(double unitPrice)
            {
                this.price = unitPrice;
            }
        }
    }
  5. Access the Program.cs file and change it as follows:
     
    using System;
    
    namespace ElectronicStore1
    {
        class Program
        {
            static void Main()
            {
                string strTitle1 = "=-= Nearson Electonics =-=\n";
                string strTitle2 = "******* Store Items ******";
    
                Console.WriteLine();
            }
        }
    }
  6. Save all

Returning a Class From a Method

Like a value from a regular type, you can return a class value from a method of a class. To do this, you can first declare the method and specify the class as the return type. Here is an example:

public class Point
{
    public short x;
    public short y;
}

public class CoordinateSystem
{
    private Point Start;
    private Point End;

    public Point GetThePoint()
    {
    }
}

After implementing the method, you must return a value that is conform to the class, otherwise you would receive an error when compiling the application. You can proceed by declaring a variable of the class in the body of the method, initializing the variable, and then returning it. Here is an example:

public class Point
{
    public short x;
    public short y;
}

public class CoordinateSystem
{
    private Point Start;
    private Point End;

    public Point GetThePoint()
    {
        Point pt = new Point();

        Console.Write("Enter the x coordinate of the point: ");
        pt.x = short.Parse(Console.ReadLine());
        Console.Write("Enter the y coordinate of the point: ");
        pt.y = short.Parse(Console.ReadLine());
        return pt;
    }
}

Once a method has returned a value of a class, the value can be used as normally as possible.

Passing a Class as Argument

Once a class has been created, it can be used like any other variable. For example, its variable can be passed as argument to a method of another class. When a class is passed as argument, its public members are available to the method that uses it. As done for the arguments of primitive types, you can pass more than one class as argument to a method. Here are different examples:

using System;

namespace Geometry
{
    public class Point
    {
        public short x;
        public short y;
    }

    public class CoordinateSystem
    {
        public Point Start;
        public Point End;

        public Point GetThePoint()
        {
            Point pt = new Point();

            Console.Write("Enter the x coordinate of the point: ");
            pt.x = short.Parse(Console.ReadLine());
            Console.Write("Enter the y coordinate of the point: ");
            pt.y = short.Parse(Console.ReadLine());
            return pt;
        }

        public double DistanceFromOrigin(Point pt)
        {
            double sqr1 = Math.Pow(pt.x, 2);
            double sqr2 = Math.Pow(pt.y, 2);
            double distance = Math.Sqrt(sqr1 + sqr2);
            return distance;
        }

        public double DistanceBetween2Points(Point pt1, Point pt2)
        {
            double sqr1 = Math.Pow(pt2.x - pt1.x, 2);
            double sqr2 = Math.Pow(pt2.y - pt1.y, 2);
            double distance = Math.Sqrt(sqr1 + sqr2);
            return distance;
        }
    }

    class Program
    {
        private static CoordinateSystem IdentifyCoordinates()
        {
            CoordinateSystem coord = new CoordinateSystem();

            Console.WriteLine("Start Point");
            coord.Start = coord.GetThePoint();
            Console.WriteLine("End Point");
            coord.End = coord.GetThePoint();

            return coord;
        }

        private static void Show(CoordinateSystem c)
        {
            Console.WriteLine("Coordinate System");
            Console.WriteLine("Starting Point: P({0}, {1})", c.Start.x, c.Start.y);
            Console.WriteLine("Ending Point:   Q({0}, {1})", c.End.x, c.End.y);
            Console.WriteLine("Distance Between Both Points: {0:F}",
                              c.DistanceBetween2Points(c.Start, c.End));
        }

        static void Main(string[] args)
        {
            CoordinateSystem coord = IdentifyCoordinates();

            Console.WriteLine();
            Show(coord);
        }
    }
}

Here is an example of running the program:

Start Point
Enter the x coordinate of the point: -2
Enter the y coordinate of the point: 2
End Point
Enter the x coordinate of the point: 3
Enter the y coordinate of the point: -6

Coordinate System
Starting Point: P(-2, 2)
Ending Point:   Q(3, -6)
Distance Between Both Points: 9.43
Press any key to continue . . .

Because classes are always used as references, when passing a class as argument, it is implied to be passed by reference. To reinforce this, you can type the ref keyword to the left of the argument. Here is an example:

using System;

namespace ConsoleApplication1
{
    public class Point
    {
        public short x;
        public short y;
    }

    public class CoordinateSystem
    {
        public Point Start;
        public Point End;

        public Point GetThePoint()
        {
            Point pt = new Point();

            Console.Write("Enter the x coordinate of the point: ");
            pt.x = short.Parse(Console.ReadLine());
            Console.Write("Enter the y coordinate of the point: ");
            pt.y = short.Parse(Console.ReadLine());
            return pt;
        }

        public double DistanceFromOrigin(ref Point pt)
        {
            double sqr1 = Math.Pow(pt.x, 2);
            double sqr2 = Math.Pow(pt.y, 2);
            double distance = Math.Sqrt(sqr1 + sqr2);
            return distance;
        }

        public double DistanceBetween2Points(ref Point pt1, ref Point pt2)
        {
            double sqr1 = Math.Pow(pt2.x - pt1.x, 2);
            double sqr2 = Math.Pow(pt2.y - pt1.y, 2);
            double distance = Math.Sqrt(sqr1 + sqr2);
            return distance;
        }
    }

    class Program
    {
        private static CoordinateSystem IdentifyCoordinates()
        {
            CoordinateSystem coord = new CoordinateSystem();

            Console.WriteLine("Start Point");
            coord.Start = coord.GetThePoint();
            Console.WriteLine("End Point");
            coord.End = coord.GetThePoint();

            return coord;
        }

        private static void Show(CoordinateSystem c)
        {
            Console.WriteLine("Coordinate System");
            Console.WriteLine("Starting Point: P({0}, {1})", c.Start.x, c.Start.y);
            Console.WriteLine("Ending Point:   Q({0}, {1})", c.End.x, c.End.y);
            Console.WriteLine("Distance Between Both Points: {0:F}",
                              c.DistanceBetween2Points(ref c.Start, ref c.End));
        }

        static void Main(string[] args)
        {
            CoordinateSystem coord = IdentifyCoordinates();

            Console.WriteLine();
            Show(coord);
        }
    }
}
 

Practical Learning Practical Learning: Return a Class or Passing One as Argument

  1. To return a class or pass it as argument, change the Program.cs file as follows:
     
    using System;
    
    namespace ElectronicStore1
    {
        public class SaleItem
        {
            double DiscountAmount;
            double NetPrice;
            int    Quantity;
            double SaleTotal;
    
            public double GetDiscountRate()
            {
        Console.Write("Discount Applied (Enter 0 to 100, 0 if no discount): ");
                double discount = double.Parse(Console.ReadLine());
                return discount;
            }
    
            public int GetQuantity()
            {
                Console.Write("Enter Quantity: ");
                int q = int.Parse(Console.ReadLine());
                return q;
            }
    
            public StoreItem Create()
            {
                long itemNumber;
                char category;
                string make;
                string model;
                double discount;
                double price;
                StoreItem saleItem = new StoreItem();
    
                Console.Write("Enter the Item #: ");
                itemNumber = long.Parse(Console.ReadLine());
                Console.WriteLine("Category");
                Console.WriteLine("A - Audio Cables");
                Console.WriteLine("B - Instructional and Tutorials (Books)");
                Console.WriteLine("C - Cell Phones and Accessories");
                Console.WriteLine("D - Bags and Cases");
                Console.WriteLine("E - Headphones");
                Console.WriteLine("F - Instructional and Tutorials (VHS & DVD)");
                Console.WriteLine("G - Digital Cameras");
                Console.WriteLine("H - Cables and Connectors");
                Console.WriteLine("I - PDAs and Accessories");
                Console.WriteLine("J - Telephones and Accessories");
                Console.WriteLine("K - Surge Protector");
                Console.WriteLine("L - TVs and Videos");
                Console.WriteLine("U - Unknown");
                Console.Write("Your Choice? ");
                category = char.Parse(Console.ReadLine());
                Console.Write("Make:        ");
                make = Console.ReadLine();
                Console.Write("Model:       ");
                model = Console.ReadLine();
                Console.Write("Unit Price:  ");
                price = double.Parse(Console.ReadLine());
                
                saleItem.SetItemNumber(itemNumber);
                saleItem.SetCategory(category);
                saleItem.SetMake(make);
                saleItem.SetModel(model);
                saleItem.SetUnitPrice(price);
    
                return saleItem;
            }
            
            public void ShowSaleItem(StoreItem item)
            {
                double discountRate = GetDiscountRate();
                int    quantity     = GetQuantity();
                DiscountAmount = item.GetUnitPrice() * discountRate / 100;
                NetPrice = item.GetUnitPrice() - DiscountAmount;
                SaleTotal = NetPrice * quantity;
    
                Console.WriteLine("\nStore Item Description");
                Console.WriteLine("Item Number:     {0}", item.GetItemNumber());
                Console.WriteLine("Category:        {0}", item.GetCategory());
                Console.WriteLine("Make             {0}", item.GetMake());
                Console.WriteLine("Model:           {0}", item.GetModel());
                Console.WriteLine("Unit Price:      {0:C}", item.GetUnitPrice());
                Console.WriteLine("Discount Rate:   {0:P}", discountRate/100);
                Console.WriteLine("Discount Amount: {0:C}", DiscountAmount);
                Console.WriteLine("Price/Item:      {0:C}", NetPrice);
                Console.WriteLine("Quantity:        {0}", quantity);
                Console.WriteLine("Sale Total:      {0:C}", SaleTotal);
            }
        }
    
        class Program
        {
            static void Main()
            {
                StoreItem item = new StoreItem();
                SaleItem sale = new SaleItem();
                string strTitle1 = "=-= Nearson Electonics =-=\n";
                string strTitle2 = "******* Store Items ******";
    
                Console.WriteLine(strTitle1);
                Console.WriteLine(strTitle2);
    
                item = sale.Create();
                sale.ShowSaleItem(item);
    
                Console.WriteLine();
            }
        }
    }
  2. Execute the application. Here is an example:
     
    =-= Nearson Electonics =-=
    
    ******* Store Items ******
    Enter the Item #: 927374
    Category
    A - Audio Cables
    B - Instructional and Tutorials (Books)
    C - Cell Phones and Accessories
    D - Bags and Cases
    E - Headphones
    F - Instructional and Tutorials (VHS & DVD)
    G - Digital Cameras
    H - Cables and Connectors
    I - PDAs and Accessories
    J - Telephones and Accessories
    K - Surge Protector
    L - TVs and Videos
    U - Unknown
    Your Choice? L
    Make:        NEC
    Model:       VT48 Video Projector
    Unit Price:  705.95
    Discount Applied (Enter 0 to 100, 0 if no discount): 15
    Enter Quantity: 1
    
    Store Item Description
    Item Number:     927374
    Category:        L
    Make             NEC
    Model:           VT48 Video Projector
    Unit Price:      $705.95
    Discount Rate:   15.00 %
    Discount Amount: $105.89
    Price/Item:      $600.06
    Quantity:        1
    Sale Total:      $600.06
    
    Press any key to continue . . .
  3. Return to Notepad

Home Copyright © 2006-2007 FunctionX, Inc.