advanced programming using c# · visual studio.net ide •integrated development environment...
Post on 22-Jun-2020
3 Views
Preview:
TRANSCRIPT
MSc PROGRAMMING Dr Rupak Kharel
E343
r.kharel@mmu.ac.uk
Assessment
• 3 Courseworks
• Course work 1 35% - Deadline 25/10/2013*
• Course work 2 35% - Deadline 10/01/2014
• Viva Exam 30% - Will decide after CW2
• Formative lab works
* Planning to change to add two more weeks
MSc Programming - Dr R. Kharel 2
Software
• Microsoft Visual Studio 2012/2010
• Student version can be obtained from www.dreamspark.com
• Or Visual C# Express edition can also be obtained from Microsoft
website
Moodle – all notes on here
http://moodle.mmu.ac.uk
MSc Programming - Dr R. Kharel 3
Bibliography
• Deitel & Deitel C# How to Program 3rd / 4th edition
Prentice Hall
• Professional C# 3rd Edition Wrox Press
• Software Engineering: A Practitioner's Approach, 6th
Edition Pressman et al.
Any standard C# book will be good enough. There are also
loads of materials available online. Just google.
MSc Programming - Dr R. Kharel 4
C, C++, .NET and Java (V)
• Java
• Sun Microsystems corporate research project (1991)
• Code-named Green
• Based on C and C++
• Intended for intelligent consumer-electronic devices
• Lack of popularity almost causes cancellation
• Sudden popularity of WWW provides new potential
• Java capable of dynamic content
• Animated and interactive content
• Grabbed attention of business community
• Now very widely used
• Enhance functionality of WWW servers
• Provide applications for consumer devices
MSc Programming - Dr R. Kharel 5
C#
• C#
• Developed at Microsoft
• Event driven, object oriented, visual programming language
• Based from C, C++ and Java
• Incorporated into .NET platform
• Web based applications can be distributed
• Devices and desktop computers
• Programs that can be accessed by anyone through any device
• Allows communicating with different computer languages
• Integrated Design Environment (IDE)
• Makes programming and debugging fast and easy
• Rapid Application Development (RAD)
MSc Programming - Dr R. Kharel 6
Structured Programming
• Early Software Development
• Complex and costly for businesses (1960s)
• Costs exceeded budgets
• Final products unreliable
• Research led to structured programming
• Disciplined approach to programming
• Programs clear and easy to modify
• Several languages resulted from research
• C, Pascal, Ada
MSc Programming - Dr R. Kharel 7
Structured Programming (II)
• Structured Languages
• Pascal
• Designed for teaching structured programming
• Lacked features for commercial use
• C
• Had features Pascal didn’t
• Quickly adopted by programmers
• Ada
• Developed by U.S. Department of Defense (late 1970s)
• Based on Pascal
• DOD wanted one language for all its needs
• Supported multitasking
• Many activities occur in parallel
MSc Programming - Dr R. Kharel 8
The Object Oriented Paradigm
• What is the Object Oriented Paradigm?
• A scheme for encapsulating properties and actions within a unit.
• The Units are called objects
• Any noun can be represented as an object
• Date object, time object, car object
• Have properties
• Size, color, weight
• Perform actions
• Moving, sleeping, drawing
• Defined in classes
• Specify general format
• Provide specific attributes and behaviors
MSc Programming - Dr R. Kharel 9
Object Oriented Technology (II)
• Object-Oriented programming
• Based on nouns
• This is the way we tend to think
• Advantages over structured programming
• More natural process
• Results in better productivity
• Classes (and hence objects) make more self contained code and hence
enhance reusability
• Code easier to maintain
• Programs more understandable
• Focus on behaviors and interactions
• Less attention to details (abstraction)
MSc Programming - Dr R. Kharel 10
An introduction to Microsoft .NET
• .NET initiative
• Introduced by Microsoft (June 2000)
• Vision for embracing the Internet in software development
• Independence from specific language or platform
• Applications developed in any .NET compatible language
• Visual Basic .NET, Visual C++ .NET, C# and more
• Programmers can contribute to applications using the language in which
they are most competent
• Architecture capable of existing on multiple platforms
• New program development process
• Provides increased productivity
MSc Programming - Dr R. Kharel 11
An introduction to Microsoft .NET (II)
• Key components of .NET
• Web services
• Applications used over the Internet
• Software reusability
• Web services provide solutions for wide variety of companies
• Cheaper than developing one-time solutions that can’t be reused
• Single applications perform all operations for a company via various Web
services
• Manage taxes, bills, investments and more
• Pre-packaged components
• Make application development quicker and easier
• Developers no longer need to be concerned with details of components
(abstraction)
MSc Programming - Dr R. Kharel 12
An introduction to Microsoft .NET (IV)
• Other concepts
• Universal data access
• Eliminates need to synchronize files
• Updating multiple copies of same file to the most recent
• Data resides at one central location
• Accessible by anyone with connection and proper authorization
• Data formatted appropriately for display on various devices
• Same document seen on PC, PDA, cell phone and other devices
• Additional information available at Microsoft Web site www.microsoft.com/net
MSc Programming - Dr R. Kharel 13
The .NET Framework and the Common
Language Runtime • .NET Framework
• Heart of .NET strategy
• Manages and executes applications and Web services
• Provides security, memory management and other programming
capabilities
• Includes Framework class library (FCL)
• Pre-packaged classes ready for reuse
• Used by any .NET language
• Details contained in Common Language Specification (CLS)
• Submitted to European Computer Manufacturers Association to make
the framework easily converted to other platforms
• Executes programs by Common Language Runtime (CLR)
MSc Programming - Dr R. Kharel 14
The .NET Framework and the Common
Language Runtime (II)
• Common Language Runtime (CLR)
• Central part of framework
• Executes .NET programs
• Compilation process
• Two compilations take place
• Programs compiled to Microsoft Intermediate Language
(MSIL)
• Defines instructions for CLR
• MSIL code translated into machine code
• Machine code for a particular platform
MSc Programming - Dr R. Kharel 15
.NET Framework and the Common
Language Runtime (III) • Why two compilations?
• Platform independence
• .NET Framework can be installed on different platforms
• Execute .NET programs without any modifications to code
• Language independence
• .NET programs not tied to particular language
• Programs may consist of several .NET-compliant languages
• Old and new components can be integrated
• Other advantages of CLR
• Execution-management features
• Manages memory, security and other features
• Relieves programmer of many responsibilities
• More concentration on program logic
MSc Programming - Dr R. Kharel 16
CLR
• Framework layer that resides above the OS and handle
the execution of all the .NET applications.
• Program don’t directly communication with the OS but
does it via CLR
MSc Programming - Dr R. Kharel 17
.NET Framework
• Combination of layers
MSc Programming - Dr R. Kharel 18
Visual Studio.NET IDE
• Integrated development environment
• Makes the process of developing .NET application easier
• We will be using VS 2012 (or 2010) for developing C#
applications
• This provides various development tools such as
• Keyword and syntax highlighting
• Intellisense (autocomplete)
• Compiling and building applications
• Program execution
• Depolyment
• Etc…
MSc Programming - Dr R. Kharel 19
Project and Solutions in VS.NET
• A project is a combination of executable and library that
make an application or modules
• Starts with extension .csproj where ‘cs’ is for C-sharp
• There are different types of projects such as
ConsoleApplication, WindowsFormApplication, ASP.NET
WebApplication, etc
• A solution is a placeholder for different logically related
project that make some application
• E.g. a solution might contain ASP.NET web application and a
windows form application
• .sln is the extension and can be managed by VS solution
explorer
MSc Programming - Dr R. Kharel 20
VS.NET 2012
• Give here a quick tour of VS.NET 2012
MSc Programming - Dr R. Kharel 21
First C# Application – Hello World (I)
• In VS, create one Console Application from File > New > Project > Visual C# > Windows > Console Application
• Give name HelloWorldProgram for the project
• You will see something like this
MSc Programming - Dr R. Kharel 22
1.using System;
2.using System.Collections.Generic;
3.using System.Linq;
4.using System.Text;
5.
6.namespace HelloWorldProgram
7.{
8. class Program
9. {
10. static void Main(string[] args)
11. {
12. }
13. }
14.}
First C# Application – Hello World (II)
• Add one line of code in line number 12
• Save and hit CTRL+F5 or select Debug > Start without debugging
MSc Programming - Dr R. Kharel 23
1.using System;
2.using System.Collections.Generic;
3.using System.Linq;
4.using System.Text;
5.
6.namespace HelloWorldProgram
7.{
8. class Program
9. {
10. static void Main(string[] args)
11. {
12. //This is my first program
13. Console.WriteLine("Hello World!!! \nThis is our first C#
program.\n");
14. }
15. }
16.}
MSc Programming - Dr R. Kharel 24
Understanding the Hello World Application
Namespaces
• Groups related C# features into a categories
• Allows the easy reuse of code
• Prevents name conflicts
• Must be referenced in order to be used
• Does not require physical mapping as opposed to Java
• Can be omitted when writing simple programs
MSc Programming - Dr R. Kharel 25
namespace HelloWorldProgram
{
………
}
Understanding the Hello World Application (II)
Using Keyword
• The first line of the program was
using System;
• This allows us to use all the classes in the System
namespace – concept of libraries
• This is found in virtually every C# program
Class Keyword
• All C# program contains at least one class
• This is a combination of data and methods. More on this
in near future
• One of the classes contains Main() method
MSc Programming - Dr R. Kharel 26
Understanding the Hello World Application (III)
The Main() method
Costatic void Main(string[] args)
• This is the entry point to the program, like a door to a building
• C# starts the program at the first line of the Main() method and terminates at the last line
• The method is static because an object is not initialized for class Program and directly called by CLR – static method will be better understood when we talk about classes, objects and methods in future
• The method is void() since it does not return anything – remember a method always returns something, if it does not then it returns void.
• string args[] is the list of arguments that can be supplied to the program during execution from command line – only important when writing console program, this can be omitted
MSc Programming - Dr R. Kharel 27
Understanding the Hello World Application (IV)
Printing on the Console
• This is the line that prints the output
Console.WriteLine("Hello World!!!
\nThis is our first C# program.\n");
• We used a static method Writeline() of the Console class defined in the System namespace
Comments
• These are used as the programmer’s text to explain the code and are ignored by the compiler
C# is case sensitive, so beware while using Main() not main() or void() not Void()
MSc Programming - Dr R. Kharel 28
Some escape sequences
MSc Programming - Dr R. Kharel 29
Escape sequence Description
\n Newline. Position the screen cursor to the beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next tab stop.
\r Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the previous characters output on that line.
\\ Backslash. Used to print a backslash character.
\" Double quote. Used to print a double quote (") character.
Some common escape sequences
Another simple program – Adding two
integers • Primitive data types
• Data types that are built into C#
• String, Int, Double, Char, Long
• 15 primitive data types
• Each data type name is a C# keyword
• Same type variables can be declared on separate lines or on one
line
• Console.ReadLine()
• Used to get a value from the user input
• Int32.Parse()
• Used to convert a string argument to an integer
• Allows math to be preformed once the string is converted
MSc Programming - Dr R. Kharel 30
MSc Programming - Dr R. Kharel 31
1.using System;
2.
3.namespace AdditionProgram
4.{
5. class Program
6. {
7. static void Main(string[] args)
8. {
9. string firstNumber, // first string entered by user
10. secondNumber; // second string entered by user
11.
12. int number1, // first number to add
13. number2, // second number to add
14. sum; // sum of number1 and number2
15.
16. // prompt for and read first number from user as string
17. Console.Write( "Please enter the first integer: " );
18. firstNumber = Console.ReadLine();
19.
20. // read second number from user as string
21. Console.Write( "\nPlease enter the second integer: " );
22. secondNumber = Console.ReadLine();
23.
24. // convert numbers from type string to type int
25. number1 = Int32.Parse( firstNumber );
26. number2 = Int32.Parse( secondNumber );
MSc Programming - Dr R. Kharel 32
27.
28. // add numbers
29. sum = number1 + number2;
30. // display results
31. Console.WriteLine( "\nThe sum of {0} and {1} is {2}.\n", number1,number2,sum
);
32.
33. } // end method Main
34.
35. } // end class Addition
36.} //end of namespace
Arithmetic Operators
MSc Programming - Dr R. Kharel 33
C# operation Arithmetic operator Algebraic expression C# expression
Addition + f + 7 f + 7
Subtraction – p – c p - c
Multiplication * bm b * m
Division / x / y x / y
Modulus % r mod s r % s
Arithmetic operators
Operator Precedence
MSc Programming - Dr R. Kharel 34
Operator(s) Operation Order of evaluation (precedence)
( ) Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.
*, / or % Multiplication Division Modulus
Evaluated second. If there are several such operators, they are evaluated left to right.
+ or - Addition Subtraction
Evaluated last. If there are several such operators, they are evaluated left to right.
Precedence of arithmetic operators
If in doubt, always use ( )
Equality and Relational Operators
MSc Programming - Dr R. Kharel 35
Standard algebraic equality operator or relational operator
C# equality or relational operator
Example of C# condition
Meaning of C# condition
Equality operators
= == x == y x is equal to y
!= x != y x is not equal to y
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y
Equality and relational operators.
Conditional Operators
Conditional And - &&
Conditional OR - | |
Conditional Statement and Iteration
• If-else statement
• Switch-case
• For loop
• While loop
• Do-while loop
MSc Programming - Dr R. Kharel 36
If-else selection structure
MSc Programming - Dr R. Kharel 37
If (Boolean Expression)
statement or block of statements
else
statement or block of statements
Nesting can also be done
If (door is closed)
if(have card)
swipe_the_card
Exit the building
else //do not have card
wait_for_somebody_to_come_with_card
if(some body came)
Exit the building
else //no body came
call_security
Exit the building
else //this means door is open
Exit the building
If-else Example
MSc Programming - Dr R. Kharel 38
Console.Write("Enter a character: ");
char c = (char)Console.Read();
if (Char.IsLetter(c))
{
if (Char.IsLower(c))
{
Console.WriteLine("The character is lowercase.");
}
else
{
Console.WriteLine("The character is uppercase.");
}
}
else
{
Console.WriteLine("Not an alphabetic character.");
}
Input:
2
Sample Output
Enter a character: 2
The character is not an alphabetic character
.
Additional sample might look as follows:
Run #2:
Enter a character: A
The character is uppercase.
Run #3:
Enter a character: h
The character is lowercase.
If-else Example Console.Write("Enter a character: ");
char c = (char)Console.Read();
if (Char.IsUpper(c))
{
Console.WriteLine("Character is uppercase.");
}
else if (Char.IsLower(c))
{
Console.WriteLine("Character is lowercase.");
}
else if (Char.IsDigit(c))
{
Console.WriteLine("Character is a number.");
}
else
{
Console.WriteLine("Character is not alphanumeric.");
}
MSc Programming - Dr R. Kharel 39
Enter a character: E The character is uppercase. Run #2 Enter a character: e The character is lowercase. Run #3: Enter a character: 4 The character is a number. Run #4: Enter a character: $ The character is not alphanumeric.
switch-case statement
• Performs a series of specific checks
switch(integral or string expression)
{
case constant-expression:
breaking or jump statement
//some other case blocks
…
default:
statements
breaking or jump statement
}
MSc Programming - Dr R. Kharel 40
Switch Case Example
Console.WriteLine("Coffee sizes: 1=Small 2=Medium 3=Large");
Console.Write("Please enter your selection: ");
string str = Console.ReadLine();
int switchExp = int.Parse(str);
int cost = 0;
switch (switchExp)
{
case 1:
cost = 25;
break;
case 2:
cost = 50;
break;
case 3:
cost = 75;
break;
default:
Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
break;
}
MSc Programming - Dr R. Kharel 41
if (cost != 0)
{
Console.WriteLine("Please insert {0} cents.", cost);
}
Console.WriteLine("Thank you for your business.");
Sample Output:
Coffee sizes: 1=Small 2=Medium 3=Large
Please enter your selection: 2
Please insert 50 cents.
Thank you for your business.
MSc Programming - Dr R. Kharel 42
for loop
• Loops are used for iteration purpose, to do a task multiple times until some condition is met.
for(assignment; condition; increment/decrement)
{
statements of block of statements
}
e.g.
for(int i=1; i<=5; i++)
{
Console.WriteLine(“Printing Line {0}\n”,i);
}
MSc Programming - Dr R. Kharel 43
while loop
• Checks the condition before entering the first iteration.
while(Boolean expression)
{
statements or block of statements
}
e.g.
int i=1;
while(i<=5)
{
Console.WriteLine(“Printing Line {0}\n”,i);
i++;
}
MSc Programming - Dr R. Kharel 44
do-while loop
• Performs the conditional check after executing the statements once, therefore the statements are executed at least once even if the condition is not true.
do{
statement or block of statements
} while(boolean expression);
e.g.
int i = 1;
do{
Console.WriteLine(“Printing Line {0}\n”,i);
i++;
} while(i<=5);
MSc Programming - Dr R. Kharel 45
Arrays
• Collection of values of a similar data type.
• Each array in C# is an object and is inherited from the System.Array class.
• Arrays are declared as:
<data type> [] <identifier> = new <data type> [size of array]
e.g.
int [] integers = new int[10];
int sizeOfArray = 10; int [] integers = new int[sizeOfArray];
int [] integers = {1,3,4,5,6,7}; //creates size 6 array
Note: Size of array is fixed and must be defined before using it.
MSc Programming - Dr R. Kharel 46
Arrays (II)
Accessing values in an array
int [] marks = {54,67,43,69,81}; //declares size 5 array
with respective values
int secondMark = marks[1]; //puts 67 in secondMark
Note: array index starts at 0
for (int i=0;i<marks.Length;++i){
Console.WriteLine(“Marks of student {0}:{1}”,i+1,marks[i]);
}
MSc Programming - Dr R. Kharel 47
foreach iteration
foreach(<type of elements in collection> <identifier> in
<array or collection>)
{
statements or block of statements
}
e.g.
foreach(int i in integers)
{
Console.WriteLine(“Marks of student {0}”,i);
}
MSc Programming - Dr R. Kharel 48
Methods
• These are code blocks that does specific task.
• For e.g. to calculate sum of two numbers you can define
method Sum() that takes two arguments a and b, add
them together and returns the results, i.e.
int Sum(int a, int b)
{
int result;
result = a + b;
return result;
}
MSc Programming - Dr R. Kharel 49
Next Lesson
• Object Oriented Programming approach using C#
• Discuss about class, objects, etc
MSc Programming - Dr R. Kharel 50
top related