C# Learner's Log #1 - 30.01.21

·

4 min read

Implicit typing involves using the var keyword where the compiler can intelligently figure out what data type an expression is.

        static void Main(string[] args)
        {
            double[] numbers; 
            numbers[0] = 12.7 // Error: 'Use of unassigned local variable of numbers
            numbers[1] = 
            numbers[2]
            var x = 34.5;
            var y = 10.3;     
        }

Currently, the numbers array does not exist. All we have is a variable that is pointing to an array that doesn't exist. We need to first assign values to variables.

Here's how to initialize the array:

We use the new keyword to instantiate the array.

double[] numbers = new double[3]

The number inside the square brackets represents the size of the array.

We can once again use implicit typing to simplify these lines of code since the compiler will implicity gather that this is an array of double elements. Therefore, we can write:

var numbers = new double[3]

For array initialisation, if you know exactly what values will be going into the array, you do not have to write statements on separate lines like this:

var numbers = new double[3];
numbers[0] = 12.7;
numbers[1] = 10.3;
numbers[2] = 6.11;

In C#, we can use what's known as the array initialisation syntax:

var numbers = new double[3] {12.7, 10.3, 6.11}

We can remove the number inside the square brackets and rely on the C# compiler to do the right thing, so instead of declaring an explicit size, since we now have an initialisation expression, we can leave the number out of the square brackets and the compiler will figure out what size you need to hold these values:

var numbers = new double[] {12.7, 10.3, 6.11}

We also don't need to tell the C# compiler that this will be an array of doubles, as it will be able to figure that out.

var numbers = new [] {12.7, 10.3, 6.11}

Let's write a foreach statement to loop through the array:

            var numbers = new [] {12.7, 10.4, 11.5};

            var result = 0.0;

            foreach(var number in numbers)
            {
                result += number;
            }

            Console.WriteLine(result);

When we work with arrays in C# we need to give them a specific size. So when we don't know the specific size of the array.

I have a variable named grades and each variable will be typed as a List of double.

Implicity declaring a List object:

image.png

LOOK UP C# FORMATTING SPECIFIERS