1
2_learning_the_csharp_syntax
Jason Zhu edited this page 2021-02-23 13:57:37 +11:00
Module 2. Learning the C# Syntax
Working with Code Blocks and Statements
When debugging C# code, start from top of file to bottom. As some problems may result from previous error/warning
Adding Numbers and Creating Arrays
C# can use var
for implicit typed local variable. It's optional to use var
or specific data type. But C# is still strong type language.
C# error message: "Use of unassigned local variable 'number'" as C# does not allow array created w/o assignment. Can be fixed by variable creation using new
with specified array length.
double[] numbers = new double[10];
Looping through Arrays
Array initialization syntax e.g.:
var numbers = new double[3] {12.7, 10.3, 1.1};
can be further simplified, as C# compiler can deduct array variable type and length
var numbers = new[] {12.7, 10.3, 1.1};
To loop through each element in array, use foreach
foreach (var number in numbers)
{
result += number;
}
Using a List
- Problem of array as data structure: fixed size during initialization.
- Solution: Data structure List (extendable)
To create List object:
- need using List namespace. e.g.
using System.Collections.Generic;
- need specify Type Parameters. e.g.
List<double> grades;
to specify object type within the list. - Initialize the List is also needed
List<double> grades = new List<double>();
- (Optional) we can initialize the list during creation
List<double> grades = new List<double>() {12.7, 10.3, 6.11, 4.1};
Now we have a dynamic sized object to contain other variables
To use List:
- Add element:
grades.Add(56.1)
; - Index list:
grades[2]
;