Skip to content

Latest commit

 

History

History
53 lines (39 loc) · 2.21 KB

introduction.md

File metadata and controls

53 lines (39 loc) · 2.21 KB

C# is a statically-typed language, which means that everything has a type at compile-time. Assigning a value to a name is referred to as defining a variable. A variable can be defined either by explicitly specifying its type, or by letting the C# compiler infer its type based on the assigned value (known as type inference). Therefore, the following two variable definitions are equivalent:

int explicitVar = 10; // Explicitly typed
var implicitVar = 10; // Implicitly typed

Updating a variable's value is done through the = operator. Once defined, a variable's type can never change.

var count = 1; // Assign initial value
count = 2;     // Update to new value

// Compiler error when assigning different type
// count = false;

C# is an object-oriented language and requires all functions to be defined in a class. The class keyword is used to define a class. Objects (or instances) are created by using the new keyword.

class Calculator
{
    // ...
}

var calculator = new Calculator();

A function within a class is referred to as a method. Each method can have zero or more parameters. All parameters must be explicitly typed, there is no type inference for parameters. Similarly, the return type must also be made explicit. Values are returned from methods using the return keyword. To allow a method to be called by code in other files, the public access modifier must be added.

class Calculator
{
    public int Add(int x, int y)
    {
        return x + y;
    }
}

Methods are invoked using dot (.) syntax on an instance, specifying the method name to call and passing arguments for each of the method's parameters. Arguments can optionally specify the corresponding parameter's name.

var calculator = new Calculator();
var sum_v1 = calculator.Add(1, 2);
var sum_v2 = calculator.Add(x: 1, y: 2);

Scope in C# is defined between the { and } characters.

C# supports two types of comments. Single line comments are preceded by // and multiline comments are inserted between /* and */.