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:

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 class 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 static System.Console;

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

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

public class Exercise
{
    static int Main()
    {
		Outside recto = new Outside();
		Outside.Inside ins = new Outside.Inside();

		return 0;
    }
}

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 static System.Console;

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

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

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

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

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

class Exercise
{
    static int Main()
    {
		Outside recto = new Outside();
		Outside.Inside ins = new Outside.Inside();

		Recto.Display();
		return 0;
    }
}

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 static System.Console;

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

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

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

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

	private static string OutMessage;

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

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

public class Exercise
{
    static int Main()
    {
		Outside recto = new Outside();
		Outside.Inside Ins = new Outside.Inside();

		Recto.Display();
		WriteLine();
		Ins.FieldFromOutside();
		
		return 0;
    }
}

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 static System.Console;

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()
		{
			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();
			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!!";

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

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

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

public class Exercise
{
    static int Main()
    {
		Outside recto = new Outside();
		Outside.Inside Ins = new Outside.Inside();

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

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:

public class Point
{
    internal int x;
    internal int 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
{
    internal int x;
    internal int 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 LearningPractical Learning: Using a Class as a Field

  1. Launch Microsoft Visual C#
  2. To start new program, on the main menu, click File -> New -> Project...
  3. In the middle list, click Empty Project (.NET Framework)
  4. Change the Name to ElectonicStore1
  5. Press Enter
  6. To create a new class, in the Solution Explorer, right-click the name of the project, position the mouse on Add and click Class...
  7. Set the Name to StoreItem and click Add
  8. Complete the file as follows:
    namespace ElectronicStore1
    {
        public class StoreItem
        {
            private int nbr;
            private string cat;
            private string mk;
            private string mdl;
            private double price;
    
            public int GetItemNumber()
            {
                return nbr;
            }
    
            public void SetItemNumber(int number = 0)
            {
                this.nbr = number;
            }
    
            public string GetCategory()
            {
                return cat;
            }
    
            public void SetCategory(string category = "A")
            {
                this.cat = category;
            }
    
            public string GetMake()
            {
                return mk;
            }
    
            public void SetMake(string make = "Unknown")
            {
                this.mk = make;
            }
    
            public string GetModel()
            {
                return mdl;
            }
    
            public void SetModel(string model = "Unknown")
            {
                this.mdl = model;
            }
    
            public double GetUnitPrice()
            {
                return price;
            }
    
            public void SetUnitPrice(double unitPrice = 0.00D)
            {
                this.price = unitPrice;
            }
        }
    }
  9. To create a new file, on the main menu, click Project -> Add New Item...
  10. In the middle list, click Code File
  11. Change the name to OrderProcessing and press Enter
  12. Change the file as follows:
    using static System.Console;
    
    namespace ElectronicStore1
    {
        public class OrderProcessing
        {
            public static int Main()
            {
                string strTitle1 = "=-= Nearson Electonics =-=\n";
                string strTitle2 = "******* Store Items ******";
    
                return 0;
            }
        }
    }

Returning an Object From a Method

Introduction

You can create a method or function that produces and object. You may start as follows:

public class Point
{
    internal int x;
    internal int y;
}

public class CoordinateSystem
{
    private Point start;
    private Point end;

    public Point GetThePoint()
    {
    }
}

In the body of the method, you can first create the object and then return that object. Here is an example:

public class Point
{
    internal int x;
    internal int y;
}

public class CoordinateSystem
{
    private Point start;
    private Point end;

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

        Write("Enter the x coordinate of the point: ");
        pt.x = short.Parse(Console.ReadLine());
        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.

Returning a New Object

If the class of the object you want to return has a constructor, in the body of the method, you can first create an object using the constructor, and then return that object. Here is an example:

using static System.Console;

namespace BusinessManagement
{
    public class Contractor
    {
        public int Code;
        public string FullName;
        public double HourlySalary;
    }

    public class Exercise
    {
        public static Contractor Prepare()
        {
            Contractor worker = new Contractor();
            worker.Code = 80_270_485;
            worker.FullName = "Joshua Eulaw";
            worker.HourlySalary = 28.17;

            return worker;
        }

        static int Main()
        {
            Contractor seasonal = new Contractor();

            seasonal = Prepare();

		    Title = "Apartments Rental Management";
            WriteLine("Apartments Rental Management");
            WriteLine("=============================");
            WriteLine("Contract Work");
            WriteLine("-----------------------------");
            WriteLine("Contractor Code: {0}", seasonal.Code);
            WriteLine("Full Name:       {0}", seasonal.FullName);
            WriteLine("Pay Rate:        {0}", seasonal.HourlySalary);
            WriteLine("=============================");

            return 0;
        }
    }
}

If the class of the object is equipped with a constructor that takes appropriate arguments, you can use that constructor to first build the object before returning it. Here is an example:

using static System.Console;

namespace BusinessManagement
{
    public class Contractor
    {
        public int Code;
        public string FullName;
        public double HourlySalary;

        public Contractor(int nbr, string name, double wage)
        {
            Code = nbr;
            FullName = name;
            HourlySalary = wage;
        }
    }

    public class Exercise
    {
        public static Contractor Prepare()
        {
            int number = 80_270_485;
            string identification = "Joshua Eulaw";
            double salary = 28.17;

            Contractor worker = new Contractor(number, identification, salary);

            return worker;
        }

        static int Main()
        {
            Contractor seasonal = Prepare();

		    Title = "Apartments Rental Management";
            WriteLine("Apartments Rental Management");
            WriteLine("=============================");
            WriteLine("Contract Work");
            WriteLine("-----------------------------");
            WriteLine("Contractor Code: {0}", seasonal.Code);
            WriteLine("Full Name:       {0}", seasonal.FullName);
            WriteLine("Pay Rate:        {0}", seasonal.HourlySalary);
            WriteLine("=============================");

            return 0;
        }
    }
}

Of course, you can pass the constant values directly to the constructor. This can be done as follows:

namespace BusinessManagement
{
    public class Contractor
    {
        public int Code;
        public string FullName;
        public double HourlySalary;

        public Contractor(int nbr, string name, double wage)
        {
            Code = nbr;
            FullName = name;
            HourlySalary = wage;
        }
    }

    public class Exercise
    {
        public static Contractor Prepare()
        {
            Contractor worker = new Contractor(80_270_485, "Joshua Eulaw", 28.17D);

            return worker;
        }
    }
}

Normally, you need to first build/create the object if you plan to perform other operations on it. Otherwise, you can return the object directly on the last line of the method. To do this, type return new followed by the constructor, its argument(s) if any, and close the statement. Here is an example:

using static System.Console;

namespace BusinessManagement
{
    public class Contractor
    {
        public int Code;
        public string FullName;
        public double HourlySalary;

        public Contractor(int nbr, string name, double wage)
        {
            Code = nbr;
            FullName = name;
            HourlySalary = wage;
        }
    }

    public class Exercise
    {
        public static Contractor Prepare()
        {
            return new Contractor(80_270_485, "Joshua Eulaw", 28.17D);
        }

        static int Main()
        {
            Contractor seasonal = Prepare();
		    Title = "Apartments Rental Management";

            WriteLine("Apartments Rental Management");
            WriteLine("=============================");
            WriteLine("Contract Work");
            WriteLine("-----------------------------");
            WriteLine("Contractor Code: {0}", seasonal.Code);
            WriteLine("Full Name:       {0}", seasonal.FullName);
            WriteLine("Pay Rate:        {0}", seasonal.HourlySalary);
            WriteLine("=============================");

            return 0;
        }
    }
}

Passing an Object as Argument

Introduction

You can create a method that uses a parameter that is a class type. Here is an example:

public class Point
{
    internal int x;
    internal int y;
}

public class CoordinateSystem
{
    public void DistanceFromOrigin(Point pt)
    {
        
    }
}

In the body of the method, you can ignore or use the object. When calling the method, pass a valid object. You can first create or build an object and then pass it to the method call. Here are examples:

using static System.Console;

namespace Geometry
{
    public class Point
    {
        internal int x;
        internal int y;
    }

    public class CoordinateSystem
    {
        public Point start;
        public Point end;

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

            Write("Enter the x coordinate of the point: ");
            pt.x = short.Parse(Console.ReadLine());
            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;
        }
    }

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

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

            return coord;
        }

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

        static int Main()
        {
            CoordinateSystem coord = IdentifyCoordinates();

		    Title = "Apartments Rental Management";
            WriteLine();
            Show(coord);
            
	    return 0;
        }
    }
}

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 . . .

Passing an Object by Reference

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 static System.Console;

namespace ConsoleApplication1
{
    public class Point
    {
        internal int x;
        internal int y;
    }

    public class CoordinateSystem
    {
        public Point start;
        public Point end;

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

            Write("Enter the x coordinate of the point: ");
            pt.x = short.Parse(Console.ReadLine());
            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;
        }
    }

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

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

            return coord;
        }

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

        static int Main()
        {
            CoordinateSystem coord = IdentifyCoordinates();

		    Title = "Apartments Rental Management";
            WriteLine();
            Show(coord);
            
	    	return 0;
        }
    }
}

Practical LearningPractical Learning: Returning an Object or Passing One as Argument

  1. To return a class or pass it as argument, change the OrderProcessing.cs file as follows:
    using static System.Console;
    
    namespace ElectronicStore1
    {
        public class SaleItem
        {
            double DiscountAmount;
            double NetPrice;
            int Quantity;
            double SaleTotal;
    
            public double GetDiscountRate()
            {
                Write("Discount Applied (Enter 0 to 100, 0 if no discount): ");
                double discount = double.Parse(Console.ReadLine());
    
                return discount;
            }
    
            public int GetQuantity()
            {
                Write("Enter Quantity: ");
                int q = int.Parse(Console.ReadLine());
                return q;
            }
    
            public StoreItem Create()
            {
                int itemNumber;
                string category;
                string make;
                string model;
                //double discount;
                double price;
                StoreItem saleItem = new StoreItem();
    
                Write("Enter the Item #: ");
                itemNumber = int.Parse(Console.ReadLine());
                WriteLine("Category");
                WriteLine("A - Audio Cables");
                WriteLine("B - Instructional and Tutorials (Books)");
                WriteLine("C - Cell Phones and Accessories");
                WriteLine("D - Bags and Cases");
                WriteLine("E - Headphones");
                WriteLine("F - Instructional and Tutorials (VHS & DVD)");
                WriteLine("G - Digital Cameras");
                WriteLine("H - Cables and Connectors");
                WriteLine("I - PDAs and Accessories");
                WriteLine("J - Telephones and Accessories");
                WriteLine("K - Surge Protector");
                WriteLine("L - TVs and Videos");
                WriteLine("U - Unknown");
                Write("Your Choice? ");
                category = Console.ReadLine();
                Write("Make:        ");
                make = Console.ReadLine();
                Write("Model:       ");
                model = Console.ReadLine();
                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;
    
                WriteLine("\nStore Item Description");
                WriteLine("Item Number:     {0}", item.GetItemNumber());
                WriteLine("Category:        {0}", item.GetCategory());
                WriteLine("Make             {0}", item.GetMake());
                WriteLine("Model:           {0}", item.GetModel());
                WriteLine("Unit Price:      {0:C}", item.GetUnitPrice());
                WriteLine("Discount Rate:   {0:P}", discountRate / 100);
                WriteLine("Discount Amount: {0:C}", DiscountAmount);
                WriteLine("Price/Item:      {0:C}", NetPrice);
                WriteLine("Quantity:        {0}", quantity);
                WriteLine("Sale Total:      {0:C}", SaleTotal);
            }
        }
    
        public class OrderProcessing
        {
            public static int Main()
            {
                StoreItem item = new StoreItem();
                SaleItem sale = new SaleItem();
                string strTitle1 = "=-= Nearson Electonics =-=\n";
                string strTitle2 = "******* Store Items ******";
    
                Console.Title = "Electronic Super Store";
    
                WriteLine(strTitle1);
                WriteLine(strTitle2);
    
                Console.Clear();
    
                item = sale.Create();
                sale.ShowSaleItem(item);
    
                return 0;
            }
        }
    }
  2. Execute the application. Here is an example:
  3. Press Enter
    =-= 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
  4. Press Enter
    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
  5. Press Enter to close and return to your programming environment

Passing a New Object

As mentioned in the previous sections, you can first create an object before passing it as argument. Once again, here is an example:

using static System.Console;

namespace BusinessManagement
{
    public class Contractor
    {
        public int Code;
        public string FullName;
        public double HourlySalary;

        public Contractor(int nbr, string name, double wage)
        {
            Code = nbr;
            FullName = name;
            HourlySalary = wage;
        }
    }

    public class Exercise
    {
        public static void Present(Contractor worker)
        {
            WriteLine("Apartments Rental Management");
            WriteLine("=============================");
            WriteLine("Contract Work");
            WriteLine("-----------------------------");
            WriteLine("Contractor Code: {0,8}", worker.Code);
            WriteLine("Full Name: {0,18}", worker.FullName);
            WriteLine("Pay Rate: {0,12}", worker.HourlySalary);
            WriteLine("=============================");
        }

        static int Main()
        {
		    Title = "Apartments Rental Management";
            Contractor seasonal = new Contractor(80_270_485, "Joshua Eulaw", 28.17D);

            Present(seasonal);

            return 0;
        }
    }
}

It is necessary to first create an object if you need to perform some operations on the object before passing it as argument. Otherwise, you can pass the object directly to the method. To do that, when calling the method, in the placeholder of the argument, type new followed by a constructor of the class of the object, its parentheses, and its own arguments if any. Here is an example:

using static System.Console;

namespace BusinessManagement
{
    public class Contractor
    {
        public int Code;
        public string FullName;
        public double HourlySalary;

        public Contractor(int nbr, string name, double wage)
        {
            Code = nbr;
            FullName = name;
            HourlySalary = wage;
        }
    }

    public class Exercise
    {
        public static void Present(Contractor worker)
        {
            WriteLine("Apartments Rental Management");
            WriteLine("=============================");
            WriteLine("Contract Work");
            WriteLine("-----------------------------");
            WriteLine("Contractor Code: {0,8}", worker.Code);
            WriteLine("Full Name: {0,18}", worker.FullName);
            WriteLine("Pay Rate: {0,12}", worker.HourlySalary);
            WriteLine("=============================");
        }

        static int Main()
        {
		    Title = "Apartments Rental Management";
            Present(new Contractor(80_270_485, "Joshua Eulaw", 28.17D));

            return 0;
        }
    }
}

Involving a Class in its Own Methods

Passing a Class as its Own Argument

An instance of a class can be passed as an argument to one of its own methods (if you have programmed in C++, an example of this implementation is the copy constructor; although you can legitimately create a copy constructor in C#, it does not have the exact same concept as in C++, probably because C# has the Equals() method, which is actually a concept of the .NET Framework). To do this, you primarily pass the argument as if it were any class. Here is an example:

public class Point
{
    internal int x;
    internal int y;

    public void Equivalent(Point Same)
    {
    }
}

Then, in the body of the method, do whatever you want. You can, or you may not, use the argument. Still, if you decide to use the argument, know that all of the other members of the class are available through the argument. Probably the simplest way to use the argument is the assign each of of its values to the equivalent member of the class. Here is an example:

public class Point
{
    internal int x;
    internal int y;

    public void Equivalent(Point Same)
    {
        this.x = Same.x;
        this.y = Same.y;
    }
}

When calling the method, make sure you pass an instance of the class to it. You can first create and define the class, then pass it. Here is an example:

using static System.Console;

public class Point
{
    internal int x;
    internal int y;

    public void Equivalent(Point Same)
    {
        this.x = Same.x;
        this.y = Same.y;
    }
}

public class Program
{
    private static void ShowPoint(Point pt)
    {
        Write("Point Coordinates: ");
        WriteLine("A({0}, {1})", pt.x, pt.y);
    }

    static int Main()
    {
        Point pt = new Point();
		Title = "Coordinate System";

        pt.x = 4;
        pt.y = 6;
        ShowPoint(pt);

        Point One = new Point();
        One.Equivalent(pt);
        ShowPoint(One);

        return 0;
    }
}

This would produce:

Point Coordinates: A(4, 6)
Point Coordinates: A(4, 6)
Press any key to continue . . .

Instead of first declaring a variable of the class and initializing it, you can create an instance of the class in the parentheses of the calling method. To do this, you may need a constructor that can specify the values of the fields of the class so the argument can be rightfully initialized. Here is an example:  

using static System.Console;

public class Point
{
    internal int x;
    internal int y;

    public Point()
    {
    }

    public Point(int XCoord, int YCoord)
    {
        this.x = XCoord;
        this.y = YCoord;
    }

    public void Equivalent(Point Same)
    {
        this.x = Same.x;
        this.y = Same.y;
    }
}

public class Program
{
    private static void ShowPoint(Point pt)
    {
        Write("Point Coordinates: ");
        WriteLine("A({0}, {1})", pt.x, pt.y);
    }

    static int Main()
    {
        Point pt = new Point();
		Title = "Coordinate System";

        pt.x = 4;
        pt.y = 6;
        ShowPoint(pt);

        Point One = new Point();
        One.Equivalent(new Point(-3, 2));
        ShowPoint(One);

        return 0;
    }
}

Instead of a formal method, you can use a constructor of the class to pass an instance of the same class. Then, in the constructor, use the argument as you see fit, knowing that all the members of the class are available. Here is an example:

public class Point
{
    internal int x;
    internal int y;

    public Point()
    {
    }

    public Point(int XCoord, int YCoord)
    {
        this.x = XCoord;
        this.y = YCoord;
    }

    public Point(Point Same)
    {
        this.x = Same.x;
        this.y = Same.y;
    }
}

Obviously the purpose of passing a class to one of its own methods is not to find its equivalent. The C# language (actually the .NET Framework) can also take care of that (through the Equals() built-in method). Instead, you can create a method that takes an instance of the same class but modifies that instance. For example, for our Point class, we may want to create a new point that is distanced by one unit from the current Point object. Here is an example of doing that:

using static System.Console;

public class Point
{
    internal int x;
    internal int y;

    public Point()
    {
    }

    public Point(int XCoord, int YCoord)
    {
        this.x = XCoord;
        this.y = YCoord;
    }

    public void Equivalent(Point Same)
    {
        this.x = Same.x;
        this.y = Same.y;
    }

    public void CreatePointOneUnitAway(Point AddUnit)
    {
        this.x = AddUnit.x + 1;
        this.y = AddUnit.y + 1;
    }
}

public class Program
{
    private static void ShowPoint(Point pt)
    {
        Write("Point Coordinates: ");
        WriteLine("A({0}, {1})", pt.x, pt.y);
    }

    static int Main()
    {
        Point pt = new Point();
		Title = "Coordinate System";

        pt.x = 4;
        pt.y = 6;
        ShowPoint(pt);

        Point One = new Point();
        One.CreatePointOneUnitAway(pt);
        ShowPoint(One);
        One.CreatePointOneUnitAway(new Point(-8, -3));
        ShowPoint(One);

        return 0;
    }
}

This would produce:

Point Coordinates: A(4, 6)
Point Coordinates: A(5, 7)
Point Coordinates: A(-7, -2)
Press any key to continue . . .

Returning a Class From its Own Method

You can create a method in a class that returns an instance of the class. To start, on the left side of the method, enter the name of the class. Here is an example:

public class Point
{
    public Point MethodName()
    {
    }
}

There are various ways you can deal with the method. If you want to return a new value of the class, you can declare an instance of the class, initialize it, and then return it. Here is an example:

using static System.Console;

public class Point
{
    internal int x;
    internal int y;

    public Point()
    {
    }

    public Point(int XCoord, int YCoord)
    {
        this.x = XCoord;
        this.y = YCoord;
    }

    public Point(Point Same)
    {
        this.x = Same.x;
        this.x = Same.x;
    }

    public Point AdvanceBy5()
    {
        Point Some = new Point();
        Some.x = 5;
        Some.y = 5;
        return Some;
    }
}

public class Program
{
    private static void ShowPoint(Point pt)
    {
        Write("Point Coordinates: ");
        WriteLine("A({0}, {1})", pt.x, pt.y);
    }

    static int Main()
    {
        Point pt = new Point();
		Title = "Coordinate System";

        pt.x = 4;
        pt.y = 6;
        ShowPoint(pt);

        Point Away5 = pt.AdvanceBy5();
        ShowPoint(Away5);

        return 0;
    }
}

This would produce:

Point Coordinates: A(4, 6)
Point Coordinates: A(5, 5)
Press any key to continue . . .

Alternatively, you can declare an instance of the class, use the current values of the class combined with those of the instance to get new values, and then return the instance. Here is an example:

using static System.Console;

public class Point
{
    internal int x;
    internal int y;

    public Point()
    {
    }

    public Point(int XCoord, int YCoord)
    {
        this.x = XCoord;
        this.y = YCoord;
    }

    public Point(Point Same)
    {
        this.x = Same.x;
        this.x = Same.x;
    }

    public Point AdvanceBy5()
    {
        Point Some = new Point();
        Some.x = this.x + 5;
        Some.y = this.y + 5;
        return Some;
    }
}

public class Program
{
    private static void ShowPoint(Point pt)
    {
        Write("Point Coordinates: ");
        WriteLine("A({0}, {1})", pt.x, pt.y);
    }

    static int Main()
    {
        Point pt = new Point();
		Title = "Coordinate System";

        pt.x = 4;
        pt.y = 6;
        ShowPoint(pt);

        Point Away5 = pt.AdvanceBy5();
        ShowPoint(Away5);

        return 0;
    }
}

This would produce:

Point Coordinates: A(4, 6)
Point Coordinates: A(9, 11)
Press any key to continue . . .

Remember that, to call the method, if it is not static, you will need to declare an instance of the class from where you are calling the method. The second type of implementation consists of modifying the instance of the class that is calling the method. For example, you can add values to its fields or you can perform any other operation you want on the members of the calling instance. is an example:

using static System.Console;

public class Point
{
    internal int x;
    internal int y;

    public Point()
    {
    }

    public Point(int XCoord, int YCoord)
    {
        this.x = XCoord;
        this.y = YCoord;
    }

    public Point(Point Same)
    {
        this.x = Same.x;
        this.x = Same.x;
    }

    // This method adds 1 to each field of the class
    // to get a new point away North-East of the current point
    public Point CreatePointOneUnitAway()
    {
        this.x = this.x + 1;
        this.y = this.y + 1;

        return this;
    }
}

public class Program
{
    private static void ShowPoint(Point pt)
    {
        Write("Point Coordinates: ");
        WriteLine("A({0}, {1})", pt.x, pt.y);
    }

    static int Main()
    {
        Point pt = new Point();
		Title = "Coordinate System";

        pt.x = 4;
        pt.y = 6;
        ShowPoint(pt);

        Point One = new Point(-8, 5);
        Point Another = One.CreatePointOneUnitAway();
        ShowPoint(Another);

        return 0;
    }
}

This would produce:

Point Coordinates: A(4, 6)
Point Coordinates: A(-7, 6)
Press any key to continue . . .

As we have learned now, you can create a method that takes an argument that is the same type as its parent class. In the method, you can access any member of the class, including calling the other methods of the class.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2019, FunctionX Next