920 likes | 1.11k 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
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 named B • It was originally designed for ease of use by experts who had a deep knowledge of the software and hardware they were using, 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 features that facilitated writing small, efficientcode also made it possible for programmers to make seriouslogicerrors without much support for catching them • For example, arrays are contiguous blocks of memory but have no built-in bounds checking in C or C++ • Allows one to refer to array[-6] or to array[length + 10] where length is the size of the array • Allows arrays of different sizes to be passed to a function as parameters in separate calls without the function having to know how big the array is • 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 purposefully) Introduction to the Syntax and Structure of C# Programs
More Background • The original C language 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 (true, false) • Exception handling • Templates and/or Generics • Inheritance • Interfaces • Memory management and garbage collection • Features as fundamental as conversion between compatibledatatypes (say double to int or int to double) 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 languages have been derived from the original C language. • C++ added object-oriented features to C, but kept all of C as well • Java (created by Sun, now owned by Oracle) • 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
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 comparisonoperators 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
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 Java (C++ is not) 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 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 as well as output 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 Note use of placeholders in formatting 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
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 methods 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 of appropriate types • 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 often combined as Properties Introduction to the Syntax and Structure of C# Programs
Properties: Getters/Setters 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 public 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 maintainabilitywithoutchangingitsfunctionalityin 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
Refactorings • There are many possible refactorings. • 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 • 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 • 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
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 • 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 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 Resembles Java but with additional types Introduction to the Syntax and Structure of C# Programs
.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 C# type names .NET type names Approx. 30 digits Introduction to the Syntax and Structure of C# Programs
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! Introduction to the Syntax and Structure of C# Programs
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 • 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 Introduction to the Syntax and Structure of C# Programs
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 • The string class is C#’s implementation of .NET’s System.String class • Similar to String class in Java • Unicode – characters take multiple bytes (see next slide) • 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
Small Part of Unicode Chart • 1 is FF11, 2 is FF12, … • A is FF21, B is FF22, … • Y is FF39, Z is FF3A • a is FF41, b is FF42, … • There are “other characters” before 0, after 9, before A, after Z, before a, and after z • Therearecharactersbetween Z and a • FF11 is 1111111100010001 Regular Expressions
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 Introduction to the Syntax and Structure of C# Programs
SEARCH for a SUBSTRING Introduction to the Syntax and Structure of C# Programs
Some String Methods Search for one of a set of characters Introduction to the Syntax and Structure of C# Programs
More String Methods Introduction to the Syntax and Structure of C# Programs
Even More String Methods Introduction to the Syntax and Structure of C# Programs
Some String Examples Introduction to the Syntax and Structure of C# Programs