C# Language

Combinations of Classes

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…

8 min read1,723 words22 code samples

A Class as a Type#

A Class as a Field#

Classes can be used as types for variables, just like the primitive data types we have seen.

C#
public class Point
{
    internal short x;
    internal 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:

C#
public class Point
{
    internal short x;
    internal 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. Application: 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...
  4. Change the Name to ElectonicStore1 and press Enter
  5. To create a new class, in the Solution Explorer, right-click the name of the project, position the mouse on Add and click Class...
  6. Set the Name to StoreItem and click Add
  7. Complete the file as follows: using System; using System.Collections.Generic; using System.Linq; using System.Text; 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 = 0) { this.nbr = number; } public char GetCategory() { return cat; } public void SetCategory(char 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; } } }
  8. To create a new file, on the main menu, click Project -> Add New Item...
  9. In the middle list, click Code File
  10. Change the name to OrderProcessing and press Enter
  11. Change the file as follows: using System; namespace ElectronicStore1 { public class OrderProcessing { public static int Main() { string strTitle1 = "=-= Nearson Electonics =-=\n"; string strTitle2 = "******* Store Items ******"; System.Console.ReadKey(); return 0; } } }

Returning an Object 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:

C#
public class Point
{
    internal short x;
    internal 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:

C#
public class Point
{
    internal short x;
    internal 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 you have defined a class, it can be treated as a data type for declaring other variables.

C#
using System;

namespace Geometry
{
    public class Point
    {
        internal short x;
        internal 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;
        }
    }

    public 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 int Main()
        {
            CoordinateSystem coord = IdentifyCoordinates();

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

Here is an example of running the program:

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

Since classes are reference types, they are handled differently in memory compared to value types.

C#
using System;

namespace ConsoleApplication1
{
    public class Point
    {
        internal short x;
        internal 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;
        }
    }

    public 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 int Main()
        {
            CoordinateSystem coord = IdentifyCoordinates();

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

Application: Returning a Class or Passing One as Argument

  1. To return a class or pass it as argument, change the OrderProcessing.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); } } 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"; Console.WriteLine(strTitle1); Console.WriteLine(strTitle2); Console.Clear(); item = sale.Create(); sale.ShowSaleItem(item); System.Console.ReadKey(); 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

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:

C#
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:

C#
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:

C#
using System;

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)
    {
        Console.Write("Point Coordinates: ");
        Console.WriteLine("A({0}, {1})", pt.x, pt.y);
    }

    static int Main(string[] args)
    {
        Point pt = new Point();

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

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

        return 0;
    }
}

This would produce:

C#
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:

C#
using System;

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)
    {
        Console.Write("Point Coordinates: ");
        Console.WriteLine("A({0}, {1})", pt.x, pt.y);
    }

    static int Main(string[] args)
    {
        Point pt = new Point();

        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:

C#
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:

C#
using System;

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)
    {
        Console.Write("Point Coordinates: ");
        Console.WriteLine("A({0}, {1})", pt.x, pt.y);
    }

    static int Main(string[] args)
    {
        Point pt = new Point();

        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:

C#
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:

C#
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:

C#
using System;

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)
    {
        Console.Write("Point Coordinates: ");
        Console.WriteLine("A({0}, {1})", pt.x, pt.y);
    }

    static int Main(string[] args)
    {
        Point pt = new Point();

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

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

        return 0;
    }
}

This would produce:

C#
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:

C#
using System;

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)
    {
        Console.Write("Point Coordinates: ");
        Console.WriteLine("A({0}, {1})", pt.x, pt.y);
    }

    static int Main(string[] args)
    {
        Point pt = new Point();

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

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

        return 0;
    }
}

This would produce:

C#
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:

C#
using System;

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)
    {
        Console.Write("Point Coordinates: ");
        Console.WriteLine("A({0}, {1})", pt.x, pt.y);
    }

    static int Main(string[] args)
    {
        Point pt = new Point();

        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:

C#
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. Application: Ending the Lesson

  1. Close your programming environment
  2. When asked whether you want to save, click No

Previous Copyright © 2010 C# Key Home