1 / 59

Introduction to Programming in C# John Galletly

Introduction to Programming in C# John Galletly. The Basics. What is "C#"?. “Flagship” language for Microsoft’s .NET Framework C# features: New cutting edge language Extremely powerful Easy to learn Easy to read and understand Object-oriented. Why C#?.

ditch
Download Presentation

Introduction to Programming in C# John Galletly

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Programming in C# John Galletly

  2. The Basics

  3. What is "C#"? “Flagship” language for Microsoft’s .NET Framework C# features: New cutting edge language Extremely powerful Easy to learn Easy to read and understand Object-oriented

  4. Why C#? • Can be used to develop a number of different types of applications • Software components • Mobile applications • Dynamic Web pages • Database access components • Windows desktop applications • Web services • Console-based applications

  5. Syntax – Writing C# Programs In a lot of areas, C# and Java are syntactically similar to each other, and also similar to C and C++. However, there are differences between C# and the other languages - Some of which are infuriating!

  6. Object-Oriented Programming • Construct complex systems that model real-world entities • Facilitates designing components • Assumption is that the world contains a number of entities that can be identified and described by software objects

  7. Microsoft’s .NET Framework • Not an operating system • An environment in which programs run • Resides at a layer between operating system and other applications • Offers multilanguage independence • One application can be written in more than one language • Includes over 2,500 reusable types (classes) • Enables creation of dynamic Web pages and Web services • Scalable component development

  8. What is .NET Framework? Environment for execution of Micrsoft .NET programs Powerful library of classes Programming model Common execution engine for many programming languages C# Visual Basic .NET ... and many others

  9. Inside .NET Framework

  10. Console Applications • Normally send requests to the operating system • Display text on the command console • Easiest to create • Simplest approach to learning software development • Minimal overhead for input and output of data

  11. Windows Applications • Applications designed for the desktop • Designed for a single platform • Use classes from System.Windows.Form • Applications can include menus, pictures, drop-down controls, buttons, text boxes, and labels • Use drag-and-drop feature of Visual Studio

  12. Web Applications • C# was designed with the Internet applications in mind • Can quickly build applications that run on the Web with C# • Using Web Forms: part of ASP.NET

  13. Visual Studio .NET (VS.NET) • A single IDE for all forms of .NET development • From class libraries to form-based apps to web services • And using C#, VB, C++, J#, etc.

  14. C# Introduction

  15. Class The class is the basic unit in C#. Every executable C# statement must be placed inside a class. Every C# program must have at least one one class, and one method called Main() in that class. A class is just a template or blueprint for defining objects.

  16. Basic syntax for class declaration Class comprises a class header and class body. class class_name { class body } Note: No semicolon (;) to terminate class block. But statements must be terminated with a semicolon ; Class body comprises class members – constructor, data fields and methods.

  17. The Method Main • Every C# application musthave a method named Main() defined in one of its classes. – It does not matter which class contains the method - you can have as many classes as you want in a given application - as long as one class has a method named Main. • The Main method must be defined as static. – The statickeyword tells the compiler that the Main method is a global method, and that the class does not need to be instantiated for the method to be called. - May also include the access modifier public

  18. Syntax for simple C# program // Program start class class class_name { // Main begins program execution public static void Main(string[] args) { statements } } Programmer-defined class name May be replaced by Main() A C# program starts with a class which encapsulates the method Main() Note: Main() – not main()

  19. Simple C# program // Program start class class HelloWorld { // Main begins program execution static void Main() { System.Console.WriteLine("Hello World"); } }

  20. Define a class called "HelloWorld" Include the standard namespace "System" Define the Main() method – the program entry point using System; class HelloWorld { static void Main() { Console.WriteLine("Hello World!"); } } Write text message on the screen by calling the method "WriteLine" of the class "Console"

  21. To access classes and methods without using their fully qualified name, use the using directive. Example using System; Instead of writing System.Console.WriteLine() May write using System; Console.WriteLine()

  22. Using namespaces // Namespace Declaration using System; // Program start class public class HelloWorld { // Main begins program execution static void Main() { // This is a single line comment /* This is a multiple line comment */ Console.WriteLine("Hello World!"); } }

  23. Operators, Types, and Variables Variables C# is a strongly “typed" language (aka “type-safe”.) - All operations on variables are performed with consideration of what the variable's “type" is. There are rules that define what operations are legal in order to maintain the integrity of the data you put in a variable.

  24. Types C# simple types consist of the Boolean type and three numeric types (integer, floating-point and decimal) and the String type. The pre-defined reference types are object and string, where object is the ultimate base class of all other types. Boolean type- Boolean types are declared using the keyword, bool. They have two values: true or false. These are keywords. E.g. bool gaga = true;

  25. Data Types • Common C# data types • The “root” type object • Logical bool • Signed Integer short, int, long • Unsigned Integer ushort, uint, ulong • Floating-point float, double, • Text char, string

  26. The Object Type • The object type: • Is declared by the object keyword • Is the base type of all other types • Can hold values of any type object dataContainer = 5; Console.Write("The value of dataContainer is: "); Console.WriteLine(dataContainer); dataContainer = "Five"; // same variable Console.Write("The value of dataContainer is: "); Console.WriteLine(dataContainer);

  27. All typesare compatible with object - A variable of any type can be assigned to variables of type object - All operations of type object are applicable to variables of any type.

  28. Types, Classes, and Objects • Data Type • C# has more than one type of number • int type is a whole number • Floating-point types can have a fractional portion • Types are actually implemented through classes • One-to-one correspondence between a class and a type • Simple data type such as int is implemented as a class

  29. Integer type In C#, an integer is a category of types. They are whole numbers, either signed or unsigned.

  30. Floating-Point and Decimal Types A C# floating-point type is either a float or double. They are used any time you need to represent a real number. The decimal type should be used when representing financial or money values.

  31. Caution with Floating-Point Comparisons • Sometimes problems can happen when comparing floating-point number values due to rounding errors. • Comparing floating-point numbers should not be made directly with the == (equality) operator • Example: This strange syntax will be explained shortly! double a = 1.0; double b = 0.33; double sum = 1.33; bool equal = (a+b == sum); // Not necessarily true! Console.WriteLine("a+b={0} sum={1} equal={2}", a+b, sum, equal);

  32. intstudentCount; // number of students in the class intageOfStudent = 20; // age - originally initialized to 20 intnumberOfExams; // number of exams intcoursesEnrolled; // number of courses enrolled doubleextraPerson = 3.50; // extraPerson originally set // to 3.50 doubleaverageScore = 70.0; // averageScore originally set // to 70.0 doublepriceOfTicket; // cost of a movie ticket doublegradePointAverage; // grade point average floattotalAmount = 23.57f; // note the f must be placed after // the value for float types

  33. Example • An example of using types in C# • Declare before you use (compiler enforced) • Initialize before you use (compiler enforced) public class App { public static void Main() { int width, height; width = 2; height = 4; int area = width * height; int x; int y = x * 2; ... } } declarations declaration + initializer error, x not set

  34. Boolean Variables • Based on true/false • Boolean type in C# → bool • Does not accept integer values such as 0, 1, or -1 bool undergraduateStudent; bool moreData = true;

  35. Boolean Values – Example • Example of boolean variables taking values of true or false: int a = 1; int b = 2; bool greaterAB = (a > b); Console.WriteLine(greaterAB); // False bool equalA1 = (a == 1); Console.WriteLine(equalA1); // True

  36. Data Type char • The character data type: • - Represents symbolic information – single quotes ‘… ‘ • - Is declared by the char keyword • - Gives each symbol a corresponding integer code • - Has a '\0' default value

  37. The String Data Type • The string data type: • Represents a sequence of characters • Is declared by the string keyword • Has a default value null (no value) • Really a pre-defined class • Strings are enclosed in double quotes: “…” • Strings can be concatenated • Using the + operator string s = “SWU – “ + “ICoSCIS Project";

  38. Saying Hello – Example • Concatenating the two names of a person to obtain his full name using + string firstName = "Ivan"; string lastName = "Ivanov"; Console.WriteLine("Hello, {0}!\n", firstName); string fullName = firstName + " " + lastName; Console.WriteLine("Your full name is {0}.", fullName);

  39. Class System.String • Can be used as standard type string • string s = “ICoSCIS"; • Note • • Can be concatenated with +: “SWU " + s; • • Can be indexed: s[i] • • String length: s.Length • • String values can be compared with == and !=: • if (s == “SWU") ... • • Class String defines many useful operations: • CompareTo, IndexOf, StartsWith, Substring, ...

  40. Data Constants • Add the keyword const to a declaration • Value cannot be changed • Standard naming convention – identifier usually uppercase characters • Syntax • const type identifier = expression; • Example • const double TAX_RATE = 0.0675; • const int SPEED = 70; • const char HIGHEST_GRADE = ‘A’;

  41. Mixed Expressions – Different Types • Explicit type coercion • Cast • Syntax: (type) expression • examAverage = (exam1 + exam2 + exam3) / (double) count; • int value1 = 0, • anotherNumber = 75; • double value2 = 100.99, • anotherDouble = 100; • value1 = (int) value2; // value1 = 100 • value2 = (double) anotherNumber; // value2 = 75.0

  42. Identifiers • Identifiers may consist of • Letters • Digits [0-9] • Underscore "_" • Identifiers • Can begin only with a letter or an underscore • Cannot be a C# keyword

  43. Identifiers – Examples • Examples of correct identifiers: • Examples of incorrect identifiers: int New = 2; // Here N is capital int _2Pac; // This identifier begins with _ string greeting = "Hello"; int n = 100; // Undescriptive int numberOfClients = 100; // Descriptive // Overdescriptive identifier: int numberOfPrivateClientOfTheFirm = 100; int new; // new is a keyword int 2Pac; // Cannot begin with a digit

  44. Initializing Variables • Initializing • Must be done before the variable is used! • Several ways of initializing: • By using the new keyword • By using a literal expression • By assigning an already initialized variable

  45. Initialization – Examples • Example of some initializations: // The following would assign the default // value of the int type to num: int num = new int(); // num = 0 // This is how we use a literal expression: float heightInMeters = 1.74f; // Here we use an already initialized variable: string greeting = "Hello World!"; string message = greeting;

  46. int numberOfMinutes, count, minIntValue; char firstInitial, yearInSchool, punctuation; numberOfMinutes = 45; count = 0; minIntValue = -2147483648; firstInitial = ‘B’; yearInSchool = ‘1’; enterKey = ‘\n’; // newline escape character

  47. Statements in C# • C# supports the standard assortment … • assignment • function • conditional • if, if-else, switch • iteration • for, while, do-while • control flow • return, break, continue

  48. Console Input/Output Methods • Writing to screen • Methods are members of Console class • Console.WriteLine() • - Writes to screen followed by newline • Console.Write( ) • - Writes to screen without newline

More Related