Data Types, Variables and literal values. Introduction to Programmimg. C# - Lesson Two(2)

Data Types, Variables and literal values. Introduction to Programmimg. C# - Lesson Two(2)


Please click here to read PART ONE

LESSON TWO

UNIT 1

Introduction

Many applications you’ll build in C# will require you to work with data. Sometimes that data will be hard-coded in your application. 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.

But more often, you’ll work with data that is unknown as you build your application. Perhaps the data is captured via keyboard input, or comes from a file or the internet. Therefore, you’ll need to build structures called variables that can store data in memory as your application runs.

Suppose you want to display a formatted message to the end user containing different types of data. The message would include hard-coded strings, but may combine it with information your application 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.

In this lesson, you’ll create hard-coded literal values that contain different data types. You’ll create variables that can hold certain data types, set those variables with a value, then retrieve those values later in code. And finally, you’ll learn how you can simplify your code by allowing the compiler to shoulder some of the work. By the end of this lesson, you’ll be able to create literal values and store and retrieve data in variables.

Learning objectives

In this lesson, you will:

Create literal values for five basic data types

Declare and initialize variables

Retrieve and set values in variables

Allow the compiler to determine the data type for your variable when initializing

Prerequisites

Must understand basic C# syntax rules, like how to use

Console.WriteLine()        

UNIT 2

Literal values

A literal value is a hard-coded value that never changes.

Exercise — Print out different literal data types

There are many data types in C#. But as you’re getting started you only need to know about five or six data types since they cover most scenarios. Let’s display a literal instance of data type to the output pane.

Note: — You may notice as you begin to work in the code window that it colors certain syntax in different colors to indicate keywords, operators, data types and more. Begin to take notice of the colors. It can help you spot syntax errors as you enter characters, and can help you understand the code more effectively.

Step 1: Write a string literal to the console. If we wanted alphanumeric words, phrases, or data for presentation, not calculation, we use string literal by surrounding the words with double-quotes.

Add the following line of code in the code editor:

Console.WriteLine("Hello World!");        

If you run the code, you’ll get the following output.

Hello World!

Step 2: Write a char literal to the console. If we only wanted a single alphanumeric character printed to screen, we could create a char literal by surrounding one alphanumeric character in single-quotes.

Add the following line of code in the code editor:

Console.WriteLine('b');        

If you enter the following code:

Console.WriteLine('Hello World!');        

You would get the following error:

(1,19): error CS1012: Too many characters in character literal The C# compiler was expecting a single character (since you used the character literal syntax) but you supplied 12 characters instead! Just like the string data type, you use char whenever you have a single alphanumeric character for presentation (not calculation).

The term char is short for character. In C# and some other programming languages, they’re officially referred to as “char”, but frequently referred to as a “character”.

Step 3: Write an int literal to the console If you want to print a numeric whole number (no fractions) value to Output, you can use an int literal. An int literal requires no additional operators like the char or string (more on string later).

The term int is short for integer, which you may recognize from studying math. In C#, they’re officially referred to as “int”, but frequently known by their alter ego “integer”.

Add the following line of code in the code editor:

Console.WriteLine(123);        

If you run the code, you’ll get the following output.

123        

Step 4: Write a decimal literal to the console If we wanted to print a number that includes values after the decimal point, we could use a decimal literal. 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 type decimal.

Add the following line of code in the code editor:

Console.WriteLine(12.30m);        

If you run the code, you’ll get the following output.

12.30

Without the literal suffix m, the decimal number in the previous example will be treated as type double by the compiler and the output will be

12.3

Note: — You can use either a lower-case m or upper-case M as the literal suffix for a decimal.

Step 5: Write a bool literal to the console If we wanted to print a value representing either true or false, we could use a bool literal.

Add the following lines of code in the code editor:

Console.WriteLine(true);
Console.WriteLine(false);        

This will produce the following output:

True False

The term bool is short for boolean, which you may also recognize from studying math. In C# and some other programming languages they’re officially referred to as “bool”, but often developers use the term “boolean”. The bool literals represent the idea of truth and falsehood. We’ll use bool values extensively when we start to add decision logic to our applications. We’ll evaluate expressions to see whether the expression is true or false.

Why emphasize data types?

Data types play a central role in C#. In fact, the emphasis on data types is one of the key distinguishing features of C# compared to other languages like Python and JavaScript. The designers of C# believed they can help developers avoid common software bugs by enforcing data types. You’ll see this concept unfold as you learn more about C#.

Presentation versus calculation and evaluation

Data types like strings and chars are used for “presentation, not calculation”. If you need to perform a mathematical operation on numeric values, you should use an int or decimal. If you have data that is used for presentation or reference purposes only, you should use a string or char data type.

Suppose you needed to collect data from a user like a phone number or postal code. Depending on the country where you live, that data may consist of numeric characters. However, since you rarely perform mathematical calculations on phone numbers and postal codes, you should prefer to use a string data type when working with them. The same can be said of bool. If you need to work with the words “true” and “false” in your application, you would use a string. However, if you need to work with the concept of true or false when performing an evaluation, you use a bool. This should become clearer as we perform evaluations in other lessons.

It’s important to know that these values may look like their string literal equivalents. In other words, you may think these statements are the same:

Console.WriteLine("123");
Console.WriteLine(123);
Console.WriteLine("true");
Console.WriteLine(true);        

However, that’s merely how they’re printed to screen. The fact is that the kinds of things you can do with the underlying int or bool will be different than their string equivalent.

Recap

The main takeaway is that there are many data types, but we’ll focus on just a few for now: string for words, phrases, or any alphanumeric data for presentation, not calculation char for a single alphanumeric character, int for a whole number, decimal for a number with a decimal, bool for a true/false value.


Unit 3

Declare variables

A literal value is literally a hard-coded value. However, most applications will require us to work with values that we don’t know much about ahead of time. In other words, we’ll need to work with data that comes from users, from files, or from across the network.

When we need to work with data from outside of our code, we’ll declare a variable.

What is a variable?

A variable is a data item that may change its value during its lifetime. You use variables to temporarily store values that you intend to use later in your code. A variable is a friendly label that we can assign to a computer memory address. When we want to temporarily store a value in that memory address, or whenever we want to retrieve the value that is stored in the memory address, we just use the variable name we created.

Declaring a variable

To create a new variable, you must first declare the data type of the variable, then give it a name.

string firstName;        

In this case, we’re creating a new variable of type string called firstName. From now on, this variable can only hold string values. I can choose any name as long as it adheres to a few C# syntax rules for naming variables.

Variable name rules and conventions

A software developer once famously said “The hardest part of software development is naming things.” Not only does the name of a variable have to follow certain syntax rules, it should also be used to make the code more human-readable and understandable. That’s a lot to ask of one line of code!

Here’s a few important considerations about variable names:

· 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. Developers use the underscore for a special purpose, so try to not use that for now.

· Variable names must not be a C# keyword. For example, you cannot use the following variable declarations: decimal decimal; or string string;.

· Variable names are case-sensitive, meaning that

string Value;        

and

string value;        

are two different 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 be descriptive and meaningful in your application. 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 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. The example

string firstName;        

follows all of these rules and conventions, assuming I want to use this variable to store data that represents someone’s first name.

Variable name examples

Here’s a few examples of variable declarations using the data types we learned about previously.

char userOption;
int gameScore;
decimal particlesPerMillion;
bool processedCustomer;        

Recap

Here’s the main takeaways you’ve learned so far about variables:

Variables are temporary values you store in the computer’s memory. Before you can use a variable, you have to declare it. To declare a variable, you first select a data type for the kind of data you want to store, and then give the variable a name that follows the rules. Now that we know how to declare a variable, let’s learn how to set, retrieve, and initialize the value of a variable.


Unit 4

Setting and getting values from variables

Because variables are temporary storage containers for data, they’re meant to be written to and read from. You’ll get a chance to do both in the following exercise.

Exercise –

Working with variables

In this exercise, you’ll declare a variable, assign it a value, retrieve its value, and more.

Step 1: Delete all of the code in the code editor.

Use your mouse to highlight all of the text in the code editor, then select the backspace or del key to remove everything. Later, we’ll learn a different, less destructive technique for disabling the lines of code you no longer want to execute.

Step 2: Declare a variable and assign a value to it

To assign a value to a variable, you use the assignment operator, which is a single equals character =.

Add the following code in the code editor:

string firstName;
firstName = "Bob";        

Assigning a value is also referred to as “setting the variable”, or simply, a “set” operation. assign a value to a variable It’s important to notice that assignment happens from right to left. In other words, the C# compiler must first understand the value on the right side of the assignment operator, then it can perform the assignment to the variable on the left side of the assignment operator. If you reverse the order, you’ll confuse the C# compiler.

Step3: Modify the code you wrote in Step 2 to match the following code:

string firstName;
"Bob" = firstName;        

Now, run the code. The first error you would see in the output console:

(2,1): error CS0131: The left-hand side of an assignment must be a variable, property or indexer

Step 4: Improperly assign a value of the incorrect data type to the variable Earlier, we declared that C# was designed to enforce types. When working with variables, enforcing types means you can’t assign a value of one data type to a variable declared to hold a different data type.

Modify the code you wrote in Step 3 to match the following code:

int firstName;
firstName = "Bob";        

Now, run the code. You’ll see the following error in the output console:

(2,9): error CS0029: Cannot implicitly convert type ‘string’ to ‘int’

The error message hints at what the C# compiler tries to do behind the scenes. It tried to “implicitly convert” the string “Bob” to be an int value; however, that is impossible. In other words, you can’t put a square peg into a round hole. Even so, C# tried to force the square peg to fit into the round hole, but there’s no numeric equivalent for the word “Bob”, so it failed. We’ll talk more about implicit and explicit type conversion in other lessons.

Step 5: Retrieve a value you stored in the variable

To retrieve a value from a variable, you just use the name of the variable. This example will set a variable’s value, then retrieve that value and print it to the console.

Modify the code you wrote in Step 4 to match the following code:

string firstName; firstName = "Bob";
Console.WriteLine(firstName);        

Now, run the code. You’ll see the following result in the output console:

Bob

Retrieving a value from a variable is also referred to as “getting the variable”, or simply, a “get” operation.

Step 6: Reassign the value of a variable

You can reuse and reassign the variable as many times as you want. This example illustrates that idea. Modify the code you wrote in Step 5 to match the following code:

string firstName; 
firstName = "Bob"; Console.WriteLine(firstName);
firstName = "Beth"; Console.WriteLine(firstName);
firstName = "Conrad"; Console.WriteLine(firstName);
firstName = "Grant"; Console.WriteLine(firstName);        

Now, run the code. You’ll see the following result in the output console:

Bob Beth Conrad Grant

Step 7: Initialize the variable

You must set a variable to a value before you can get the value from the variable. Otherwise, you’ll see an error. Modify the code you wrote in Step 6 to match the following code:

string firstName;
Console.WriteLine(firstName);        

Now, run the code. You’ll see the following result in the output console:

(2,19): error CS0165: Use of unassigned local variable ‘firstName’

To avoid the possibility of an unassigned local variable, we recommend that you set the value as soon as possible after you declare it. In fact, you can perform both the declaration and setting the value of the variable in one line of code. This technique is called initializing the variable. Modify the code you wrote earlier in this step to match the following code:

string firstName = "Bob";
Console.WriteLine(firstName);        

Now, run the code. You should see the following output:

Bob

Recap

Here’s the main takeaways you learned about working with variables so far:

You must assign (set) a value to a variable before you can retrieve (get) a value from a variable. You can initialize a variable by assigning a value to the variable at the point of declaration. Assignment happens from right to left. You use a single equals character as the assignment operator. To retrieve the value from the variable, you merely use the variable’s name


Unit 5

Implicitly typed local variables

The C# compiler affords many conveniences as you write your code. It can infer your variable’s data type by its initialized value.

In this unit, you’ll learn about this feature, called implicitly typed local variables.

What are implicitly typed local variables?

An implicitly typed local variable is created using the var keyword, which instructs the C# compiler to infer the type. After the type is inferred, it’s the same as if the actual data type had been used to declare the variable. In the following example, we’ll declare a variable using the var keyword instead of the string keyword.

var message = "Hello world!";        

Because the variable message is immediately set to the string value “Hello World!”, the C# compiler understands the intent and treats every instance of message as an instance of type string. In fact, the message variable is typed to be a string and can never be changed. Here, we’ll attempt to set message to the literal decimal value of 10.0m.

var message = "Hello World!";
message = 10.0m;        

If you run this code, you’ll see the following error message.

(2,11): error CS0029: Cannot implicitly convert type ‘decimal’ to ‘string’

Note: Other programming languages use the var keyword differently.

In C#, the variable is statically typed by the compiler regardless of whether you use the actual data type or allow the compiler to infer the data type. In other words, the type is locked in at the time of declaration and therefore will never be able to hold values of a different data type. You can only use the var keyword if the variable is initialized. It’s important to understand that the var keyword is dependent on the value you use to initialize the variable. If you try to use the var keyword without initializing the variable, you’ll receive an error when you attempt to compile your code.

var message;        

If you attempt to run this code, as it compiles you’ll see the following output:

(1,5): error CS0818: Implicitly-typed variables must be initialized

Why use the var keyword?

The var keyword has been widely adopted in the C# community, so it’s likely if you look at a code example in a book or online, you’ll see the var keyword used instead of the actual data type name. So, we wanted to make sure to introduce it in this lesson.

However, the var keyword has an important use in C#. For reasons that may not be clear to you until you write advanced code, there are situations where the data type may not be obvious at the time you initialize the variable. In fact, in some cases, C# may invent a new data type just for your code and may not be able to give it a predictable name ahead of time. Again, this is an advanced feature of C# that will be covered in other lessons.

As you get started, we recommend you continue to use the actual data type name when you declare variables. Using the data type when you declare variables will help you be purposeful as you write your code.

Recap

The most important takeaways from this unit about the var keyword and implicitly typed local variables:

o1. The var keyword tells the compiler to infer the data type of the variable based on the value it is initialized to.

o2. You’ll likely see the var keyword as you read other people’s code; however, you should use the data type when possible.

Unit 6

Challenge

In this challenge, you’ll write code that will combine literal and variable values into a single message.

Step 1: Delete all of the code in the?.NET Editor from the earlier exercise

Select all of the code in the?.NET Editor then select the del or backspace key to delete it.

Step 2: Write code in the?.NET Editor to display a message

When you’re finished, the message should resemble the following output:

Hello, Bob! You have 3 messages in your inbox. The temperature is 34.4 celsius.

Store the following values from the output in variables:

Bob
3
34.4

These variables should be given names that reflect their purpose. Make sure you select the correct data type for each of the variables based on the type of data it will hold.

Finally, you’ll combine the variables with literal strings passed into a series of Console.Write() commands to form the complete message.

Solution

The following code is one possible solution for the challenge from the previous unit.

string name = "Bob";
int messages = 3;
decimal temperature = 34.4m;
Console.Write("Hello, ");
Console.Write(name);
Console.Write("! You have ");
Console.Write(messages);
Console.Write(" messages in your inbox. The temperature is ");
Console.Write(temperature);
Console.Write(" celsius.");        

This code is merely “one possible solution” because we didn’t specify exactly how to create the output. For example, it’s possible you could have used more Console.Write() statements; however, you should have initialized three variables to store the three values per the instructions in the challenge.

Furthermore, you should have used:

· a variable of type string to hold the name “Bob”.

· a variable of type int to store the number of messages.

· a variable of type decimal to store the temperature.

If you were successful, congratulations!

Important

If you had trouble completing this challenge, maybe you should review the previous units before you continue. All new ideas we will be describing in other lessons will depend on your understanding of the ideas that were presented in this lesson.


Thank you for your time, i hope this article add some value to you. Please share someone might be in need of it.

In case you missed part one click here or copy and paste the link below

https://medium.com/@ferdinandcharles6/introduction-to-programmimg-c-b2568b7e8554

Bye for now see you next week, it gets more exciting in part 3

要查看或添加评论,请登录

Ferdinand Charles的更多文章

社区洞察

其他会员也浏览了