C# Syntax, Variables, Methods

Overview

C# is an object-oriented programming language or OOP for short. This lesson focuses on the syntax, variables, and methods of the language. In C# and other OOP languages, programs consist of various objects interacting with each other through methods (think of it as an action). These objects can pass and save data in containers called variables. The syntax of the C# language refers to the “grammar” we use to write the code that the computer compiles. In this lesson, we focus on three things of the C# language by creating our first program, “Hello World!”

Syntax

Like stated above the syntax of the C# language is the grammar we use to write the code. Unlike the grammar of the English language, it must be followed, or the program will not understand your code. Let’s look at some common beginner errors:

Case Sensitivity

Let’s look at an example:

x = 5;
X = 5;

Do you think “x” and “X” are the same variables? Most people would be able to use inductive reasoning to conclude that they are the same, but a compiler (the system that translates your code to a language that the computer reads), will view these as two separate variables because one is lower case and one is upper case. In truth, these are two distinct characters according to the computer.

Semi-colons

The semi-colon is a lot like the period in the English language, but if you miss a semi-colon, your program will most likely throw an exception (an error). When learning the syntax of the C# language, it can be hard to figure out when to use a semi-colon because some code blocks need them, and some do not. Look at the examples below to familiarize yourself with when to use a semi-colon with different elements of the C# language.

  • Namespaces – not required
  • namespace Example {
    	// silence
    }
  • Classes – not required
  • class Example {
    	// silence
    }
  • Method (Construction) – not required
  • void Example() {
    	// do something
    }
  • Method (Calling) – required
  • void Example();
  • Variables – required
  • int example = 5;

Whitespace

In truth, the computer ignores whitespace (spaces, tabs, and returns) when compiling your code. It is still essential to use appropriate whitespace when writing code because we want our code to be easy for us and others to read. Over the years, programmers have developed “best practices” that we should all follow to allow us to understand others and our code. Let’s look at some examples:

  • Lines – code is run in sequential order (one line at a time), this means we should write all our code in sequential order.
  • int i = 5;
    int j = 4 + 2;
    int x = i + j; // 5 + 6

    The code above can be condensed into:

    int i = 5; int j = 4 + 2; int x = i + j;

    Both sections of code will compile, but which one do you find easier to read? Chances are the first one. This is a rather simple examples as well, as you progress through your coding career you will have more complex codeblocks which it will become more important to organize it in such a way that you can quickly understanding it.

  • Spaces – the use of spaces can greatly increases the readiblity of your code. Let’s look at the example below:
  • int i = 5;
    int j = 4 + 2;
    int x = i + j; // 5 + 6

    The code above can be condensed into:

    int i=5;int j=4+2;int x=i+j;

    Again, the code will compile, but chances are you can more easily understand what the first block. Spacing after most syntax in the C# language allows your brain to decipher each element of the code quickly.

  • Tabbing – in some languages (Python, for example) the use of proper tabbing is required for the programming to compile correctly, in C#, it is highly recommended that you follow the following guidelines:
  • private void Name() {
    	int i = 4 + 3;
    	int j = 2 + 5;
    	int x = j - i;
    }

    Everything encapsulated in the “Name()” method is indented by one tab press, this clearly signifies the programmer that when the “Name()” method is called it will run lines 2 to 4 highlighted above. This code, of course, can be condensed down to:

    private void Name(){int i=4+3;int j=2+5;int x=j-i;}

    As you can see tabbing can make reading code a lot easier.

Variables

A variable is a type of storage that can hold a specific type of data. You can think of the data type as a contract between you and programming in which you are stating the type of data you will store in the variable. There are many data types, but the common ones we will be using are:

Data Types

  • int – an integer number ranging from -2,147,483,648 to 2,147,483,647.
  • int name = 5;
  • float – floating point number (decimal) -3.402823e38 to 3.402823e38.
  • float name = 5.1f;
  • bool – A logical types that can be either true or false.
  • bool name = false;
  • string – A sequence of characters, you are reading a string right now.
  • string name = "Hello World";

Variable Name

The variable name is what you use to identify our variables in our code. Think of it like naming your storage box. In C#, the best practice for naming variables follows pascal-casing, in which the first letter of the first word is lower-case, and each following word is upper-case. When creating a variable name, we can only use letters, digits, and underscores “_.” The first character must be a letter. Let’s look at some examples:

  • Single Word Name
  • int number = 5;
  • Two Word Name
  • float floatingNumber = 5.1;
  • Tree Word Name
  • bool trueOrFalse = false;
  • Letters, Numbers, Underscores
  • string programString_1 = "Hello World";

Assigning Variables

Up until this point, we have been assigning a value to all the variables we have created. This is denoted by the equal sign followed by the value to assign (int i = 3). This is not required in the C# language, and you can create an empty variable and assign a variable later. After you have instantiated (created) the variable, you do not need to write in the datatype. Let’s look at some examples.

  • Instantiate and Assign
  • int number = 5;
  • Instantiate then Assign
  • int number;
    number = 5;

Methods

A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments. In C#, every executed instruction is performed in the context of a method. The Main method is the entry point for every C# application and it is called by the common language runtime (CLR) when the program is started.

In this section, we will be looking at methods two different ways: constructing methods and calling methods. Constructing methods refers to creating a new method, while calling methods refers to running a specified method. Constructing methods, like variables, have a specific syntax that they follow:

Constucting Methods

  • Scope

  • The scope of a method sets the ability for other elements of the code to interact with the script. The scoping keywords that we will be using in this course are: private and public. The scope is only required in the construction of a new method and not when it is called. We will not be looking at scope too much in this course.

    // private scope
    private void NewMethod() {
    	// do something
    }
    
    // public scope
    public void NewerMethod() {
    	// do something
    }
  • Return Value

  • Methods can return values to the script that called them, the type of value that is return is specified in the creation of the method. In this course, we will return the variable datatypes stated above. If no return type is needed we state that the return type is “void,” if a return type is used we must use the keyword “return” to specify what we are returning.

    // no return type
    private void NewMethod() {
    	// do something
    }
    
    // int return type
    public int IntMethod() {
    	int i = 1;
    	return i;
    }
    
    // float return type
    public float BoolMethod() {
    	float f = 1.1;
    	return f;
    }
    
    // bool return type
    public bool BoolMethod() {
    	bool b = 1;
    	return b;
    }
    
    // string return type
    public string BoolMethod() {
    	string s = "Hello World";
    	return s;
    }
  • Method Name

  • The method name identifies the method in your code, just like a variable name. The main difference is that a method uses camel-casing, meaning it starts with a capital, and each new world is also capitalized.

    private void Single() {
    	// do something
    }
    
    public void MultiWords() {
    	// do something
    }
    
    public void VeryLongName() {
    	// do something
    }
  • Parameters

  • Methods can pass or take in data, like variables when called. When constructing a method we must specify the data we are willing to take in by stating the data in the parenthesis “()”:

    private void Single(int num) {
    	int i = num;
    }
    
    public void SetName(string name) {
    	string playerName = name;
    }
    
    public void CreatePlayer(string name, int level, bool isPlaying) {
    	string playerName = name;
    	int playerLevel = level;
    	bool playerPlaying = isPlaying;
    }
  • Encaspulation

  • Finally, we need to tell the method what to do when it is called – we do this through encapsulation. In short, this means we write the code we want to execute between the curly braces “{}”:

    private void Single(int num) {
    	int i = num; // is encapsulized
    }
    
    public void SetName(string name) {
    	string playerName = name; // is encapsulized
    }
    
    public void CreatePlayer(string name, int level, bool isPlaying) {
    	string playerName = name; // is encapsulized
    	int playerLevel = level; // is encapsulized
    }
    	bool playerPlaying = isPlaying;  // is not encapsulized and will throw an exception

Calling Methods

Calling methods is a far easier process than constructing methods. We call a method we run all the code encapsulated in the method. We also must pass in any parameters that are required to run the method. Let’s call the examples from the previous section:

NewMethod(); // No parameters
Single(7); // single parameter
CreatePlayer("John Doe", 1337, true); // multiple parameters
Mark as Complete
chevron_right