Lab 10: Structs and Enumeration There is one more way to create your own value types in C#. You can use the struct keyword. A struct (short for structure) can have its own fields, methods, and constructors just like a class (and unlike an enumeration), but it is a value type and not a reference type. Declaring Struct Types To declare your own struct value type, you use the struct keyword followed by the name of the type, followed by the body of the struct between an opening and closing brace. For example, here is a struct called Time that contains three public int fields called hours, minutes, and seconds: struct Time public int hours, minutes, seconds; However, making the fields of a struct public is a violation of encapsulation and in most cases is not advisable. There is no way to ensure the values of public fields are valid. For example, anyone could set the value of minutes or seconds to greater than 60. A better idea is to make the fields private and provide your struct with constructors and methods, as shown in this example: struct Time public Time(int hh, int mm, int ss) hours = hh % 24; minutes = mm % 60; seconds = ss % 60; public int Hours() return hours; private int hours, minutes, seconds; Remarks It is an error to declare a default (parameterless) constructor for a struct. A default constructor is always provided to initialize the struct members to their default values. It is an error to initialize an instance field in a struct. When you create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized. Now let s proceed to the exercises by typing the following program in exercise 1 Computer & Programming: Structs and Enumerations 1/13 Powered by MIKE TM
1:// struct declaration and initialization 2:using System; 3:namespace ex10_1 4: 5: public struct Point 6: 7: public int x, y; 8: 9: public Point(int p1, int p2) 10: 11: x = p1; 12: y = p2; 13: 14: 15: class MainClass 16: 17: public static void Main() 18: 19: // Initialize: 20: Point mypoint = new Point(); 21: Point yourpoint = new Point(10,10); 22: 23: // Display results: 24: Console.Write("My Point: "); 25: Console.WriteLine("x = 0, y = 1", mypoint.x, mypoint.y); 26: Console.Write("Your Point: "); 27: Console.WriteLine("x = 0, y = 1", yourpoint.x, 28:yourPoint.y); 29: 30: 31: 1.1 Run the above program, write your output below, and explain how the program works: My Point: x=0, y=0 Your Point: x=10, y=10 เน องจากเราไม ได ก าหนดค าเร มต นให mypoint ด งน นค า mypoint.x, mypoint.y จ งเป น 0 แต yourpoint เราก าหนดค าให ด วย constructor Point(10,10) ด งน นค า yourpoint.x, yourpoint.y จ งม ค าเป น 10 1.2. If the line #9 is REPLACED by public Point() and line #11 is INSERTED with int p1, int p2; Can the program still compile? If not, explain why. โปรแกรมจะคอมไพล ไม ได เน องจากม ข อห ามในการสร าง constructor ท ไม ม parameter เลย (default constructor) เช น Point() เป นต น เน องจาก constructor ประเภทน จะถ กก าหนดให สร างค าต งต นเป น default ของ สมาช กใน struct อย แล ว Computer & Programming: Structs and Enumerations 2/13 Powered by MIKE TM
1.3. Change both lines (9 and 11) back to their original conditions as they were in question 1. Then comment out the line #12 (to look like // y = p2;) and try compiling the program. Can the program still compile? If not, explain why. โปรแกรมจะคอมไพล ไม ได เน องจากการสร าง constructor ( method ท ม ช อเด ยวก บช อ struct ) น น จะต อง สามารถก าหนดค าเร มต นให ก บสมาช กท กต วของ struct น นได ในกรณ น constructor ไม สามารถก าหนดค าต งต นให ก บ สมาช ก y ได จ งเก ด error ข น 1.4. Change the line #12 back to its original condition as it was in question 1. Then change the line #7 to public int x=0, y; Try compiling the program. Can the program still compile? If not, explain why. โปรแกรมจะคอมไพล ไม ได เน องจากในการสร าง struct เราไม สามารถก าหนดค าเร มต นให ก บแต ละฟ ลด (เช น x หร อ y) ได โปรแกรมจะยอมให ก าหนดค าเร มต นผ านทาง constructor หร อการก าหนดค าให จากภายนอกเท าน น ด งน นเม อ เราพยายามท จะก าหนดค าต งต นให x จ งเก ด error ข น Computer & Programming: Structs and Enumerations 3/13 Powered by MIKE TM
1.5 Write a program to store contact information of your friends by using struct as a method to store each of your friend s contact. Your program will accept n number of contacts. Each Contact struct contains first name, last name, address, phone number, email address, and date of birth (DOB) fields. All of the fields, except for the DOB, are of string type. The DOB field is also a struct type consisting of three integer fields: day, month, and year. An example of the ouput of the program is shown below; The bold-faced texts are what you type in. Please enter the number of contacts: 2 Please enter the first name: monchai Please enter the last name: sopitkamon Please enter an email address: fengmcs@ku.ac.th Please enter the day of birth (1-31): 01 Please enter the month of birth (1-12): 01 Please enter the year of birth: 1970 Please enter the first name: somchai Please enter the last name: ratanachote Please enter an email address: fengscr@ku.ac.th Please enter the day of birth (1-31): 18 Please enter the month of birth (1-12): 11 Please enter the year of birth: 1960 monchai sopitkamon 50 Phaholyothin Rd. 02-942-8555 x 1432 fengmcs@ku.ac.th 1/1/1970 somchai ratanachote 50 Phayothin Rd. 02-942-8555 x 1111 fengscr@ku.ac.th 18/11/1960 Computer & Programming: Structs and Enumerations 4/13 Powered by MIKE TM
Fill in the blanks of the following part of code to make the program work. using System; namespace ex10_15 public struct DOB // Declares Date of Birth (DOB) struct public int day; // declares day field public int month; // declares month field public int year; // declare year field public DOB(int d,int m, int y) // Constructor for DOB struct day=d; // day assignment month=m; // month assignment year=y; // year assignment public struct Contact // Declare Contact struct public string firstname; // declares first name field public string lastname; // declares last name field public string email; // declares email field public DOB dateofbirth; // declares DOB field class MainClass public static void entercontact(ref Contact cont) // This method is used to fill in all fields of Contact struct Console.Write("Please enter the first name: "); cont.firstname=console.readline(); Console.Write("Please enter the last name: "); cont.lastname=console.readline(); Console.Write("Please enter an email address: "); cont.email=console.readline(); Console.Write("Please enter the day of birth (1-31): "); int dd=int.parse(console.readline()); Console.Write("Please enter the month of birth (1-12): "); int mm=int.parse(console.readline()); Console.Write("Please enter the year of birth: "); int yy=int.parse(console.readline()); cont.dateofbirth = new DOB(dd,mm,yy); // Instantiate DOB struct public static void showcontact(contact cont) // This method writes out all fields of a Contact struct Console.Write("0 ",cont.firstname);// writes first name Console.WriteLine(cont.lastname); // writes last name Console.WriteLine(cont.email); // writes email // writes DOB in DD/MM/YY format Console.WriteLine("0/1/2", cont.dateofbirth.day,cont.dateofbirth.month,cont.dateofbirth.year); Computer & Programming: Structs and Enumerations 5/13 Powered by MIKE TM
public static void Main() Console.Write("Please enter the number of contacts: "); int n = int.parse(console.readline()); // creates and instantiates a one-dimension array // of Contact struct with n elements Contact[] conts = new Contact[n]; for (int i=0; i<n; i++) // Fills in all fields of each element of Contact struct Console.WriteLine(" ", i); entercontact(ref conts[i]); Console.WriteLine(); for (int i=0; i<n; i++) //Writes out all fields of each element of Contact struct Console.WriteLine(" ", i); showcontact(conts[i]); Console.WriteLine(""); // ends Main() // ends class // ends namespace 2 Enumerations An enum type is a distinct value type (Section 4.1) that declares a set of named constants. The example enum Color Red, Green, Blue declares an enum type named Color with members Red, Green, and Blue. Enum declarations An enum declaration declares a new enum type. An enum declaration begins with the keyword enum, and defines the name, accessibility, underlying type, and members of the enum. enum-declaration: attributesopt enum-modifiersopt enum identifier enum-baseopt enum-body ;opt enum-base: ; integral-type enum-body: enum-member-declarationsopt enum-member-declarations, Each enum type has a corresponding integral type called the underlying type of the enum type. This underlying type must be able to represent all the enumerator values defined in the enumeration. An enum declaration may explicitly declare an underlying type of byte, sbyte, short, ushort, int, uint, long or ulong. Note that char cannot be used as an underlying type. An enum declaration that does not explicitly declare an underlying type has an underlying type of int. The example Computer & Programming: Structs and Enumerations 6/13 Powered by MIKE TM
enum Color: long Red, Green, Blue declares an enum with an underlying type of long. A developer might choose to use an underlying type of long, as in the example, to enable the use of values that are in the range of long but not in the range of int, or to preserve this option for the future. 2.1 Create an enumeration type named Month of integral type whose members are months of year (i.e., Jan, Feb,, Dec). Write your code below. enum Month: int Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec Enum members The body of an enum type declaration defines zero or more enum members, which are the named constants of the enum type. No two enum members can have the same name. enum-member-declarations: enum-member-declaration enum-member-declarations, enum-member-declaration enum-member-declaration: attributesopt identifier attributesopt identifier = constant-expression Each enum member has an associated constant value. The type of this value is the underlying type for the containing enum. The constant value for each enum member must be in the range of the underlying type for the enum. Multiple enum members may share the same associated value. The example enum Color Red, Green, Blue, Max = Blue shows an enum in which two enum members Blue and Max have the same associated value. The associated value of an enum member is assigned either implicitly or explicitly. If the declaration of the enum member has a constant-expression initializer, the value of that constant expression, implicitly converted to the underlying type of the enum, is the associated value of the enum member. If the declaration of the enum member has no initializer, its associated value is set implicitly, as follows: * If the enum member is the first enum member declared in the enum type, its associated value is zero. * Otherwise, the associated value of the enum member is obtained by increasing the associated value of the textually preceding enum member by one. This increased value must be Computer & Programming: Structs and Enumerations 7/13 Powered by MIKE TM
within the range of values that can be represented by the underlying type; otherwise, a compiletime error occurs. The example using System; enum Color Red, Green = 10, Blue class Test static void Main() Console.WriteLine(StringFromColor(Color.Red)); Console.WriteLine(StringFromColor(Color.Green)); Console.WriteLine(StringFromColor(Color.Blue)); static string StringFromColor(Color c) switch (c) case Color.Red: return String.Format("Red = 0", (int) c); case Color.Green: return String.Format("Green = 0", (int) c); case Color.Blue: return String.Format("Blue = 0", (int) c); default: return "Invalid color"; prints out the enum member names and their associated values. The output is: Red = 0 Green = 10 Blue = 11 2.2 Apply the enumeration type Month from exercise 2.1 to your final code of exercise 1.5, so that the output of the date of birth (DOB) in exercise 1.5 shows a month of year (Jan, Feb, etc.), instead of an integer (1, 2, and etc.). For example, with the same set of input data as in exercise 1.5, the output of the showcontact() method would produce the result as follows: monchai sopitkamon fengmcs@ku.ac.th 1/Jan/1970 somchai ratanachote fengscr@ku.ac.th 18/Nov/1960 Computer & Programming: Structs and Enumerations 8/13 Powered by MIKE TM
Write your updated codes in the DOB struct and entercontact() method in the provided blanks below. public enum Month: int Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec public struct DOB // Declares Date of Birth (DOB) struct public int day; // declares day field public Month month; // declares month field public int year; // declare year field public DOB(int d,month m, int y) // Constructor for DOB struct day=d; // day assignment month=m; // month assignment year=y; // year assignment public struct Contact // Declare Contact struct public string firstname; // declares first name field public string lastname; // declares last name field public string email; // declares email field public DOB dob; // declares DOB field class MainClass public static void entercontact(ref Contact cont) // This method is used to fill in all fields of Contact struct Console.Write("Please enter the first name: "); cont.firstname=console.readline(); Console.Write("Please enter the last name: "); cont.lastname=console.readline(); Console.Write("Please enter an email address: "); cont.email=console.readline(); Console.Write("Please enter the day of birth (1-31): "); int dd=int.parse(console.readline()); Console.Write("Please enter the month of birth (1-12): "); int mm=int.parse(console.readline()); Console.Write("Please enter the year of birth: "); int yy=int.parse(console.readline()); cont.dob = new DOB(dd,(Month) mm-1,yy); // Instantiate DOB struct Enum values and operations Each enum type defines a distinct type; an explicit enumeration conversion (Section 6.2.2) is required to convert between an enum type and an integral type, or between two enum types. The set of values that an enum type can take on is not limited by its enum members. In particular, any value of the underlying type of an enum can be cast to the enum type, and is a distinct valid value of that enum type. Enum members have the type of their containing enum type (except within other enum member initializers: see Section 14.3). The value of an enum member declared in enum type E with associated value v is (E)v. The following operators can be used on values of enum types: ==,!=, <, >, <=, >=, +, -, ^, &,, ~, ++, --, sizeof. Computer & Programming: Structs and Enumerations 9/13 Powered by MIKE TM
2.3 Using the result of exercise 2.2, together with codes from exercises 1.5 and 2.2, add a method called IsSameMonth() and add extra codes to the end of the Main() method of exercise 1.5, to check to see if two people from Contact i and Contact j (i j and i and j are both valid Contact numbers), i) are born in the same month, ii) Contact i is younger than Contact j in term of month, and iii) Contact i is older than Contact j in term of month. The IsSameMonth() method takes two different Contacts as its input, performs the month comparison, writes out the comparison result, and returns nothing back to Main(). An example of the output showing all three possible cases as shown below (The bold-faced texts represent the user s input): Please enter the number of contacts: 2 Please enter the first name: monchai Please enter the last name: sopitkamon Please enter an email address: fengmcs@ku.ac.th Please enter the day of birth (1-31): 01 Please enter the month of birth (1-12): 01 Please enter the year of birth: 1970 Please enter the first name: somchai Please enter the last name: ratanachote Please enter an email address: fengscr@ku.ac.th Please enter the day of birth (1-31): 18 Please enter the month of birth (1-12): 11 Please enter the year of birth: 1960 monchai sopitkamon fengmcs@ku.ac.th 1/Jan/1970 somchai ratanachote fengscr@ku.ac.th 18/Nov/1960 Enter contact number of the first person to compare months: 0 Enter contact number of the second person to compare months: 1 monchai is older than somchai in term of month Please enter the number of contacts: 2 Please enter the first name: monchai Please enter the last name: sopitkamon Please enter an email address: fengmcs@ku.ac.th Please enter the day of birth (1-31): 01 Please enter the month of birth (1-12): 06 Please enter the year of birth: 1970 Please enter the first name: somchai Please enter the last name: ratanachote Please enter an email address: fengscr@ku.ac.th Please enter the day of birth (1-31): 10 Please enter the month of birth (1-12): 06 Please enter the year of birth: 1960 Computer & Programming: Structs and Enumerations 10/13 Powered by MIKE TM
monchai sopitkamon fengmcs@ku.ac.th 1/Jun/1970 somchai ratanachote fengscr@ku.ac.th 10/Jun/1960 Enter contact number of the first person to compare months: 0 Enter contact number of the second person to compare months: 1 monchai was born on the same month as somchai Please enter the number of contacts: 2 Please enter the first name: monchai Please enter the last name: sopitkamon Please enter an email address: fengmcs@ku.ac.th Please enter the day of birth (1-31): 01 Please enter the month of birth (1-12): 12 Please enter the year of birth: 1970 Please enter the first name: somchai Please enter the last name: ratanachote Please enter an email address: fengscr@ku.ac.th Please enter the day of birth (1-31): 10 Please enter the month of birth (1-12): 6 Please enter the year of birth: 1960 monchai sopitkamon fengmcs@ku.ac.th 1/Dec/1970 somchai ratanachote fengscr@ku.ac.th 10/Jun/1960 Enter contact number of the first person to compare months: 0 Enter contact number of the second person to compare months: 1 monchai is younger than somchai in term of month Computer & Programming: Structs and Enumerations 11/13 Powered by MIKE TM
Fill in the provided blanks below. using System; namespace ex10_15 public enum Month: int Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec public struct DOB // Declares Date of Birth (DOB) struct public int day; public Month month; public int year; // declares day field // declares month field // declare year field public DOB(int d,month m, int y) // Constructor for DOB struct day=d; // day assignment month=m; // month assignment year=y; // year assignment public struct Contact // Declare Contact struct public string firstname;// declares first name field public string lastname; // declares last name field public string email; // declares email field public DOB dob; // declares DOB field class MainClass public static void entercontact(ref Contact cont) // This method is used to fill in all fields of Contact struct Console.Write("Please enter the first name: "); cont.firstname=console.readline(); Console.Write("Please enter the last name: "); cont.lastname=console.readline(); Console.Write("Please enter an email address: "); cont.email=console.readline(); Console.Write("Please enter the day of birth (1-31): "); int dd=int.parse(console.readline()); Console.Write("Please enter the month of birth (1-12): "); int mm=int.parse(console.readline()); Console.Write("Please enter the year of birth: "); int yy=int.parse(console.readline()); cont.dob = new DOB(dd,(Month) mm-1,yy); // Instantiate DOB struct public static void showcontact(contact cont) // This method writes out all fields of a Contact struct Console.Write("0 ",cont.firstname);// writes first name Console.WriteLine(cont.lastname); // writes last name Console.WriteLine(cont.email); // writes email // writes DOB in DD/MM/YY format Console.WriteLine("0/1/2", cont.dob.day,(month) cont.dob.month,cont.dob.year); Computer & Programming: Structs and Enumerations 12/13 Powered by MIKE TM
public static void IsSameMonth(Contact cont1, Contact cont2) if(cont1.dob.month==cont2.dob.month) Console.WriteLine("0 was born on the same month as 1", cont1.firstname,cont2.firstname); else if(cont1.dob.month<cont2.dob.month) Console.WriteLine("0 is older than 1 in term of month", cont1.firstname,cont2.firstname); else if(cont1.dob.month>cont2.dob.month) Console.WriteLine("0 is younger than 1 in term of month", cont1.firstname,cont2.firstname); public static void Main() Console.Write("Please enter the number of contacts: "); int n = int.parse(console.readline()); // creates and instantiates a one-dimension array of Contact struct // with n elements Contact[] conts = new Contact[n]; for (int i=0; i<n; i++) // Fills in all fields of each element of Contact struct Console.WriteLine(" ", i); entercontact(ref conts[i]); Console.WriteLine(); for (int i=0; i<n; i++) //Writes out all fields of each element of Contact struct Console.WriteLine(" ", i); showcontact(conts[i]); Console.WriteLine(""); Console.Write("Enter contact number of the first person to compare months: "); int a = int.parse(console.readline()); Console.Write("Enter contact number of the second person to compare months: "); int b = int.parse(console.readline()); IsSameMonth(conts[a],conts[b]); // ends Main() // ends class // ends namespace Computer & Programming: Structs and Enumerations 13/13 Powered by MIKE TM