860 likes | 998 Views
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 C++
E N D
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# C and its derivatives Introduction to the Syntax and Structure of C# Programs
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 • 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 • 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 • 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, 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, 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, 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++… • 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 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 The obligatory Hello World program Introduction to the Syntax and Structure of C# Programs
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 • 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 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# Introduction to the Syntax and Structure of C# Programs
C# - Example with separate class Driver and another class Introduction to the Syntax and Structure of C# Programs
Example with Another Class Ordinary C# Class Attributes Parameterized Constructor Overridden ToString method Introduction to the Syntax and Structure of C# Programs
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 Creating, editing, running, and debugging C# code Introduction to the Syntax and Structure of C# Programs
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 • 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 • On the File menu, choose New/Project Introduction to the Syntax and Structure of C# Programs
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, 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, 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 Use this to add a new class or other projectitem Introduction to the Syntax and Structure of C# Programs
Adding a New Class Name the class file Introduction to the Syntax and Structure of C# Programs
Customize VS Suit your preferences for fonts, colors, spacing, and more Introduction to the Syntax and Structure of C# Programs
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 Set Default Location for new Projects – like a Java workspace Introduction to the Syntax and Structure of C# Programs
More Options Show line numbers in code editor Introduction to the Syntax and Structure of C# Programs
More Options Set size of tabs for indenting things – 4 is common Introduction to the Syntax and Structure of C# Programs
More Options Select all of the Advanced Options Introduction to the Syntax and Structure of C# Programs
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 Options Preferences for vertical spacing – makes program more readable. Example shows results. Introduction to the Syntax and Structure of C# Programs
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 Options Intellisense Options Introduction to the Syntax and Structure of C# Programs
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 On-the-fly coding hints and more Introduction to the Syntax and Structure of C# Programs
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 Looks and acts like a variable but built like two functions Introduction to the Syntax and Structure of C# Programs
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 .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 .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 • 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 .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 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 • 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 • 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