Programming languages like C# let you write instructions that you want the computer to carry out. Each programming language has its own syntax, but after learning your first programming language and attempting to learn another one, you'll quickly realize that they all share many similar concepts. A programming language's job is to allow a human to express their intent in a human-readable and understandable way. The instructions you write in a programming language are called "source code" or just "code". Software developers write code
At this point, a developer can update and change the code, but the computer can't understand the code. The code first must be compiled into a format that the computer can understand.
Compilation
A special program called a compiler converts your source code into a different format that the computer's central processing unit (CPU) can execute. When you used the green Run button in the previous unit, the code you wrote was first compiled, then executed.
Why does code need to be compiled? Although most programming languages seem cryptic at first, they can be more easily understood by humans than the computer's preferred language. The CPU understands instructions that are expressed by turning thousands or millions of tiny switches either on or off. Compilers bridge these two worlds by translating your human-readable instructions into a computer-understandable set of instructions.
Syntax
The rules for writing C# code is called syntax. Just like human languages have rules regarding punctuation and sentence structure, computer programming languages also have rules. Those rules define the keywords and operators of C# and how they are put together to form programs.
When you wrote code into the .NET Editor, you may have noticed subtle changes to the color of different words and symbols. Syntax highlighting is a helpful feature that you'll begin to use to easily spot mistakes in your code that don't conform to the syntax rules of C#.
The C# programming language allows you to build many types of applications, like:
- Business applications to capture, analyze, and process data
- Dynamic web applications that can be accessed from a web browser
- Games, both 2D and 3D
- Financial and scientific applications
- Cloud-based applications
- Mobile applications
My first line of code in .NET Editor
There's a long-standing tradition among software developers to print the phrase "Hello World!" to the console output window.
Common mistakes new programmers make:
- Entering lower-case letters instead of capitalizing C in Console, or the letters W or L in WriteLine.
- Entering a comma instead of a period between Console and WriteLine.
- Forgetting to use double-quotation marks, or using single-quotation marks to surround the phrase Hello World!.
- Forgetting a semi-colon at the end of the command.
How to Display a new message
1.Modify the code you wrote so that it's prefixed by a code comment using two forward slashes //:
You can create a code comment by prefixing a line of code with two forward slashes //. This prefix instructs the compiler to ignore all the instructions on that line.
Code comments are helpful when you're not ready to delete the code yet, but you want to ignore it for now. You can also use code comments to add messages to yourself or others who may later read the code, reminding you of what the code is doing
2.Add new lines of code to match the following code snippet.
The difference between Console.Write and Console.WriteLine
Console.WriteLine prints a message to the output console. At the end of the line, it adds a line feed similar to pressing Enter or Return to create a new line.
To print to the output console, but without adding a line feed at the end, you use the second technique, Console.Write. So, the next call to Console.Write prints another message to the same line.
How does your code work
Let's focus on the following line of code you wrote:
Console.WriteLine("Hello World!");
When you ran your code, you saw that the message Hello World! was printed to the output console. When the phrase is surrounded by double-quotation marks in your C# code, it's called a literal string. In other words, you literally wanted the characters H, e, l, l, o, and so on, sent to the output.
The Console part is called a class. Classes "own" methods; or you could say that methods live inside of a class. To visit the method, you must know which class it's in. For now, think of a class as a way to represent an object. In this case, all of the methods that operate on your output console are defined inside of the Console class.
There's also a dot (or period) that separates the class name Console and the method name WriteLine(). The period is the member access operator. In other words, the dot is how you "navigate" from the class to one of its methods.
The WriteLine() part is called a method. You can always spot a method because it has a set of parentheses after it. Each method has one job. The WriteLine() method's job is to write a line of data to the output console. The data that's printed is sent in between the opening and closing parenthesis as an input parameter. Some methods need input parameters, while others don't. But if you want to invoke a method, you must always use the parentheses after the method's name. The parentheses are known as the method invocation operator.
Finally, the semicolon is the end of statement operator. A statement is a complete instruction in C#. The semicolon tells the compiler that you've finished entering the command.
Literal value
Many of the applications that you'll build in C# will require you to work with data. Sometimes that data will be hard-coded in your application. Hard-coded values are values that are constant and unchanged throughout the execution of the program. For example, you may need to print a message to the user when some operation succeeds. A "success" message would likely be the same every time the application is executed. This hard-coded value can also be called a constant, or a literal value.
Suppose you want to display a formatted message to the end user containing different types of data. The message would include hard-coded strings combined with information your app collects from the user. To display a formatted message, you'll need to create both hard-coded values and define variables that can store data of a certain type, whether numeric, alphanumeric, and so on.
Different literal data types
1.Character literals
If you only wanted a single alphanumeric character printed to screen, you could create a char literal by surrounding one alphanumeric character in single quotes. The term char is short for character. In C#, this data type is officially named "char", but frequently referred to as a "character"
Notice that the letter b is surrounded with single quotation marks 'b'. Single quotes create a character literal. Recall that using double quotation marks creates a string data type.
2.Integer literals
If you want to display a numeric whole number (no fractions) value in the output console, you can use an int literal. The term int is short for integer, which you may recognize from studying math. In C#, this data type is officially named "int", but frequently referred to as "integer". An int literal requires no other operators like the string or char.
3.Floating-point literals
A floating-point number is a number that contains a decimal, for example 3.14159. C# supports three data types to represent decimal numbers: float, double, and decimal. Each type supports varying degrees of precision.
Float Type Precision
To create a float literal, append the letter F after the number. In this context, the F is called a literal suffix. The literal suffix tells the compiler you wish to work with a value of float type. You can use either a lower-case f or **upper-case F **as the literal suffix for a float.
Double ~15-17 digits
To create a double literal, just enter a decimal number. The compiler defaults to a double literal when a decimal number is entered without a literal suffix.
Decimal 28-29 digits
To create a decimal literal, append the letter m after the number. In this context, the m is called a literal suffix. The literal suffix tells the compiler you wish to work with a value of decimal type. You can use either a lower-case m or upper-case M as the literal suffix for a decimal.
4.Boolean literals
If you wanted to print a value representing either true or false, you could use a bool literal. The term bool is short for Boolean. In C#, they're officially referred to as "bool", but often developers use the term "Boolean".
Variable
A variable is a container for storing a type of value. Variables are important because their values can change, or vary, throughout the execution of a program. Variables can be assigned, read, and changed. You use variables to store values that you intend to use in your code. A variable name is a human-friendly label that the compiler assigns to a memory address. When you want to store or change a value in that memory address, or whenever you want to retrieve the stored value, you just use the variable name you created.
Declare a variable
To create a new variable, you must first declare the data type of the variable, and then give it a name.
string firstName;: In this case, you're creating a new variable of type string called firstName. From now on, this variable can only hold string values.
Variable name rules and conventions
- Variable names can contain alphanumeric characters and the underscore character. Special characters like the hash symbol # (also known as the number symbol or pound symbol) or dollar symbol $ are not allowed.
- Variable names must begin with an alphabetical letter or an underscore, not a number.
- Variable names are case-sensitive, meaning that string Value; and string value; are two different variables.
- Variable names must not be a C# keyword. For example, you cannot use the following variable declarations: decimal decimal; or string string;
Coding conventions for variables
- Variable names should use camel case, which is a style of writing that uses a lower-case letter at the beginning of the first word and an upper-case letter at the beginning of each subsequent word. For example, string thisIsCamelCase;.
- Variable names should begin with an alphabetical letter. Developers use the underscore for a special purpose, so try to not use that for now.
- Variable names should be descriptive and meaningful in your app. Choose a name for your variable that represents the kind of data it will hold.
- Variable names should be one or more entire words appended together. Don't use contractions or abbreviations because the name of the variable (and therefore, its purpose) may be unclear to others who are reading your code.
- Variable names shouldn't include the data type of the variable. You might see some advice to use a style like string strValue;. That advice is no longer current.
Variable name examples
- char userOption;
- int gameScore;
- decimal particlesPerMillion;
- bool processedCustomer;
Reassign the value of a variable
String concatenation
**String concatenation **is "programmer speak" for simply combining two or more string values into a new string value. Unlike addition, the second value is appended to the end of the first value, and so on. In the following exercise, you'll write code to concatenate string values together.
Concatenate multiple variables and literal strings
String interpolation
String interpolation combines multiple values into a single literal string by using a "template" and one or more interpolation expressions. An interpolation expression is indicated by an opening and closing curly brace symbol { }. You can put any C# expression that returns a value inside the braces. The literal string becomes a template when it's prefixed by the $ character.
In other words, instead of writing the following line of code:
string message = greeting + " " + firstName + "!";
You can write this more concise line of code instead:
string message = $"{greeting} {firstName}!";
Use string interpolation to combine a literal string and a variable value
Use string interpolation with multiple variables and literal strings
Combine verbatim literals and string interpolation
Suppose you need to use a verbatim literal in your template. You can use both the verbatim literal prefix symbol @ and the string interpolation $ symbol together.
Perform addition with implicit data conversion
Often, you'll want to perform mathematical operations on numeric data. You'll start with addition in this unit, and expand to other operations in the next unit because there's an important lesson to learn about how the C# compiler parses and interprets your code
Add two numeric values
To add two numbers together, you'll use the addition operator, which is the plus symbol +. Yes, the same plus symbol + that you use for string concatenation is also used for addition. The reuse of one symbol for multiple purposes is sometimes called "overloading the operator" and happens frequently in C#.
In this instance, the C# compiler understands what you're attempting to do. The compiler parses your code and sees that the + (the operator) is surrounded by two numeric values (the operands). Given the data types of the variables (both are ints), it figures out that you intended to add those two values
Mix data types to force implicit type conversions
What happens if you try to use the + symbol with both string and int values?
Attempt a more advanced case of adding numbers and concatenating strings
Instead of adding the int variable widgetsSold to the literal int 7, the compiler treats everything as a string and concatenates it all together
Add parentheses to clarify your intention to the compiler
The parentheses symbol () becomes another overloaded operator. In this case, the opening and closing parentheses form the order of operations operator, just like you might use in a mathematical formula. You indicate that you want the inner-most parentheses resolved first resulting in the addition of int values widgetsSold and the value 7. Once that is resolved, then it will implicitly convert the result to a string so that it can be concatenated with the rest of the message.
Perform math operations
Perform basic math operations. Write code to perform addition, subtraction, multiplication, and division with integers.
As you can see:
- + is the addition operator
- - is the subtraction operator
- * is the multiplication operator
- / is the division operator
However, the resulting quotient of the division example may not be what you may have expected. The values after the decimal are truncated from the quotient since it is defined as an int, and int cannot contain values after the decimal.
Code to exercise C#'s order of operations
As you learned in the previous exercise, you can use the () symbols as the order of operations operators. However, this isn't the only way the order of operations is determined.
In math, PEMDAS is an acronym that helps students remember the order of operations. The order is:
- Parentheses (whatever is inside the parenthesis is performed first)
- Exponents
- Multiplication and Division (from left to right)
- Addition and Subtraction (from left to right)
C# follows the same order as PEMDAS except for exponents. While there's no exponent operator in C#, you can use the System.Math.Pow method. The module "Call methods from the .NET Class Library using C#" will feature this method and others
Increment and decrement values
The final basic operations you'll learn about in this module is how to increment and decrement values using special operators that are combinations of symbols. You'll need to increment and/or decrement values, especially when you're writing looping logic or code that interacts with a data structure.
The += operator adds and assigns the value on the right of the operator to the value on the left of the operator. So, lines two and three in the following code snippet are the same
- int value = 0; // value is now 0.
- value = value + 5; // value is now 5.
- value += 5; // value is now 10
The ++ operator increments the value of the variable by 1. So, lines two and three in the following code snippet are the same:
- int value = 0; // value is now 0.
- value = value + 1; // value is now 1.
- value++; // value is now 2.
To write code to increment and decrement a value
Position the increment and decrement operators
Both the increment and decrement operators have an interesting quality — depending on their position, they perform their operation before or after they retrieve their value. In other words, if you use the operator before the value as in ++value, then the increment will happen before the value is retrieved. Likewise, value++ will increment the value after the value has been retrieved.
Using .Net Editor to write a letter.


























Top comments (0)