Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chengyu Sun California State University, Los Angeles

Similar presentations


Presentation on theme: "Chengyu Sun California State University, Los Angeles"— Presentation transcript:

1 Chengyu Sun California State University, Los Angeles
CS4540 Special Topics in Web Development C# for Java Programmers: Language Basics Chengyu Sun California State University, Los Angeles

2 Create HelloWorld in Visual Studio
Project type Directory structure, Solution, and Project A solution may contain multiple projects .sln and .csproj files Solution View and Folder View

3 Using Git Source control
File  Add to Source Control Team Explorer Package project (for submitting homework and labs) Commit all changes, then git archive -o <filename>.zip HEAD

4 Naming Conventions Use PascalCase for anything public
Use camelCase for anything private or local See more in .NET Naming Guidelines and C# Identifier Names

5 IDE Support for Coding Conventions
Use Quick Action Fix Customize rules with a .editorconfig file Add an .editorconfig file to a solution or project

6 The Anatomy of a Simple C# Program
Program.cs File using System; namespace ConsoleApp1 { class Program static void Main(string[] args) Console.WriteLine("Hello World!"); } Import Namespace Class Main method

7 Comparison with Java Namespace is similar to package
using is similar to import There is no relation between namespace/class and directory/file Namespace/class name does not have to match directory/file name A file may contain multiple namespaces A namespace may contain multiple classes

8 Variations of Main() private or public void or int
With or without arguments Synchronous or asynchronous

9 Elements of an Imperative Programming Language
Comments Types Variables and Literals Operators and expressions Statements Functions and methods Classes and Objects Packages

10 Comments Single-line comment: // Block comment: /* */
Documentation comments: /// Similar to Javadoc comments /** */

11 About Data Types .NET data types (i.e. CTS data types) are defined in the System namespace Different .NET languages have additional type keywords that are mapped to the System types See Table 1-2 in Pro C# 7

12 Common C# Types More in Table 3-4 in Pro C# 7 C# Type System Type
Description bool System.Boolean True or false byte System.Byte Unsigned 8-bit integer short System.Int16 16-bit integer int System.Int32 32-bit integer long System.Int64 64-bit integer float System.Single 32-bit floating-point number double System.Double 64-bit floating-point number char System.Char 16-bit Unicode character string System.String A sequence of Unicode characters More in Table 3-4 in Pro C# 7

13 About C# Types C# type keywords are all in low case
Unlike in Java where Integer and int are different types, C# types are just aliases of the System types E.g. Int32.Parse("123") is the same as int.Parse("123")

14 Implicit Typing Using var
var a = 10; // int var b = 2.1; // double var c = true; // bool The type of the variable is determined by the compiler via type inference Once the type of a variable is inferred, it cannot be changed Implicit typing is particularly useful with dynamically created classes

15 Values Types and Reference Types
Java has primitive types and class types All C# types are class types, but some are value types and some are reference types (see Figure 3-3 in Pro C# 7) Value types behave like Java primitive types Reference types behave like Java class types

16 Value vs. Reference int a = 10; int b = a; b = 20; // a ?? class Foo {
int value = 10; } Foo a = new Foo(); Foo b = a; b.value = 20; // a.value ??

17 Pass By Value vs. Pass By Reference
int a = 10; class Foo { int value = 10; } Foo a = new Foo(); void change( int a ) { a = 20; } change(a); // a ?? void change( Foo a ) { a.value = 20; } change(a); // a.value ??

18 Nullable Types Usually a variable of a value type always has a value
We can make a value type nullable (i.e. allowing null value) by adding a ? suffix to the type, e.g. int? Nullable and non-nullable versions of a type are two different types Nullable types are particularly useful when dealing with relational databases

19 enum Type enum Color { Red, Green, Blue } enum Color { Red = 100,
Color color = Color.Red; Console.WriteLine( color == 0 ); Console.WriteLine( color.ToString() == "Red" );

20 Some C# Literals bool: true, false int: 123, 10_000, 0xFF, 0b0101
double: 1.23, 2.2e5 float: 1.23f char: 'A', '\u0041', '\t', '\n' string: "hello" Other: null, default

21 Interpolated String with $
string name = "John"; string greeting = $"Hello, {name}!"; Console.WriteLine(greeting); What's inside {} is an expression

22 The Verbatim Identifier @
string path1 = "C:\test\files"; string path2 = "C:\\test\\files"; string path3 string path4 = "C:/test/files"; Also useful for creating multiline strings

23 Constant with const double radius = 10; const double pi = 3.1415;
Console.WriteLine(pi * radius * radius);

24 Operators All Java operators, e.g. +, ++, =, ==, !=, &, &&, ?:, ., [], new, … Null-related operators: ?, ?? Name operator: nameof Get the simple string name of a variable, type, or member Quite useful in ASP.NET MVC where routes match controller/method names

25 String Equality … == and != can be used to check string equality/inequality This is a special case for reference types It performs a character-by-character, case-sensitive, culture-insensitive comparison Simple case-insensitive comparison can be done by converting both strings to upper (or lower) case

26 … String Equality More complex comparison can be done using the Equals() method in string. For example: s1.Equals(s2, StringComparison.CurrentCulture) s1.Equals(s2, StringComparison.CurrentCultureIgnoreCase) s1.Equals(s2, StringComparison.Ordinal) s1.Equals(s2, StringComparison.OrdinalIgnoreCase)

27 String Comparison >, >=, <, <= do NOT work for strings
String comparison can be done using the Compare() static method in string For example: Case-sensitive comparison using current culture string.Compare(s1, s2) string.Compare(s1, s2, true) Ignore case

28 Null Coalescing Operator ??
x != null ? x : y x ?? y Returns the value of x if it's not null; otherwise returns y

29 Null Conditional Operator ?
x == null ? null : x.y x?.y x == null ? null : x[y] x?[y] Used when accessing an object member or an array element Multiple null conditional operators can be chained together, e.g. a?.b?.c?.d

30 Null Conditional Example
class Person { Address address; } class Address { string street; string city; string state; string zip; // check if a person lives in LA if( person == null ) return false; else { if( person.address == null) return person.address.city == "LA"; } ??

31 Statements Selection statements: if, if-else, switch
Loop statements: for, foreach, while, do-while They are identical to the ones in Java except for foreach and some additional capabilities of switch

32 foreach Example Iterate through the elements in an array or a collection string[] colors = { "Red", "Green", "Blue" }; foreach (var color in colors) Console.WriteLine(color);

33 Array C# arrays are mostly like Java ones Declare Allocate
int[] numbers = new int[10]; for( var i=0 ; i < numbers.Length ; ++i ) numbers[i] = i+1; string[] strings = { "a", "b", "c" }; Populate All in one statement

34 Array Initialization Syntax
string[] a1 = { "a", "b", "c" }; string[] a2 = new string[] { "a", "b", "c" }; int l1 = { "a", "b", "c" }.Length; // Syntax Error! int l2 = new string[] { "a", "b", "c"}.Length; "Array Literal"

35 Multidimensional and Jagged Arrays
Multidimensional arrays int[,] a1 = { {1,2,3}, {4,5,6} }; // a 2x3 array Console.WriteLine( a1[0,1] ); Jagged arrays are arrays of arrays where each array may have different number of elements int[][] a2 = { new int[]{1,2,3}, new int[]{4,5} }; Console.WriteLine( a2[0][1] );

36 Basic IO Using the Console Class
Output: Write(), WriteLine() Input: Read() reads one character ReadLine() reads one line Example: reads the name, price, and quantity of a product Use double.Parse() and int.Parse() to convert a string to a number

37 Formatted Output Expressions Console.WriteLine(
$"There are {quantity} {product} at ${price}" ); Console.WriteLine("There are {0} {1} at ${2}", quantity, product, price); Placeholders with the indexes of the arguments

38 More Formatting Use standard format strings, e.g.
$"There are {quantity} {product} at {price:c}" "There are {0} {1} at {2:c}" Use custom format strings, e.g. $"There are {quantity} {product} at ${price:0.00}" "There are {0} {1} at ${2:0.00}" See Formatting Types in .NET

39 Readings Pro C# 7: Chapter 2 and 3


Download ppt "Chengyu Sun California State University, Los Angeles"

Similar presentations


Ads by Google