0% found this document useful (0 votes)
32 views

Lecture 8 - Structure

The document discusses visual programming using C# and .NET. It provides an overview of topics that will be covered in the course, including C# syntax, language constructs, developing graphical applications using structs and enums, type-safe collections, handling events, inheritance, entity data models, LINQ, XAML, tasks and concurrency. The course aims to teach students how to develop graphical applications using C# and .NET.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Lecture 8 - Structure

The document discusses visual programming using C# and .NET. It provides an overview of topics that will be covered in the course, including C# syntax, language constructs, developing graphical applications using structs and enums, type-safe collections, handling events, inheritance, entity data models, LINQ, XAML, tasks and concurrency. The course aims to teach students how to develop graphical applications using C# and .NET.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Visual Programming

Department of CSE, QUEST


Dr. Irfana Memon
Dr. Irfana Memon
Department of CSE, QUEST

https://sites.google.com/a/quest.edu.pk/dr-irfana-memon/lecture-slides
Course Content
Review of C# Syntax: Overview of Writing Applications using C#, Data types, Operators, and
Expressions
C# Programming Language Constructs, Creating Methods
Invoking Methods, Handling Exceptions, Creating overloaded Methods

Developing the Code for a Graphical Application: Implementing Structs and Enums
Implementing Type-safe Collections: Creating Classes, Organizing Data into Collections,

Department of CSE, QUEST


Dr. Irfana Memon
Handling Events, Defining and Implementing Interfaces
Creating a Class Hierarchy by Using Inheritance, Extending .NET Framework Classes,
Creating Generic Types
Accessing a Database: Creating and Using Entity Data Models, Querying and Updating Data
by Using LINQ
Designing the User Interface for a Graphical Application: Using XAML, Binding Controls to
Data, Styling a User Interface
Improving Application Performance and Responsiveness: Implementing Multitasking by
using Tasks and Lambda Expressions
2
Performing Operations Asynchronously, Synchronizing Concurrent Access to Data
Developing the Code for
a Graphical Application:

Department of CSE, QUEST


Dr. Irfana Memon
Implementing Structs
and Enums

3
C# Structures
• In C#, a structure is a value type data type. It helps you to
make a single variable hold related data of various data
types.
• The struct keyword is used for creating a structure.
• Structures are used to represent a record.
• Suppose you want to keep track of your books in a library.

Department of CSE, QUEST


Dr. Irfana Memon
• You might want to track the following attributes about each
book:
 Title
 Author
 Subject
 Book ID

4
Defining a Structures
• To define a structure, you must use the struct statement.
• The struct statement defines a new data type, with more than one
member for your program.
For example, here is the way you can declare the Book structure −

struct Books
{
public string title;

Department of CSE, QUEST


Dr. Irfana Memon
public string author;
public string subject;
public int book_id;
};

5
Defining a Structures
using System;
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};

Department of CSE, QUEST


Dr. Irfana Memon
public class testStructure
{
public static void Main(string[] args)
{
Books Book1; /* Declare Book1 of type Book */
Books Book2; /* Declare Book2 of type Book */ /* book 1 specification */
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book1.subject = "C Programming Tutorial";
Book1.book_id = 6495407; /* book 2 specification */ 6
Book2.title = "Telecom Billing";
Defining a Structures
Book2.author = "Zara Ali";
Book2.subject = "Telecom Billing Tutorial";
Book2.book_id = 6495700; /* print Book1 info */
Console.WriteLine( "Book 1 title : {0}", Book1.title);
Console.WriteLine("Book 1 author : {0}", Book1.author);
Console.WriteLine("Book 1 subject : {0}", Book1.subject);
Console.WriteLine("Book 1 book_id :{0}", Book1.book_id); /* print Book2 info */
Console.WriteLine("Book 2 title : {0}", Book2.title);
Console.WriteLine("Book 2 author : {0}", Book2.author);

Department of CSE, QUEST


Dr. Irfana Memon
Console.WriteLine("Book 2 subject : {0}", Book2.subject);
Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);
Console.ReadKey();
}
}

7
Features of C# Structures
• You have already used a simple structure named Books.
• Structures in C# are quite different from that in traditional C
or C++.
• The C# structures have the following features:
 Structures can have methods, fields, indexers, properties,
operator methods, and events.

Department of CSE, QUEST


Dr. Irfana Memon
 Structures can have defined constructors, but not
destructors. However, you cannot define a default
constructor for a structure. The default constructor is
automatically defined and cannot be changed.

8
Features of C# Structures
 Unlike classes, structures cannot inherit other structures
or classes.
 Structures cannot be used as a base for other structures
or classes.
 A structure can implement one or more interfaces.
 Structure members cannot be specified as abstract,

Department of CSE, QUEST


Dr. Irfana Memon
virtual, or protected.
 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 the New operator is not used, the fields remain
unassigned and the object cannot be used until all the
fields are initialized. 9
Exercise
Write a C# program to keep records and perform statistical analysis for a class of 20
students. The information of each student contains ID, Name, Sex, quizzes Scores (2
quizzes per semester), mid-term score, final score, and total score.
The program will prompt the user to choose the operation of records from a menu as
shown below:
========================================================
MENU
========================================================
1. Add student records

Department of CSE, QUEST


Dr. Irfana Memon
2. Delete student records

3. Update student records

4. View all student records

5. Calculate an average of a selected student’s scores

6. Show student who gets the max total score

7. Show student who gets the min total score

8. Find student by ID
9. Sort records by total scores 10
Enter your choice:1
Note: All students records are stored in an array of structures
Solution
Step1: Declaring a structure called student
to store the records
struct student
{
public string stnumber;
public string stname;
public string sex;
public float quizz1;
public float quizz2;
public float assigment;
public float midterm;

Department of CSE, QUEST


Dr. Irfana Memon
public float final;
public float total;
};

11
Solution
Step1: Declaring a structure called student
to store the records
struct student
{
public string stnumber;
public string stname;
public string sex;
public float quizz1;
public float quizz2;
public float assigment;
public float midterm; Step2: Defining the displaymenu() method to display the menu. The simple menu

Department of CSE, QUEST


Dr. Irfana Memon
public float final; provides nine choices from 1 to 9 to work with the records.
public float total; static void displaymenu()
}; {
Console.WriteLine("================================================");
Console.WriteLine(" MENU ");
Console.WriteLine("================================================");
Console.WriteLine(" 1.Add student records");
Console.WriteLine(" 2.Delete student records");
Console.WriteLine(" 3.Update student records");
Console.WriteLine(" 4.View all student records");
Console.WriteLine(" 5.Calculate an average of a selected student's scores");
Console.WriteLine(" 6.Show student who get the max total score");
Console.WriteLine(" 7.Show student who get the min total score"); 12
Console.WriteLine(" 8.Find a student by ID");
Console.WriteLine(" 9.Sort students by TOTAL");
}
Solution
Step3: defining the add(student[] st, ref int itemcount) method to add a new record to the the array of
student objects. This method takes two arguments. The first argument is the array of student objects(st) and
the second argument is the number of items in the array. The two arguments are passed by references. For an
array, we don't need to use the ref keyword when we want to pass it by reference. However, we need to use
the ref keyword when we want to pass an argument of primitive type such as int, float, dobule,etc. When the
new item is added the value itemcount variable increases by 1 that means the number of records in the list
increases.
Console.Write("Enter student's mid term
//method add/append a new record
score:");
static void add(student[] st,ref int itemcount){
st[itemcount].midterm=float.Parse(Console.Re
Again:
adLine());
Console.WriteLine();
Console.Write("Enter student's final score:");
Console.Write("Enter student's ID:");
st[itemcount].final=float.Parse(Console.ReadLi

Department of CSE, QUEST


Dr. Irfana Memon
st[itemcount].stnumber=Console.ReadLine().ToString() ;
ne());
//making sure the record to be added doesn't already exist
st[itemcount].total=st[itemcount].quizz1+st[ite
if(search(st,st[itemcount].stnumber,itemcount)!=-1){
mcount].quizz2+st[itemcount].assigment+st[it
Console.WriteLine("This ID already exists.");
emcount].midterm+st[itemcount].final;
goto Again;
++itemcount; //increase the number of items
}
by one
Console.Write("Enter student's Name:");
}
st[itemcount].stname=Console.ReadLine ().ToString();
Console.Write("Enter student's Sex(F or M):");
st[itemcount].sex=Console.ReadLine().ToString();
Console.Write("Enter student's quizz1 score:");
st[itemcount].quizz1=float.Parse(Console.ReadLine());
Console.Write("Enter student's quizz2 score:"); 13
st[itemcount].quizz2=float.Parse(Console.ReadLine());
Console.Write("Enter student's assigment score:");
st[itemcount].assigment=float.Parse(Console.ReadLine());
Solution
Step4: Defining the viewall(student[] st, int itemcount) method to display the list of all records
in the set. To display all records, we need a while loop to traverse through the array of student
objects.
static void viewall(student[] st,int itemcount)
{
int i = 0;
Console.WriteLine("{0,-5}{1,-20}{2,-5}{3,-5}{4,-5}{5,-5}{6,-5}{7,-5}{8}(column index)", "0", "1",
"2", "3", "4", "5", "6", "7", "8");
Console.WriteLine("{0,-5}{1,-20}{2,-5}{3,-5}{4,-5}{5,-5}{6,-5}{7,-5}{8,-5}", "ID", "NAME", "SEX",
"Q1", "Q2", "As", "Mi", "Fi", "TOTAL");

Department of CSE, QUEST


Dr. Irfana Memon
Console.WriteLine("=====================================================");
while (i < itemcount)
{
if (st[i].stnumber !=null )
{
Console.Write("{0,-5}{1,-20}{2,-5}", st[i].stnumber, st[i].stname, st[i].sex);
Console.Write("{0,-5}{1,-5}{2,-5}",st[i].quizz1,st[i].quizz2,st[i].assigment);
Console.Write("{0,-5}{1,-5}{2,-5}",st[i].midterm,st[i].final,st[i].total);
Console.Write("\n");
}
i = i + 1;
14
}
}
Solution
Step5: Defining the search(student[] st, int itemcount)
method to search for the index of a target record. This
method is useful as we need it to find the location of the
target record in the array of student objects. It can help us
to make sure the record does exit before we allow the
record for deletion or updating. If the target element is
found, the method returns the index of this element. It
return -1, if the target element is not found in the array.

static int search(student[] st, string id,int itemcount){


int found =-1;
for (int i = 0; i < itemcount && found==-1; i++)

Department of CSE, QUEST


Dr. Irfana Memon
{

if (st[i].stnumber == id) found=i;

else found=-1 ;
}

return found;

15
Solution
Step6: Defining the delete(student[] st, ref int itemcount) method to delete a target record from the array of
student objects. The user will be prompted to enter the id of student record that his/her want to delete. Then
this id will be checked to make sure it does exist in the list. If the target record or element really exists, the
deletion process can be made. The deletion process starts by checking whether the target record is the last
record, beginning or middle record. If the target record is the last record in the list, we simply delete the
record by supplying it to the clean(student[] st, int index) method. The last record is the record that has it
index equal to itemcount subtracted by 1. If the target record stays at the beginning or in the middle of the
list, we need to use a loop to allow the previous element to take over the next element. This process continue
until it reaches the end of the list(itemcount-1). Then the clean() method is called to clean the last element of
the list that should not exit. After the element is cleaned, the itemcount variable decreases by 1. This means
that the number of elements in the list decreases.
clean(st, index);

Department of CSE, QUEST


Dr. Irfana Memon
static void delete(student[] st, ref int itemcount) --itemcount;
{
string id; Console.WriteLine("The record was deleted.");
int index; }
if (itemcount > 0) else //delete the first or middle record
{ {
Console.Write("Enter student's ID:"); for (int i = index; i < itemcount-1; i++)
id = Console.ReadLine(); {
index = search(st, id.ToString(),itemcount); st[i] = st[i + 1];

if ((index!=-1) && (itemcount != 0))


{
if (index == (itemcount-1)) //delete the last record 16
{
Solution
Step6: (Continue) st[index].stnumber = null;
st[index].stname = null;
clean(st, index); st[index].sex = null;
--itemcount; st[index].quizz1 = 0;
st[index].quizz2 = 0;
Console.WriteLine("The record was deleted."); st[index].assigment = 0;
} st[index].midterm = 0;
else //delete the first or middle record st[index].final = 0;
{ st[index].total = 0;
for (int i = index; i < itemcount-1; i++)
{ }
st[i] = st[i + 1];

Department of CSE, QUEST


Dr. Irfana Memon
clean(st, itemcount);
--itemcount ;
}}}
else Console.WriteLine("The record doesn't exist. Check
the ID and try again.");
}
else Console.WriteLine("No record to delete");
}
static void clean(student[] st,int index)
{

17
Solution
Step7: Defining the update_rec(struct student st[], int itemcount) method to update a specified record. The
update process starts by asking the user to input the id of the record to be changed. The id value is check to
make sure it really exists. If it exits the change to the target record can be made after asking the user to input
the new value of the field that need change. else if (column_index == 2)
{
static void update(student[] st, int itemcount) Console.Write("Enter student's Sex(F or M):");
{ st[index].sex = Console.ReadLine().ToString();
string id; }
int column_index; else if (column_index == 3)
Console.Write("Enter student's ID:"); {
id=Console.ReadLine(); Console.Write("Enter student's quizz1 score:");
Console.Write("Which field you want to update(1-7)?:"); st[index].quizz1 = float.Parse(Console.ReadLine());

Department of CSE, QUEST


Dr. Irfana Memon
column_index=int.Parse(Console.ReadLine()); }
else if (column_index == 4)
int index = search(st, id.ToString(),itemcount); {
Console.Write("Enter student's quizz2 score:");
if ((index != -1) && (itemcount != 0)) st[index].quizz2 = float.Parse(Console.ReadLine());
{ }
if (column_index == 1) else if (column_index == 5)
{ {
Console.Write("Enter student's Name:"); Console.Write("Enter student's assigment score:");
st[index].assigment = float.Parse(Console.ReadLine());
st[index].stname = Console.ReadLine().ToString(); }
} else if (column_index == 6) 18
{
Console.Write("Enter student's mid term score:");
st[index].midterm = float.Parse(Console.ReadLine());
}
Solution
Step7: (Continue)

else if (column_index == 7)
{
Console.Write("Enter student's final score:");
st[index].final = float.Parse(Console.ReadLine());
}
else Console.WriteLine("Invalid column index");
st[index].total = st[index].quizz1 + st[index].quizz2 +
st[index].assigment + st[index].midterm + st[index].final;

Department of CSE, QUEST


Dr. Irfana Memon
}
else Console.WriteLine("The record deosn't exits.Check
the ID and try again.");

19
Solution
Step8: Defining the average(student[] st, int itemcount) method to calculate the average score of a selected
student. The method alo starts by asking the user to input the id of the target student. This id is checked to
make sure it really exist. The average score can be calculated by dividing the sum of quizz1 score, quizz2
score, assignment score, mid-term score, and final score by 5.
static void average(student[] st, int itemcount)
{
string id;
float avg=0;
Console.Write("Enter students'ID:");
id = Console.ReadLine();

Department of CSE, QUEST


Dr. Irfana Memon
int index = search(st, id.ToString(),itemcount);
if (index != -1 && itemcount>0)
{
st[index].total = st[index].quizz1 + st[index].quizz2 + st[index].assigment + st[index].midterm +
st[index].final;
avg = st[index].total /5;
}

Console.WriteLine("The average score is {0}.", avg);


}

20
Solution
Step9: Defining the showmax(student[] st, int itemcount) and showmin(student[] st, int itemcount)
methods show about the student who gets the maximum score and the student who gets the minimum
score. To find the highest total core or lowest total core, we need to compare every total score of each
element.
static void showmax(student[] st, int itemcount)
{
float max = st[0].total;
int index=0;
Console.WriteLine(itemcount);
if (itemcount >= 2)
{
for (int j = 0; j < itemcount-1; ++j)

Department of CSE, QUEST


Dr. Irfana Memon
if (max < st[j+1].total) {
max = st[j+1].total;
index = j+1;
}
}
else if (itemcount == 1)
{
index = 0;
max = st[0].total;
}
else Console.WriteLine("Not record found!");
if (index != -1) Console.WriteLine("The student with ID:{0} gets the highest score {1}.", st[index].stnumber,
max); 21
}
\
Solution
static void showmin(student[] st, int itemcount)
{
float min = st[0].total;
int index = 0;
if (itemcount >= 2)
{
for (int j = 0; j < itemcount-1; ++j)
if (min > st[j+1].total)
{
min = st[j+1].total;

Department of CSE, QUEST


Dr. Irfana Memon
index = j+1;
}
}
else if (itemcount == 1)
{
index = 0;
min = st[0].total;
}
else Console.WriteLine("No record found!");
if (index != -1) Console.WriteLine("The student with ID:{0} gets the lowest score {1}.", st[index].stnumber,
min);
}
22
Solution
//method to find record
static void find(student[] st, int itemcount)
{
string id;
Console.Write("Enter student's ID:");
id=Console.ReadLine();

int index=search(st,id.ToString(),itemcount);
if (index != -1)
{

Department of CSE, QUEST


Dr. Irfana Memon
Console.Write("{0,-5}{1,-20}{2,-5}", st[index].stnumber, st[index].stname, st[index].sex);

Console.Write("{0,-5}{1,-5}{2,-5}", st[index].quizz1, st[index].quizz2, st[index].assigment);

Console.Write("{0,-5}{1,-5}{2,-5}", st[index].midterm, st[index].final, st[index].total);


Console.WriteLine();

}
else Console.WriteLine("The record deosn't exits.");

}
23
C# Enums
• An enumeration is a set of named integer constants.
• An enumerated type is declared using the enum keyword.
• C# enumerations are value data type.
• In other words, enumeration contains its own values and
cannot inherit or cannot pass inheritance.
Declaring enum Variable
The general syntax for declaring an enumeration is −

Department of CSE, QUEST


Dr. Irfana Memon
enum <enum_name> { enumeration list };
Where,
•The enum_name specifies the enumeration type name.
•The enumeration list is a comma-separated list of identifiers.
• Each of the symbols in the enumeration list stands for an
integer value, one greater than the symbol that precedes it.
• By default, the value of the first enumeration symbol is 0. For 24
example −
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
Declaring C# Enums

Declaring enum Variable


The general syntax for declaring an enumeration is −
enum <enum_name> { enumeration list };
Where,
•The enum_name specifies the enumeration type name.

Department of CSE, QUEST


Dr. Irfana Memon
•The enumeration list is a comma-separated list of identifiers.
• Each of the symbols in the enumeration list stands for an
integer value, one greater than the symbol that precedes it.
• By default, the value of the first enumeration symbol is 0. For
example −
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
25
Example (C# Enums)
The following example demonstrates use of enum variable −

using System;
namespace EnumApplication
{
class EnumProgram
{
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
static void Main(string[] args)

Department of CSE, QUEST


Dr. Irfana Memon
{
int WeekdayStart = (int)Days.Mon;
int WeekdayEnd = (int)Days.Fri;
Console.WriteLine("Monday:{0}",WeekdayStart);
Console.WriteLine("Friday:{0}",WeekdayEnd); Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the
26
following result −
Monday: 1
Friday: 5
Wish You Good Luck

Dr. Irfana Memon


27

Department of CSE, QUEST

You might also like