37,19 €
A C# 7 beginners guide to the core parts of the C# language!
About This Book
Who This Book Is For
This book will appeal to anyone who is interested in learning how to program in C#. Previous programming experience will help you get through the initial sections with ease, although, it's not mandatory to possess any experience at all.
What You Will Learn
In Detail
Beginning C# 7 Hands-On - The Core Language teaches you core C# language and syntax in a working Visual Studio environment. This book covers everything from core language through to more advanced features such as object-oriented programming techniques. This book is for C# 7 beginners who need a practical reference to core C# language features.
You'll also gain a view of C# 7 through web programming with web forms, so you'll learn HTML, basic CSS, and how to use a variety of controls, such as buttons and drop-down lists. You'll start with the fundamentals of C# and Visual Studio, including defining variables, interacting with users, and understanding data types, data conversions, and constants.
You'll move on to checking conditions using if/else blocks, and see how to use loops to do things such as repeat blocks of code. After covering various operators to evaluate and assign control structures, you'll see how to use arrays to store collections of data. By the time you've finished the book, you'll know how to program the vital elements of the core C# language. These are the building blocks that you can then combine to build complex C# programs.
Style and approach
A comprehensive book that blends theory with just the right amount of practical code implementations, to help you get up and running with the C# programming language. You'll also get to work with other tools and technologies that complement C# programming. Each core part of the C# 7 language is coded as you learn, and code output is tested every time to verify the syntax is working as expected, so it's easy for you to learn directly from the working code examples.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 490
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: August 2017
Production reference: 1300817
ISBN 978-1-78829-654-0
www.packtpub.com
Author
Tom Owsiak
Project Coordinator
Suzanne Coutinho
Acquisition Editor
Dominic Shakeshaft
Proofreader
Safis Editing
Content Development Editor
Gary Schwartz
Indexer
Rekha Nair
Technical Editor
Joel D'Souza
Graphics
Kirk D'Penha
Copy Editors
Tom Jacob
Gladson Monteiro
Production Coordinator
Arvindkumar Gupta
Tom Owsiak has eight years of experience as a teacher in Mathematics, Physics, Statistics, and Programming. He has worked for five years as a database programmer using various technologies such as .NET, Clipper, SQL, SQL Server, SAS, and Excel, and many related technologies.
Tom is the publisher of one of the most successful courses on Udemy, called Learn C# With Visual Studio 2013. Currently, Tom works as a Mathematics and Computer Science teacher at Mercy College in Dobbs Ferry, NY.
For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review.
If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Beginning C# Hands-On - The Core Language teaches you the core C# language and syntax in a working Visual Studio environment. This book covers everything from the core language through to more advanced features, such as object-oriented programming techniques. This book is for C# beginners who need a practical reference to the core C# language features.You'll also gain a view of C# through web programming with web forms, so you'll learn HTML, basic CSS, and how to use a variety of controls, such as buttons and drop-down lists. You'll start with the fundamentals of C# and Visual Studio, including defining variables, interacting with users, and understanding data types, data conversions, and constants. You'll move on to checking conditions using if...else blocks, and how to use loops to do things such as repeat blocks of code. After covering various operators to evaluate and assign control structures, you'll see how to use arrays to store collections of data. By the time you’ve finished the book, you’ll know how to program the vital elements of the core C# language. These are the building blocks that you can then combine to build complex C# programs.
Visual Studio 2017 will install and run on Windows 7 or above, and 2 GB or 4 GB of RAM is recommended. Minimum 1 GB hard disk space is essential too.
This book will appeal to anyone who is interested in learning how to program in C#. Previous programming experience will help you get through the initial sections with ease, although it’s not mandatory to possess any experience at all.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, path names, dummy URLs, user input, and Twitter handles are shown as follows: "Specifically, Default.aspx is a file that contains the markup of the elements on the web page."
A block of code is set as follows:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"> <asp:ListItem>Monday</asp:ListItem> <asp:ListItem>Tuesday</asp:ListItem> <asp:ListItem>Wednesday</asp:ListItem></asp:DropDownList>
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"> <asp:ListItem>
Monday
</asp:ListItem> <asp:ListItem>
Tuesday
</asp:ListItem> <asp:ListItem>
Wednesday
</asp:ListItem></asp:DropDownList>
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "If you wish, click on Browse and save the file to a location you choose and click on OK."
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you. You can download the code files by following these steps:
Log in or register to our website using your email address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Beginning-CSharp-Hands-On-The-Core-Language. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/BeginningCSharpHandsOnTheCoreLanguage_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
If you visit a page like indeed.com and enter C# in the what box, you'll get results that show that there are many jobs in this field, as shown in Figure 1.1.1. This shows that C# is a very valuable skill to master. Perhaps you just like to tinker, and C# is great for that as well:
In this chapter, we're going to take a look at how to get Visual Studio 2017. You can either go directly to www.visualstudio.com/downloads or just do a search for Visual Studio 2017 download. This should bring you to a page similar to this one:
Keep in mind that these pages are updated regularly. In the preceding screenshot, you will see that there are several versions. The one that interests us, of course, is Visual Studio Community 2017, the free version.
Click on Free download. This should automatically download a small installer. Depending on how your system is set up, it will either download it directly to the Downloads folder, or prompt you for where you want to save it. I've created a VS_Community folder inside my Downloads folder and saved it there. Of course, you can save it wherever you want to. Once this is done--it won't take long as it's just a small file--locate the downloaded VS_Community EXE file and open it up.
Once you open it, you should see this screen:
Click on Continue, which should take you through to the next screen:
From here, you can select the set of features you want to install on your system. For our purposes, I've chosen .NET desktop development at the top. If you click on it, you should see a check mark appear in the top corner to show that it's been selected:
Down at the bottom of the window, there's a location bar. If you click on the three little dots, you can select where you want the Visual Studio program to be installed on your system. On the right-hand side, you have a summary field:
This tells you what's going to be installed; also, down at the bottom, it says Total install size, 3.06 GB, so that's how much minimum free space you need wherever you're going to install this. Then, of course, click on the Install button in the lower right-hand corner. This should bring you to a page similar to this one:
Now, it's just a matter of waiting for everything to be downloaded and then applied to your system. One thing that I recommend you do at this point is temporarily disable your antivirus software while this is being installed because it could interfere with the installation process. I got to about 90 percent and my system hung when I installed it. I went back and disabled my anti-virus software and it installed fine. You may have to do the same.
Once it's downloaded and installed, you should see a screen similar to this one:
From here on, of course, you can either look at the release notes if you want, or just click on the Launch button. Go ahead and click on the Launch button. This should bring you to a screen similar to this one:
If you want, you can sign in with your Microsoft account, if you remember. I chose Not now, maybe later. The next step is to choose the interface:
I like the standard Blue one. Of course, you can use the Dark one or the Light one, whichever one you like, and then click on Start Visual Studio. Once it's loaded, it should look very similar to the one that you see right here:
Now Go to Help > About Microsoft Visual Studio; you'll see the version that you have installed. Mine is 15.3.0, which is the latest version at the time of this writing. Make sure that yours is the same or above (it should be, as you just downloaded the latest version from Microsoft); otherwise, the code samples that we create will not work because they rely on the features of C# available in this version. Okay, close the About box. That's it! You're now ready to start learning C# 7.
In this chapter, you learned how to locate, download, install, and launch Visual Studio Community. In the next chapter, we'll take greater control of Visual Studio and configure it to some extent.
In this chapter, we will configure the appearance of Visual Studio a little further.
To get started with customizing Visual Studio, click in the Quick Launch box in the upper right-hand corner, as shown in the following screenshot. Then, enter a word, such as font, and select the first item:
From here, you can configure many different settings. For example, you can select a Text Editor, which controls the size of the code in the window so that it's easy to read. The font size should be something big, such as 20—it makes a real difference; that is, when you are learning, how big things are makes a difference. They're easier to understand simply because they're bigger. Refer to the following screenshot to see how this is done:
In the next stage, we will customize the Statement Completion settings, as shown in the following screenshot. This is a very useful feature that makes coding more efficient. Again, set it to something big:
Next, let's configure the Environment fonts. Again, there are many possible options. One that I use very commonly is Segoe UI. Once more, set it to something big, for example, 18; that is, something easy to read in any case, as shown in the following screenshot:
Click on OK when you're finished. Some of these changes take effect immediately and some don't. For example, as you will see with Environment fonts, the text enlarges immediately.
Now, one thing that's useful is being able to position some of the panels. What do I mean by this? Try the following.
Click on View and then select Solution Explorer—that's a window or a panel. You can position this panel in many places. If you click where it says Solution Explorer and drag it, you can liberate this panel and then place it where you like. You are also given a really nice preview of what to expect once it drops. So, if you drag the Solution Explorer and hover your mouse at the top box located on the cross, a transparent blue area appears. The blue area tells you that it's going to go across the top. Again, if you click and drag it to the left-hand side of the screen and drop it, the Solution Explorer will be positioned on the left-hand side.
This is how you can control the layout of the panels—just drag them around the screen. Sometimes, you'll get a cross like the one shown in the preceding screenshot. This simply tells you that if you hover your mouse over the middle of the cross, the document that you're holding with your mouse will be tabbed together with other open windows, like the Start Page in this example. Now they are basically tabbed as a unit—the Start Page and the Solution Explorer panel. If you drag it once more and then drop it on the right-hand side, for instance, it will appear where it is commonly positioned:
One more useful thing that you can do is enable Auto Hide of panels such as Solutions Explorer. This means that when you're not using a panel, it hides from view, giving you access to more space.
If you click on the pin at the top right-hand corner of the panel, as shown in the following screenshot, you can enable Auto Hide. On the other hand, if you want it back, you click on the words Solution Explorer that appear vertically below the right-hand side of the screen, and then it reappears. If you want to pin the panel back to the position you had selected, just click on the pin again. Now it is back to where you had positioned it, and it will stay there even if you mouse away from it:
In this chapter, we reviewed some of the things that you can do to make working Visual Studio easier.
In the next chapter, we will create a simple C# program and run it.
In this chapter, you will create and run a simple first web page. It will contain the minimum that you need to be able to do work with C# later.
To begin, crank up Visual C# and do the following:
In the
File
menu, select
New
, and then select
Web Site
.
Press
Shift
+
Alt
+
N
.
From the
New Web Site
box, select
Visual C#
for the language, as shown in the following screenshot:
To keep things as simple as possible, select
ASP.Net Empty Web Site
.
At the bottom of the dialog box, in the Web location field, the default value File System is sufficient.
If you wish, click on Browse and save the file to a location you choose and click on OK.
After you click on OK, you'll see the Solutions Explorer window on the right-hand side of the screen, as shown in the following code. The Solutions Explorer shows the structure of how things are designed in Visual C#. You'll notice that there is a Solution; within the Solution, there is a website, and within the website there are different files that make up the site.
Specifically, Web.config is a file that stores basic website configuration settings. We can see the following code after we click on the Web.config file:
<?xml version="1.0"?><!-- For more information on how to configure your ASP.NET application, please visit https://go.microsoft.com/ fwlink/?LinkId=169433 --><configuration> <system.web> <compilation debug="true" targetFramework="4.5.2" /> <httpRuntime targetFramework="4.5.2" /> </system.web></configuration>
In the next stage, you need to add a document that can be shown in a browser. To accomplish this, do the following:
Right-click on the name of the website and select
Add
.
Select
Web Form
, and leave the name as
Default
.
This will generate a very simple template. You can close
Solutions Explorer
so that it's out of the way, if you wish.
The code across the top of the screen is highly specific to Microsoft. You wouldn't see this, for example, in HTML pages generated by hand or otherwise, unless you were working with a Microsoft product.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
The following code shows an HTML document. Essentially, HTML gives structure to web pages. Visual Studio is a very powerful system:
Note the following on the screen:
The HTML code within the screen is collapsible.
Select the text you want to treat as a collapsible region.
When collapsed, you'll see an ellipsis (
...
) between two
<html>
tags.
If you hover your mouse over the ellipsis, you'll see that the code which has been collapsed appears in a preview box.
If you click on the left-hand side to expand the <html> tag, you have the <head> section. This is where you can store additional information, for example, the <title> tags of a web page. I entered Our First page as the title. The title is what is visible when a page is launched on the tab of a browser, for example, Microsoft Edge and Google Chrome:
After that, you have the <body> tag. Within the body, again you have a <form> tag. The <form> tags are useful for submitting information to web servers for processing. Within the form, you have a <div> tag, or logical division of a page:
<body> <form id="form1" runat="server"> <div> </div> </form></body>
These elements are individually collapsible; so there is a logical structure to the document. Note the <html> opening and closing tags. It's good to have structured things; so you insert them as pairs—one opening and one closing.
Note where the code says runat. This is what's known as an attribute, which is a property that something possesses. In this case, the <form> tag has the runat attribute and it is called server. This means that the form can be dynamic—it can submit information, process it, and return it processed with some output when returned. We will discuss this in greater detail as you progress throughout the book.
<form id="form1" runat="server">
Now we'll launch this HTML code using the following steps:
Begin by putting some text within the
<div>
tags. Enter
Our First Web Page
.
Next, click on the drop-down menu of the run button, select whichever browser you are using, and launch the code in that browser:
After a few seconds,
Our First Web Page
appears, as shown in the following screenshot:
In Microsoft Edge, for example, there are many different ways that you can view this information. You can very simply turn on Pretty Print, Ctrl+Shift+P, and now it is nicely formatted.
For our purposes, what you need to know is that the code you type and the code that ends up on the browser side are a little different. The code on the browser side is somewhat enhanced behind the scenes automatically—you don't really have to worry about it at all. However, you should be aware of what's going on.
To unload or close the document, click on Stop Debugging in the toolbar, or press Shift + F5.
In this chapter, you learned how to create a very simple HTML document and how to run it in a browser. With this knowledge in place, you can now go on to learn how to connect it in C#.
In this chapter, we will improve our HTML page by adding C# code. You will use the template that you set up in the previous chapter.
To continue the development of your first C# program, do the following:
If you wish, you can place something like
Our First C# Page
between the
<title>
tags.
Make sure that the
Solution Explorer
window is displayed. If it isn't shown, go to
View
|
Solution Explorer
. (
Ctrl
+
Alt
+
L
is the key combination, if you prefer using those.)
In
Solution Explorer
, expand the node that says
Default.aspx
.
Open
Default.aspx.cs
, as shown in the following screenshot. This is where you place your C# code:
Notice that by default, at this stage, the code gets grayed out, as shown in the following screenshot. This means that you can remove it. You can just delete it—it's not necessary for our purposes:
Before we talk more about C#, let's go back to Default.aspx and switch to the Design view, as shown in the following screenshot:
Now we'll add one visual item to the page—a label for displaying text in web pages. To do this, follow these steps:
In the menu bar, click on
View
and then on
Toolbox
(
Ctrl
+
Alt
+
X
).
In the
Search
box at the top left-hand side, type
Label
.
Once it finds
Label
, click on it and drag it inside the
<div>
tag , as shown in the following screenshot. You can then close the toolbox:
In the next stage, switch back to the Source view. Here, you will see the code or markup generated for that item:
Keep in mind that this is specific to Microsoft, but you can still recognize it. You basically have an ID and Label1 attribute, which is an attribute. This is how you refer to the item in your C# code. You can change it to something more meaningful, say sampLabel, for sample label.
Here, runat="server" means that the content that the label displays can be generated automatically and dynamically, for example, over the course of your connection to a web page or server.
The Text control is what you see. Thus, if you remove the word Label and then switch back to the Design view, it will just say sampLabel, which is the ID:
<asp:Label ID="
sampLabel
" runat="server" Text="label"></asp:Label>
Now let's go back to Default.aspx.cs and add the following comments under using System. These are notations for yourself—they are not executable code:
//1. using is a keyword, so it's blue//2. System is a name space that stores already created code//3. using System brings in existing code
The benefit of using existing code is that you'll have less code to create. Now go down to the next level, and insert the comments, as shown in the following screenshot:
//4. a class is a required container for creating our own code samples
Later, we will create a class. For now, because of the design of C#, it has to be there as a scaffolding into which you place your own code.
At the next stage, also as shown in the above screenshot, enter the following comments above the block of code that begins with protected void Page_Load:
//5. Code below is where we place our own code //6. Page_Load is code that runs when a page loads from a server
That's a lot of preliminary work! Now let's take a look at the action. The following screenshot shows the code when opened in Microsoft Edge:
The code produces Hello, World! on the page. Thus, we have generated some very basic C# powered content. You can enlarge the type to your liking by clicking the ellipsis (...) in the upper-right corner of the screen and selecting Zoom. Also note that the screen is entitled Our First Page in the upper-left corner.
One thing to observe at the top left-hand side of Figure 2.2.10 is a localhost identifier, which is your local computer. The number is the logical software port 57719. Where it says Default.aspx, Default is the name of a page and .aspx is the extension on the page.
To close, click on the brown square button in the toolbar to stop debugging. Close the window. The code is shown in the following screenshot:
In this chapter, you learned some of the basics of running a simple web page powered by C#. In the next chapter, we'll talk about variables.
In this chapter, you will learn about variables. We will begin with a simple project already in place to save time.
Remember from the previous chapter that there's a Label control involved; be sure that you have that up. Start by doing the following:
Switch to the
Design
view, by clicking the button in the lower-left corner. Your screen should look like the one shown in the following screenshot:
In the next stage, go back to the Source view.
Name it
sampLabel
as before.
Go into
Default.aspx.cs
on the right-hand side, as shown in the following screenshot:
The code that we are going to create will be very basic and deal with variables. The first question is, ultimately, why introduce a variable in the first place? This is an important aspect. It is usually based on an observation that something is changing.
Imagine something as simple as this. You see a group of people, and you observe that their height varies from person to person. Clearly, height is a variable quantity; that is, it's changing. Within the group of people, the height changes.
So, let's start by adding this comment to our code:
//7. You see a group of people and the height changes
In code like C#, for example, we introduce a variable to represent this change. C# is strongly typed, which means that every single variable has a definite data type.
Imagine a variable in a simplified sense as a little box. If a box is designed to hold numerical values, you cannot put a non-numerical value into that box—you cannot put a word into a box that is designed to hold numbers. It doesn't work.
The line we just added declares and sets up a variable based on an observation of something in the world. Hover your mouse over this line, and it says Double. This is an absolutely important thing to understand. The data type on both sides match, as shown in the following screenshot. If you don't have harmony between the two, many times this leads to errors, especially when you're learning for the first time—it's really crucial.
Now I will add the following simple comment. This is the language that you would use to describe that line. Note that it is a statement: it ends with a semicolon, so it completes a definite action—the declaration and setting of a variable.
//8. Declares and sets a variable value
To display this, as usual, type sampLabel, dot (.), and Text. Then assign it to be displayed. This means putting in an equal sign and building up a string on the right-hand side between the quotes. For example, type John's height is, and to add his height, type the plus sign (+) and then the height variable.
Hover your mouse over the plus sign (+). It's an operator—it operates on things. Specifically, string left refers to John's height is and object right refers to the quantity on the right-hand side, that is, the height variable, as shown in the following screenshot:
After it runs, it generates another string. The first word, string, indicates that when you add two strings, a string and an object in this particular case, the object that you get back is another string. This means that John's height is + height; is a string; Text also stores strings, so the two data types are matched.
As you can see in the following screenshot, the popup starts with a string. If you don't have the two data types matched, many times this results in errors when you're learning for the first time:
Now let's run the code. Crank it up in Google Chrome, for example, and you'll see the image shown in the following screenshot:
If you right-click and select View page source, the only thing that's been generated is the highlighted text shown in Figure 2.3.7. The label has been converted into basic HTML behind the scenes. All of the other stuff has been added by default—don't worry about it. It has to be present because of the way this stuff has been designed by the people who created ASP.NET:
Now you understand why a variable should be introduced and how to display its value. Of course, when you look at another person, they are normally of a different height. Thus, we will enter height and assign a new value, for example, 55.5, and close with a semicolon to complete the statement, as shown here:
height=55.5;
Next, we will add a comment as follows:
height=55.5; //9. Assigns a new value usually based on some observation
To display this updated value, enter the following:
sampleLabel.Text+=
Look very carefully at what happens when we run this code using Google Chrome, as shown in Figure 2.3.8. It's almost where we want it to be, except that John's height and Mary's height need to be separated into two lines:
To fix this, you can embed a line break. To do this, you enter the <br> tag right in front of Mary's. When you run the code now, you will observe the screen shown in the following screenshot:
Now we have the output that we want. First John's height and then Mary's height on separate lines. The values shown are coming from C#. The fact that Mary's height is on its own line is because we embedded the <br> tag into the string, so it produces a new line in HTML.
In this chapter, you learned the basics of introducing and using variables. In the next chapter, we'll work with a new feature called string interpolation, which allows embedding variable names directly into strings. This makes coding much more streamlined.
In this chapter, we'll use a new feature that was introduced in C# 6.0 called string interpolation. This feature allows embedding variable names directly into strings, which makes coding much more streamlined.
The latest version of Visual Studio has the string interpolation feature built into it. You will only need to follow the first instructions here if you have an older version of Visual Studio, or if you are having problems with string interpolation. If you are using the latest version of Visual Studio, then you can jump to the "Printing a variable" heading to see string interpolation in action.
Open our project, right-click on the name of the website in Solution Explorer, and then select Manage NuGet Packages..., as shown in the following screenshot:
Next, click on Browse in the NuGet Package Manager screen that appears. Packages that you can add to Visual Studio to extend its features are shown in the window on the left-hand side. Enter codeDom in the Search box at the upper-left corner and press Enter:
From the items that appear, select the following and install it into your project by clicking on the Install
