A brief overview and introduction l.jpg
This presentation is the property of its rightful owner.
Sponsored Links
1 / 86

C# Syntax and Structure 1 1 Materials from text, professor, MSDN, and Joe Hummel, SIGCSE PowerPoint PPT Presentation


  • 68 Views
  • Uploaded on
  • Presentation posted in: General

A brief overview and introduction. C# Syntax and Structure 1 1 Materials from text, professor, MSDN, and Joe Hummel, SIGCSE . A Little Background on C#. C and its derivatives. What Languages Do You Know?. You have experience programming in one or more programming languages such as Java

Download Presentation

C# Syntax and Structure 1 1 Materials from text, professor, MSDN, and Joe Hummel, SIGCSE

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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


A brief overview and introduction l.jpg

A brief overview and introduction

C# Syntax and Structure11 Materials from text, professor, MSDN, and Joe Hummel, SIGCSE

Introduction to the Syntax and Structure of C# Programs


A little background on c l.jpg

A Little Background on C#

C and its derivatives

Introduction to the Syntax and Structure of C# Programs


What languages do you know l.jpg

What Languages Do You Know?

  • You have experience programming in one or more programming languages such as

    • Java

    • C++

    • Visual Basic

    • Assembly Language

    • more …

Introduction to the Syntax and Structure of C# Programs


A little background l.jpg

A Little Background

  • The C language was developed in the early 1970’s for use in creating the Unix operating system

    • Parent language was B

  • It was originally designed for ease of use by experts who knew what they were doing, not for use by the computing world in general

    • Designed to write small, efficient code that used “coding tricks” to improve performance, code size

    • Not designed for security, privacy, robustness, etc.

    • Easytohack because of the designed-in ease of doing “coding tricks”

Introduction to the Syntax and Structure of C# Programs


Background continued l.jpg

Background, continued

  • The same features that made it possible to write small, efficientcode made it possible for programmers to make seriouslogicerrors without having much of the necessary support to catch them

    • For example, arrays are contiguous blocks of memory but have no built-in bounds checking in C or C++

      • This allows arrays of different sizes to be passed to a function as parameters in different calls without the function having to know how many entries each can hold

      • But it also allows users to trash memory by inadvertently (or intentionally) using subscripts that are out of bounds

      • In less sophisticated operating systems, it even allows the user’s program to trash the operating system inadvertently (or purposely)

Introduction to the Syntax and Structure of C# Programs


More background l.jpg

More Background

  • C did not support many of the features that are so important today. For example, the original did not support

    • Object-oriented concepts such as classes, objects, inheritance, etc.

    • Boolean data types

    • Exception handling

    • Templates and/or Generics

    • Inheritance

    • Interfaces

  • Features as fundamental as conversion between compatibledatatypes were often added by people who did not use commonnamingconventions or commondesignprinciples – making it impossible for people who understood one concept to make intelligent guesses about similar concepts

Introduction to the Syntax and Structure of C# Programs


Background continued7 l.jpg

Background, continued

  • C became a popular, widely used language

  • Many compilers were created, all with some differences, meaning code was not always portable between machines

  • Standardscommittee formed

    • Attempt was made to be sure all compilers supported “standard” features in a consistent way

    • Backward compatibility with existing software was also important

    • Periodically, standards have been expanded and updated

Introduction to the Syntax and Structure of C# Programs


Background continued8 l.jpg

Background, continued

  • Many other languages have been derived from the original C language.

    • C++ added object-oriented features to C, but kept all of C as well

    • Java

      • Removed some dangerous features of C (such as arrays without bounds-checking)

      • Added some features such as object-orientation, garbagecollection, better memorymanagement, and so forth

    • C# - Microsoft’s “better Java” – but also an international open standard

    • Many others

  • If you know the syntax of one C derivative, you are probably able to understand the syntax of another reasonably quickly

Introduction to the Syntax and Structure of C# Programs


Background continued9 l.jpg

Background, continued

  • The derivative languages “look like” C in that they use similar syntax, many similar semantics, and similar keywords

    • All use { }, semicolons, // for comments, and so forth

    • All use keywords such as int, double, if, else, return, while, for, try, catch, throw, private, public, class, and so forth to mean similar things

    • All use operators such as =, ==,+, -, *, /, %, ( ), [ ], >, <, <=, &&, ||, ++, --, and so forth in similar ways to mean similar things

Introduction to the Syntax and Structure of C# Programs


So if you know java or c l.jpg

So, if you know Java or C++…

  • You can read and understand much of C#

    • Semicolons end C# statements

    • Case-sensitive so COUNT, Count, and count are three different identifiers

    • { } are used to designate a block of code in the same way as in Java, C++

    • Primitive data types (int, float, double, char, bool, etc.) have the same interpretations as in C++ and Java

    • // marks the beginning of a single line comment

    • Many keywords such as if, else, while, for, public, private, return are used in each language with similar meanings

    • Arithmetic, logical, and comparison operators are essentially the same: +, -, *, /, =, +=, &&, ||, >, < , ==, !, etc.

    • All have a main (or Main) method where execution begins for a console application

Introduction to the Syntax and Structure of C# Programs


Popularity of c is growing l.jpg

Popularity of C# is growing

Based on a poll of about 400 programmers at an April 2009 developers conference

Introduction to the Syntax and Structure of C# Programs


C a first example l.jpg

C# - a first example

The obligatory Hello World program

Introduction to the Syntax and Structure of C# Programs


Hello world l.jpg

Hello World

Somewhat fewer syntactic and structural requirements than Java …

… For example, thename of the class need not be the same as the name of the file that contains it

C# is fully object-oriented like Javabut not like C++

Main is Pascalcase and may or may not have arguments

Use this syntax to write a line of text on the console window instead of Java’s System.out.println or C++’s cout

Introduction to the Syntax and Structure of C# Programs


Namespaces and using l.jpg

Namespaces and Using

  • Related classes are grouped into namespaces

    • Like Java packages and like C++ namespaces

  • Namespaces may be designated for use in C# programs with a using command

    • Similar to imports in Java and #include in C++

If a “using” is specified for the namespace, classes from the namespace do not have to be qualified with the namespacename unless there is an ambiguity

Introduction to the Syntax and Structure of C# Programs


Example with keyboard input l.jpg

Example with Keyboard Input

ReadLine inputs a string representing the entire line of input

The same Console class can be used for input

Introduction to the Syntax and Structure of C# Programs


Identifier naming conventions in c l.jpg

Identifier Naming Conventions in C#

Introduction to the Syntax and Structure of C# Programs


C example with separate class l.jpg

C# - Example with separate class

Driver and another class

Introduction to the Syntax and Structure of C# Programs


Example with another class l.jpg

Example with Another Class

Ordinary C# Class

Attributes

Parameterized Constructor

Overridden ToString method

Introduction to the Syntax and Structure of C# Programs


Driver program l.jpg

Driver Program

Console output for the program

ToString method of MilesPerGallon invoked implicitly hereto convert object into a string that can be displayed

Introduction to the Syntax and Structure of C# Programs


Visual studio l.jpg

Visual Studio

Creating, editing, running, and debugging C# code

Introduction to the Syntax and Structure of C# Programs


Using visual studio with c l.jpg

Using Visual Studio with C#

  • Visual Studio with C#uses the same IDE (InteractiveDevelopmentEnvironment) as

    • Visual C++

    • Visual Basic

    • Visual F# and IronPython (added in VS 2010)

  • VS has many features in common with the EclipseIDE for Java

  • The IDE for VS provides a codeeditor, projectmanager, interactivedebugger, UML diagramming tool, and many other features, some of which we shall see

Introduction to the Syntax and Structure of C# Programs


Visual studio solution l.jpg

Visual Studio Solution

  • Visual studio organizes C# programs into

    • Solutions (.sln)

    • Made up of one or more projects (.csproj)

    • Each project has one or more C# source code files (.cs) and possibly other files as well

  • The solution explorer tab in Visual Studio shows the solution structure:

Project

Source code files

Introduction to the Syntax and Structure of C# Programs


Creating a console application in vs2010 l.jpg

Creating a Console Application in VS2010

  • On the File menu, choose New/Project

Introduction to the Syntax and Structure of C# Programs


Creating a console app cont l.jpg

Creating a Console App, cont.

Can target .NET version

Console Application

Project Name

Location of Solution Folder

Solutionname same as project by default

Introduction to the Syntax and Structure of C# Programs


Creating a console app cont25 l.jpg

Creating a Console App, cont.

Code editor window

File name may also be changed here

Namespace and classnames default as shown – but the names may be changed

Introduction to the Syntax and Structure of C# Programs


Creating a console app cont26 l.jpg

Creating a Console App, cont.

Use these menu choices to run.

The F-key combinations or buttons can also be used.

Introduction to the Syntax and Structure of C# Programs


Add a new class to the project l.jpg

Add a New Class to the Project

Use this to add a new class or other projectitem

Introduction to the Syntax and Structure of C# Programs


Adding a new class l.jpg

Adding a New Class

Name the class file

Introduction to the Syntax and Structure of C# Programs


Customize vs l.jpg

Customize VS

Suit your preferences for fonts, colors, spacing, and more

Introduction to the Syntax and Structure of C# Programs


Setting options l.jpg

Setting Options

  • Use Tools/Options to get to Options Dialog

May also set options for error messages, output, debugger, etc.

Select Font

Select Syntax Coloring Choices

Preview your selection

Introduction to the Syntax and Structure of C# Programs


More options l.jpg

More Options

Set Default Location for new Projects – like a Java workspace

Introduction to the Syntax and Structure of C# Programs


More options32 l.jpg

More Options

Show line numbers in code editor

Introduction to the Syntax and Structure of C# Programs


More options33 l.jpg

More Options

Set size of tabs for indenting things – 4 is common

Introduction to the Syntax and Structure of C# Programs


More options34 l.jpg

More Options

Select all of the Advanced Options

Introduction to the Syntax and Structure of C# Programs


More options35 l.jpg

More Options

Set your preferences for automatic indenting – example shows the effect for the selected item

Introduction to the Syntax and Structure of C# Programs


More options36 l.jpg

More Options

Preferences for vertical spacing – makes program more readable. Example shows results.

Introduction to the Syntax and Structure of C# Programs


More options37 l.jpg

More Options

Set preferences for horizontal spacing to improve readability. See results in example to left.

Introduction to the Syntax and Structure of C# Programs


More options38 l.jpg

More Options

Intellisense Options

Introduction to the Syntax and Structure of C# Programs


Save restore options l.jpg

Save/Restore Options

This can be used to set options on one machine and use them on other machines as well.

Introduction to the Syntax and Structure of C# Programs


Intellisense l.jpg

Intellisense

On-the-fly coding hints and more

Introduction to the Syntax and Structure of C# Programs


Intellisense41 l.jpg

Intellisense

  • After a period is typed following the name of a namespace, class, object, etc., a list of what may come next appears

    • Use tab to accept

    • Escape to cancel

More on Intellisense later …

Introduction to the Syntax and Structure of C# Programs


C properties l.jpg

C# Properties

Looks and acts like a variable but built like two functions

Introduction to the Syntax and Structure of C# Programs


Properties in net l.jpg

Properties in .NET

  • In Java, classes often have

    • Private attributes (fields) that are defined as variables

    • Public getter and/or setter methods that allow a user of the class to assign a value to an attribute or retrieve the current value of the attribute

  • In .NET, the attributes (fields) and their getter/setter methods are combined as Properties

Introduction to the Syntax and Structure of C# Programs


Properties in net44 l.jpg

Properties in .NET

Private field

Property Name

Public getter/setter combo

The term “value” is a keyword used as a parameter if none is given explicitly

Introduction to the Syntax and Structure of C# Programs


Properties in net45 l.jpg

Properties in .NET

  • Properties are used in a much simpler fashion in .NET than getters/setters are in Java

    • The nameof the property is used as if it were a variable

      • The getter is invoked if semantics call for retrieving the propertyvalue

      • The setter is invoked if semantics call for assigning a newpropertyvalue

Setter invoked

Getter invoked

Introduction to the Syntax and Structure of C# Programs


Properties in net even better with vs l.jpg

Properties in .NET – even better with VS

  • It is extremely easy in VS to create a C# property

    • Simply type the term prop and press tab-key, tab-key

    • This generates:

    • Replace int with correct data type

    • Replace MyProperty with the name your property is to have

    • No other code is required

      • No need to declare/define the private attribute

      • No need to fill in code for the getter and setterif the typical standard code will do

Introduction to the Syntax and Structure of C# Programs


Properties in net47 l.jpg

Properties in .NET

  • In .NET, it is considered to be goodpracticeto replace essentially allprivateattributes (fields) by publicproperties, if getters and/or setters are desired

    • The underlying privateattribute (field) is preserved

    • The publicgetters and setters allow controlled access to the privateattribute

    • A property may have a public getter with a private setter to permit the outside world to retrieve but notchange the value

    • The get or set may be omitted if the property is a write-only or a read-only property

  • Is there an easy way to convert an existingprivateattribute into a publicproperty?

    • Yes!!

    • Use refactoring

Introduction to the Syntax and Structure of C# Programs


Refactoring l.jpg

Refactoring

Improving the readability and the structure of code without changing how the code works or what it does

Introduction to the Syntax and Structure of C# Programs


Code refactoring in visual studio l.jpg

Code Refactoring in Visual Studio

  • Sometimes one has code that “does the job”, but it is poorlystructured, overly long or complex, difficult to read and understand, difficult to maintain, and needsimprovement

  • Refactoring is the process of modifying the structure of existing code to improveitsreadability and maintainabilitywithoutchangingitsfunctionality in any way

    • Makes the code look better and be more readable without breaking what the code does

    • Visual Studio and CodeRush XPress automate much of the process of refactoring

Introduction to the Syntax and Structure of C# Programs


Code refactoring l.jpg

Code Refactoring

  • One example of refactoring is the conversion of an existingprivateattribute to a publicproperty automatically by VS

Could also rename

Right-click on item to refactor

Expand theRefactor list and chooseEncapsulate Field

Introduction to the Syntax and Structure of C# Programs


Property generation l.jpg

Property Generation

  • Pressing the Enter key generates code that is similar to the following

Introduction to the Syntax and Structure of C# Programs


Other refactorings l.jpg

Other Refactorings

  • There are many possible refactorings. Here are some others

    • Rename a method, variable, class, property, etc.

    • Addparameter or reorderparameters

    • Create an overload of a method

    • If a change is made in one place, all references to that item in the entire project are changed to match (even if they are in other files of the project)

Introduction to the Syntax and Structure of C# Programs


Extract method refactoring l.jpg

Extract Method Refactoring

  • Suppose a method has become too complex or too lengthy

    • One can simplify it by turning a logical section of it into a separate method

Introduction to the Syntax and Structure of C# Programs


Extracting a new method from existing code l.jpg

Extracting a New Method From Existing Code

  • First select the code to be extracted

Right click the selected text and choose Refactor / Extract Method

Introduction to the Syntax and Structure of C# Programs


Extracting method l.jpg

Shows proposed call to new method that will replace the extracted code

Extracting Method

It figures out what parameters are needed and from where they come

Click glyph

Gives information

Introduction to the Syntax and Structure of C# Programs


Extracting a method l.jpg

Extracting a Method

  • Allows us to set the location of the new method in the existing code and accept or reject the proposedrefactoringoperation

Introduction to the Syntax and Structure of C# Programs


Extracting a method57 l.jpg

Extracting a Method

Call to new method replaces the extractedcode

Can changename if desired

New method inserted

Introduction to the Syntax and Structure of C# Programs


Net data types l.jpg

.NET Data Types

Resembles Java but with additional types

Introduction to the Syntax and Structure of C# Programs


Net common type system l.jpg

.NET Common Type System

System.Object is a base class for everything

Introduction to the Syntax and Structure of C# Programs


Types in c mapped to net types l.jpg

Types in C# mapped to .NET Types

C# type names

.NET type names

Approx. 30 digits

Introduction to the Syntax and Structure of C# Programs


Nullable types in c l.jpg

Nullable Types in C#

  • The name of an instance (object) of a class may not refer to anything at a given time just as in Java.

    • Student John = null;

    • Employee Jill = null;

  • There is an analog for value types such as int, double, and decimal in C#.

    • Important to be able to have no value for a value type because databases allow numericvalues to be “empty”.

    • What if one enters data via a form and leaves blank the box for age? This may be OK if age is optional for the application, but how do we show that in a program?

    • int age = null ; // syntax error for value types!

  • The name of an instance (object) of a class may not refer to anything at a given time just as in Java.

    • Student John = null;

    • Employee Jill = null;

  • There is an analog for value types such as int, double, and decimal in C#.

    • Important to be able to have no value for a value type because databases allow numericvalues to be “empty”.

    • What if one enters data via a form and leaves blank the box for age? This may be OK if age is optional for the application, but how do we show that in a program?

    • int age = null ; // syntax error for value types!

Introduction to the Syntax and Structure of C# Programs


Nullable types cont l.jpg

Nullable Types, cont.

  • Nullable types are C#’s solution to valuetypes with no values

  • Uses ? syntax like this:

    • valuetype? valuename = null;

    • Examples

      • int? age = null;

      • double? GPA = null;

    • Of course, variables defined as nullable types may also have values of their underlying type

      • age = 21;

      • GPA = 4.00;

Introduction to the Syntax and Structure of C# Programs


More on nullable types l.jpg

More on Nullable Types

  • All nullable types have two public properties

    • HasValue is a boolean property that indicates whether a nullable variable has a non-null value or not

    • Value returns the current value of a variable of nullabletype, but throwsanexception if HasValue is false

    • See example on next slide …

Introduction to the Syntax and Structure of C# Programs


Example l.jpg

Example

Introduction to the Syntax and Structure of C# Programs


Null coalescing operator l.jpg

Null Coalescing Operator

  • The null coalescing operator (??) evaluates a nullablevariable, and it returns either the variable’svalue if it has one or it returns a specifiedvalue if the variable is null

  • The following example illustrates this where bal is of type decimal?

    decimal balance = bal ?? 0.0M;

  • The above assigns the value of bal to balance if bal is notnull. Otherwise, it assigns 0 to balance.

The constant 0.00 is of type double. Adding a suffix of “M” designates the constant as type decimal

Introduction to the Syntax and Structure of C# Programs


String class l.jpg

String Class

  • The string class is C#’s implementation of .NET’s System.String class

    • Similar to String class in Java

    • Unicode

    • Supports == and != operators

    • Length property is set to the number of characters in the value currently

    • String.Empty is an empty string

Introduction to the Syntax and Structure of C# Programs


Visual studio help l.jpg

Visual Studio Help

  • Many methods in the class; use VS Help to find String class’s methods for more detail

Introduction to the Syntax and Structure of C# Programs


Some string methods l.jpg

Some String Methods

Introduction to the Syntax and Structure of C# Programs


Some string methods69 l.jpg

Some String Methods

Introduction to the Syntax and Structure of C# Programs


Some string methods70 l.jpg

Some String Methods

Introduction to the Syntax and Structure of C# Programs


More string methods l.jpg

More String Methods

Introduction to the Syntax and Structure of C# Programs


Even more string methods l.jpg

Even More String Methods

Introduction to the Syntax and Structure of C# Programs


Some string examples l.jpg

Some String Examples

Introduction to the Syntax and Structure of C# Programs


Example continued l.jpg

Example, continued

Introduction to the Syntax and Structure of C# Programs


Example continued75 l.jpg

Example, continued

Introduction to the Syntax and Structure of C# Programs


Output of example l.jpg

Output of Example

Introduction to the Syntax and Structure of C# Programs


Overloads l.jpg

Overloads

  • Many of the String methods have one or more overloads

  • Some common methods (Equals, IndexOf, EndsWith, StartsWith, . . .) have at least one overload that allows one to specify culture-specific information

  • For example:

    if (str1.Equals (str2, StringComparison.CurrentCultureIgnoreCase)) …

Introduction to the Syntax and Structure of C# Programs


Example78 l.jpg

Example

Introduction to the Syntax and Structure of C# Programs


Verbatim string literals l.jpg

Verbatim String Literals

  • Verbatimstringliterals start with @ and are enclosed in doublequotationmarks. For example:

    @"good morning"// a verbatim string literal

  • The advantage of verbatim strings is that escape sequences are not processed:

    @"c:\terry\files\nuts.txt"

    // rather than

    "c:\\terry\\files\\nuts.txt"

  • To include a double quotation mark in an @-quoted string, double it:

    @"""Ahoy!"" cried the captain."

    // "Ahoy!" cried the captain.

Introduction to the Syntax and Structure of C# Programs


System object l.jpg

System.Object

The ultimate base class in .NET

Introduction to the Syntax and Structure of C# Programs


The object base class l.jpg

The Object Base Class

Introduction to the Syntax and Structure of C# Programs


System object members l.jpg

System.Object Members

Introduction to the Syntax and Structure of C# Programs


Gethashcode l.jpg

GetHashCode

  • The purpose of System.Object’sGetHashCode method is to compute an integer value that somehow “represents” the object in question

    • The resulting integer is not necessarily unique, though a unique integer is “desirable” if that can be done

    • Can be thought of as an “encryption” of the object into an integer

  • This integer “hash code” has many purposes

Introduction to the Syntax and Structure of C# Programs


Overriding a method l.jpg

Overriding a Method

Must designate an override

This ToString method overrides the virtualToString method defined in Object

Introduction to the Syntax and Structure of C# Programs


Interfaces l.jpg

Interfaces

Use a colon instead of “implements”

Introduction to the Syntax and Structure of C# Programs


Inheritance l.jpg

Inheritance

Use “base” instead of “super”

Introduction to the Syntax and Structure of C# Programs


  • Login