Introduction to Structures
Introduction to Structures
Fundamentals of Structures
Introduction
To store the values presented to it, a computer divides its memory in two parts. The heap is the section in which the objects from classes are stored. In previous lessons, we saw various examples of creating classes and creating objects from classes. Such objects are stored in the heap. We also saw that, to create an object and store it in the heap, we must use the new operator (unless the class is static). To refer to an object stored in the heap, you must use its reference. This means that you don't need nor get the actual object. You only need its address in the computer memory.
The stack is the section of memory that stores small values such as natural numbers, symbols, or Boolean values. The actual values of such types are available, not simply their addresses. If you want, you can create a group of values of small types, called primitive data types.
A structure, like a class, is a list of types used to describe an object. Unlike a class that is used for large and complex objects, a structure is used for small objects.
Practical Learning: Introducing Structures
public enum Category { Regular, StateHighway, USHighway, Interstate, CapitalBeltway }
Creating a Structure
To create a structure, you use the same formula as for a class but use the struct keyword. Here is an example that starts a structure:
struct Integer { }
Like a class, the creation of a structure can start with an access level, usually the public or the internal keyword. Here is an example:
public struct Integer
{
}
Practical Learning: Creating a Structure
public enum Category
{
Regular,
StateHighway,
USHighway,
Interstate,
CapitalBeltway
}
public struct Road
{
}
Structures and Fields
Like a class, a structure can have fields. They are listed in the body of the structure. Here is an example:
struct Integer
{
private int val;
}
Practical Learning: Adding a Field to a Structure
public enum Category
{
Regular,
StateHighway,
USHighway,
Interstate,
CapitalBeltway
}
public struct Road
{
private string id;
private double len;
private Category cat;
private string ending;
private string beginning;
}
Structures and Properties
A structure, like a class, can have properties. A property is created using the exact same rules and suggestions we saw for classes. Here is an example of a property with a complete definition:
struct Integer
{
private int val;
public int Value
{
get { return val; }
set { val = value; }
}
}
Practical Learning: Creating Properties in a Structure
public enum Category
{
Regular,
StateHighway,
USHighway,
Interstate,
CapitalBeltway
}
public struct Road
{
private string id;
private double len;
private Category cat;
private string ending;
private string beginning;
public string Designation
{
get
{
return id;
}
set
{
id = value;
}
}
public Category RoadType
{
get { return cat; }
set { cat = value; }
}
public double Distance
{
get { return len; }
set { len = value; }
}
public string Start
{
get { return beginning; }
set { beginning = value; }
}
public string End
{
get { return ending; }
set { ending = value; }
}
}
Structures and Methods
Like a class, a structure can have methods. A structure supports all concepts we reviewed for methods of classes. A method of a structure can be of type void. Here is an example:
struct Integer
{
private int val;
public int Value
{
get { return val; }
set { val = value; }
}
public void Read()
{
}
}
In the same way, a method can return a value of a primitive type. A method can use one or more parameters. A method can be overloaded with various versions that take different parameters.
Practical Learning: Adding a Method to a Structure
public enum Category
{
Regular,
StateHighway,
USHighway,
Interstate,
CapitalBeltway
}
public struct Road
{
private string id;
private double len;
private Category cat;
private string ending;
private string beginning;
public string Designation
{
get
{
return id;
}
set
{
id = value;
}
}
public Category RoadType
{
get { return cat; }
set { cat = value; }
}
public double Distance
{
get { return len; }
set { len = value; }
}
public string Start
{
get { return beginning; }
set { beginning = value; }
}
public string End
{
get { return ending; }
set { ending = value; }
}
public double GetDistanceInKilometers()
{
return Distance * 1.6093;
}
}
Structures and Constructors
A Default Constructor?
A structure, like a class, can have one or more constructors. We saw that, if you don't create any constructor in a class, the compiler will create a default constructor for your class, that is, a constructor that doesn't use any parameter. We also saw that, if you create at least one constructor in a class and that constructor in a class and that single constructor uses at least one parameter, or all constructors of the class have at least one parameter, the default constructor would not be available anymore. In that case, if you still want a default constructor, you must explicitly create a constructor that doesn't use a parameter.
When it comes to a structure, the compiler always creates a default constructor for you and that constructor cannot be hidden. As a result, you are not allowed to create a default constrcutor in a structure.
Creating Constructors in a Structure
If you decide to create a constructor in a structure, that constructor must have at least one parameter. Other than that rule, the constructors of a structure follow the same rules and suggestions of constructors of a class. For example, a structure can use one constructor that uses one or more parameters Here is an example:
struct Integer
{
private int val;
public Integer(int number)
{
val = number;
}
public int Value
{
get { return val; }
set { val = value; }
}
public void Read()
{
}
}
A constructor can be overloaded with various versions that use different parameters. Here is an example:
struct Integer { private int val; public Integer(int number) { val = number; } public Integer(string number) { val = int.Parse(number); } public Integer(int number, int maximumSize) { val = number; maximumSize = 1; } public int Value { get { return val; } set { val = value; } } public void Read() { } }
Practical Learning: Adding Constructors to a Structure
public enum Category
{
Regular,
StateHighway,
USHighway,
Interstate,
CapitalBeltway
}
public struct Road
{
private string id;
private double len;
private Category cat;
private string ending;
private string beginning;
public Road(string identification)
{
len = 0.00;
ending = "";
beginning = "";
id = identification;
cat = Category.Regular;
}
public Road(string identification, Category type, double length)
{
cat = type;
ending = "";
len = length;
beginning = "";
id = identification;
}
public string Designation
{
get
{
return id;
}
set
{
id = value;
}
}
public Category RoadType
{
get { return cat; }
set { cat = value; }
}
public double Distance
{
get { return len; }
set { len = value; }
}
public string Start
{
get { return beginning; }
set { beginning = value; }
}
public string End
{
get { return ending; }
set { ending = value; }
}
public double GetDistanceInKilometers()
{
return len * 1.6093;
}
}
Creating an Object from a Structure
To use a structure, you can declare a variable of it. Initialize the variable as done for a class, using the new operator. Remember that a structure always has a default constructor. Therefore, if you don't have an initial value, initialize the variable with the default constructor. Here is an example:
public struct Integer
{
private int val;
public Integer(int number)
{
val = number;
}
public Integer(string number)
{
val = int.Parse(number);
}
public Integer(int number, int maximumSize)
{
val = number;
maximumSize = 1;
}
public int Value
{
get { return val; }
set { val = value; }
}
public void Read()
{
}
}
public class Exercise
{
public void Create()
{
Integer itg = new Integer();
}
}
You can also initialize the variable with a constructor that uses one or more parameters. Here is an example:
public struct Integer
{
private int val;
public Integer(int number)
{
val = number;
}
}
public class Exercise
{
public void Main()
{
Integer itg = new Integer(1257);
}
}
As done for variables of the other types and as seen for classes, to declare a variable for a structure, you can use the var keyword.
Accessing the Members of a Structure
After declaring a variable of a structure, you can use the object the same way you would a class. You can access its members (fields, properties, and methods) using the period operator. Here is an example:
public struct Integer
{
private int val;
public Integer(int number)
{
val = number;
}
public int Value
{
get { return val; }
set { val = value; }
}
}
public class Exercise
{
public void Create()
{
Integer itg = new Integer();
itg.Value = 1500;
}
}
Practical Learning: Accessing a Structure
<!DOCTYPE html> <html> <head> <title>Road System Database</title> <style> .container { margin: auto; width: 500px; } .hard { font-weight: bold; } .left-col{ width: 120px; } .startend { width: 350px } </style> </head> <body> @{ Road rd = new Road(); rd.Designation = "I-83"; rd.RoadType = Category.Interstate; rd.Distance = 85.3; rd.Start = "East Fayette Street / North President Street / Fallsway in Baltimore, MD"; rd.End = "I-81 / US 322 / Capital Beltway in Harrisburg, PA"; } <div class="container"> <h2 style="text-align: center">Road System Database</h2> <form name="frmRoads" method="post"> <table border="1"> <tr> <td class="hard left-col">Road Name:</td> <td>@rd.Designation</td> </tr> <tr> <td class="hard">Type of Road:</td> <td>@rd.RoadType</td> </tr> <tr> <td class="hard">Length:</td> <td>@rd.Distance.ToString() Miles (@rd.GetDistanceInKilometers().ToString("F") Kms)</td> </tr> <tr> <td class="hard">Start</td> <td>@rd.Start</td> </tr> <tr> <td class="hard">End</td> <td>@rd.End</td> </tr> </table> </form> </div> </body> </html>
Topics on Structures
Structures and Inheritance
A structure is sealed from inheritance. This means that you cannot create a class or a structure that is based on, or is derived from, a structure.
A Property of a Structure Type
Once a structure exists, you can use it like a data type. For example, you can create a property that is a structure type. The rules are the same we reviewed for creating a property of a class. Here are examples:
public enum Category
{
Regular,
StateHighway,
USHighway,
Interstate,
CapitalBeltway
}
public struct Road
{
private string id;
private double len;
private Category cat;
private string ending;
private string beginning;
public Road(string identification)
{
len = 0.00;
ending = "";
beginning = "";
id = identification;
cat = Category.Regular;
}
public Road(string identification, Category type, double length)
{
cat = type;
ending = "";
len = length;
beginning = "";
id = identification;
}
public string Designation
{
get
{
return id;
}
set
{
id = value;
}
}
public Category RoadType
{
get { return cat; }
set { cat = value; }
}
public double Distance
{
get { return len; }
set { len = value; }
}
public string Start
{
get { return beginning; }
set { beginning = value; }
}
public string End
{
get { return ending; }
set { ending = value; }
}
public double GetDistanceInKilometers()
{
return len * 1.6093;
}
}
public class Intersection
{
public Road Road1 { get; set; }
public Road Road2 { get; set; }
public string InOrNear { get; set; }
public Intersection()
{
}
public Intersection(Road one, Road two, string position)
{
Road1 = one;
Road2 = two;
InOrNear = position;
}
}
After creating the property, you can use it as you see fit.
Returning a Structure From a Method
Like regular data type or a class, a structure can serve as the return type of a method. The rules are more related to those of a class. When creating the method, type the name of the structure on the left side of the name of the method. In the body of the method, implement the desired behavior. Before exiting the method, make sure you return a valid value that is of the type of the structure. Here is an example:
public enum Category
{
Regular,
StateHighway,
USHighway,
Interstate,
CapitalBeltway
}
public struct Road
{
private string id;
private double len;
private Category cat;
private string ending;
private string beginning;
public Road(string identification)
{
len = 0.00;
ending = "";
beginning = "";
id = identification;
cat = Category.Regular;
}
public Road(string identification, Category type, double length)
{
cat = type;
ending = "";
len = length;
beginning = "";
id = identification;
}
public string Designation
{
get
{
return id;
}
set
{
id = value;
}
}
public Category RoadType
{
get { return cat; }
set { cat = value; }
}
public double Distance
{
get { return len; }
set { len = value; }
}
public string Start
{
get { return beginning; }
set { beginning = value; }
}
public string End
{
get { return ending; }
set { ending = value; }
}
public double GetDistanceInKilometers()
{
return len * 1.6093;
}
}
public class StateAdministration
{
public Road Create()
{
Road h137 = new Road("Highway 137", Category.StateHighway, 192.24);
h137.Start = "Brownfield, TX";
h137.End = "Near Ozona in west Texas";
return h137;
}
}
When a method returns a value of the type of a structure, you can assign the method call to a variable of the type of the structure.
Passing a Structural Object as Argument
Like a regular data type, a structure can be used as the type of a parameter of a method. The argument is primarily passed as done for a class. After passing the argument, in the body of the method, you can access the public members of the structure, using the period operator. Here is an example:
Class File: Road.cs
public enum Category
{
Regular,
StateHighway,
USHighway,
Interstate,
CapitalBeltway
}
public struct Road
{
private string id;
private double len;
private Category cat;
private string ending;
private string beginning;
public Road(string identification)
{
len = 0.00;
ending = "";
beginning = "";
id = identification;
cat = Category.Regular;
}
public Road(string identification, Category type, double length)
{
cat = type;
ending = "";
len = length;
beginning = "";
id = identification;
}
public string Designation
{
get
{
return id;
}
set
{
id = value;
}
}
public Category RoadType
{
get { return cat; }
set { cat = value; }
}
public double Distance
{
get { return len; }
set { len = value; }
}
public string Start
{
get { return beginning; }
set { beginning = value; }
}
public string End
{
get { return ending; }
set { ending = value; }
}
public double GetDistanceInKilometers()
{
return len * 1.6093;
}
}
public class StateAdministration
{
public Road Create()
{
Road h137 = new Road("Highway 137", Category.StateHighway, 192.24);
h137.Start = "Brownfield, TX";
h137.End = "Near Ozona in west Texas";
return h137;
}
}
public class RoadSystem
{
public string Describe(Road rd)
{
return "Road Name: " + rd.Designation + ", " +
"Road Type: " + rd.RoadType + ", " +
"Distance: " + rd.Distance + ", " +
"Start: " + rd.Start + ", " +
"End: " + rd.End;
}
}
---------------------------------------------
Web Page: Index.cshtml
<!DOCTYPE html>
<html>
<head>
<title>Road System Database</title>
</head>
<body>
@{
RoadSystem rs = new RoadSystem();
StateAdministration sa = new StateAdministration();
Road going = sa.Create();
}
<h3>Road System Database</h3>
<p>Road Description</p>
<p>@rs.Describe(going)</p>
</body>
</html>
This would produce:
When you pass a structure to a method as we did above, it is referred to as passing by value. A copy of the value of the structure is passed to the method. If the method modifies the argument, the original variable would stay intact. If you want the method to modify the value of the structure, you can pass the argument by reference. You can do this using the (rules of the) ref and the out keywords.
Introduction to Built-In Structures
Overview
To assist you in creating various types of applications, the .NET Frameword includes various ready-made structures that you can directly use in your code. As is always the case, the structures are included in different namespace created in various libraries.
Introduction to the Drawing Namespace
One of the namespaces that contain some of the most regularly used structures is named Drawing, which itself is a member of the System.Drawing namespace. To use the System.Drawing namespace, if you are working in Microsoft Visual Studio, add a reference to the System.Drawing.dll to your project (normally, it is added by default when you create an ASP.NET Web Application project). In the top section of the document that contains your code, add a line as using System.Drawing;.
A Point
The Origin of an Object
Each object used in a graphical application must be drawn on the computer screen. In Microsoft Windows (as well as most operating systems), the coordinate system has its origin (0, 0) on its top-left corner:
In the same way, every pixel on the monitor screen is recognized by its address. The address is represented as a point. To support the concept of points, the .NET Framework provides a structure named Point. The Point structure is defined in the System.Drawing namespace.
Characteristics of a Point
One of the properties of the Point structure is X, which represents the horizontal distance of the point from the top-left corner of the object that owns the point. Another property, Y, represents the vertical measurement of the point with regards to the top-left corner of the object that owns the point. Based on this, a Point object can be represented on the Windows coordinate system as follows:
Both the X and the Y properties of the Point structure are of type int. If you have a point that cannot be identified, to support unidentified points, the Point structure is equipped with a static field named Empty. In this property, both the X and the Y values are set to 0:
Here is an example of accessing it:
using System.Drawing;
public class Exercise
{
private void Create()
{
Point origin = new Point.Empty;
}
}
To help you find out whether a point is empty, the Point structure is equipped with a Boolean property named IsEmpty. You can enquire about this property using a conditional statement.
To create or identify a point, you can use one of the three constructors of the Point structure. One of these constructors uses the following syntax:
public Point(int x, int y)
This constructor takes a left and a top arguments. Here is an example of creating a point using it:
using System.Drawing;
public class Exercise
{
private void Create()
{
Point pt = new Point(6, -2);
}
The Point structure is equipped with methods to perform various operations such as adding or subtracting points, etc.
The Size of an Object
Introduction
The size of an object is a combination of its with and its height. This can be illustrated as follows:
To support the size of an object, the System.Drawing namespace defines a structure named Size. There are four characteristics that define a Size value: its location and its dimensions. A Size value must have a starting point (X, Y) just as the Point object was illustrated earlier:
The members of a Size structure use values of type int.
Characteristics of a Size
The Size structure is equipped with properties named Width and Height that represent their width and height respectively.
To let you specify a size, the Size structure is equipped with the following constructor:
public Size(int width, int height);
You can also define a Size object using a Point value. To support this, the Size structure is equipped with the following constructor:
public Size(Point pt);
After declaring a variable with this constructor, you can access its Width and Height properties.
The Rectangle
Introduction
The combination of the location and size of an object is represented as a rectangle: a quadrilateral geometric figure with four four right angles. To support this figure, the System.Drawing namespace provides a structure named Rectangle. A rectangle can be represented as follows:
The object that "owns" or defines the rectangle also owns this origin.
Characteristics of a Rectangle
To completely represent it, a rectangle is defined by its location and its size. The location is defined by a point on the top-left corner of the rectangle:
Based on this, a rectangle can be further illustrated as follows:
To create a rectangle, you must provide at least its location and size. The location can be represented by a Point object and the dimensions can be represented with a Size value. To support this, the Rectangle structure provides the following constructor that you can use to declare a variable:
public Rectangle(Point location, Size size);
This constructor requires a Point object and a Size value. If instead you know the values of the location, the width and the height, the Rectangle structure provides the following constructor:
public Rectangle(int x, int y, int width, int height);
The Color
Introduction
The color is a non-spatial value that controls the transparency of an object. To support colors, the System.Drawing namespace of the System.Drawing.dll library provides a structure named Color:
public struct Color
Composing a Color
A color is created as a combination of four values: alpha, red, green, and blue. Each value or number can have a value that ranges from 0 to 255 in the decimal system. The alpha section is reserved for the operating systems.
Converted to decimal, this number has a value of 255 * 255 * 255 = 16581375. This means that we can have approximately 16 million colors available.
Your computer monitor has a surface that resembles a series of tinny horizontal and vertical lines. The intersection of a horizontal line and a vertical line is called a pixel. This pixel holds, carries, or displays one color:
Using a Color
To make color selection easier, the Color structure is equipped with various read-only static properties that each represents a name for a color. Therefore, to use any of the available colors, type the Color structure followed by the "." operator, followed by the desired color. All the popular names of colors are recognized by name. These include Red, Green, Blue, Black, White, Yellow, Pink, Navy, Violet, Teal, Maroon, Orange, Fuchsia, Silver, Gray, Olive, Brown, Aqua, Beige, Gold, Firebrick, and Khaki, etc, just to name a few.
Extracting a Color
To create a color, declare a variable of type Color. To let you specify the values of the color, the Color structure is equipped with a static method named FromArgb() that is overloaded with four versions whose syntaxes are:
public static Color FromArgb(int argb); public static Color FromArgb(int alpha, Color baseColor); public static Color FromArgb(int red, int green, int blue); public static Color FromArgb(int alpha, int red, int green, int blue);
The third version, which is the most used, allows you to specify three values that each ranges from 0 to 255. Instead of defining a color by its RGB composition, if you know the name of the color you want to use, the Color structure provides a method named FromName that you can use. Its syntax is:
public static Color FromName(string name);
This method expects as argument the name of the color. When calling this method, make sure you know the name of the color you want to use.
You cannot realistically know the names of all available colors. To assist you with identifying a color, the Color structure provides a method named FromKnownColor. Its syntax is:
public static Color FromKnownColor(KnownColor name);
This method takes as argument a member of an enumeration named KnownColor. The KnownColor enumeration holds the names of common colors (such as Red, Green, Blue, Yellow, Violet, etc), the colors used on web pages (such as LightBlue or DarkGreen), the colors defined in Microsoft Windows (such as ActiveBorder, AppWorkspace, or ButtonFace, etc), and many others.
Extracting a Color
Whether a color was initialized with one of the Color pre-defined color properties, using the FromArgb(), the FromName(), or the FromKnownColor() methods, to let you retrieve the red, green, or blue components of a color, the Color structure is equipped with read-only properties named R (it produces the red value), G (it produces the green value), and B (it produces the bluevalue). As an alternative, you can call the Color.ToArgb() method. Its syntax is:
public int ToArgb();
This method returns an integer.
If you want to get the color by its common or known name, the Color structure provides a method named ToKnownColor. Its syntax is:
public KnownColor ToKnownColor();
This method returns a value that is based on the KnownColor enumeration.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2019, FunctionX | Next |
|