Beginning C# 7 Hands-On – The Core Language - Tom Owsiak - E-Book

Beginning C# 7 Hands-On – The Core Language E-Book

Tom Owsiak

0,0
37,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

A C# 7 beginners guide to the core parts of the C# language!

About This Book



  • Learn C#, Visual Studio, and Object Oriented Programming,
  • See practical examples of all the core C# language features so that you can easily master them yourself
  • Use the C# 7 programming language to work with code and data, which can be applied to other programming languages as well,
  • Complete a variety of programming assignments for hands-on practice, as you move through the course.

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



  • Learn C#, Visual Studio, and object-oriented programming
  • Learn all the core C# 7 language syntax with hands-on working examples
  • Learn everything from basic variable assignments to complex multidimensional arrays
  • Go through practical examples of all the core C# 7 language features so that you can easily master them yourself
  • Use the C# programming language to work with code and data, which can be applied to other programming languages as well

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:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 490

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Beginning C# Hands-On – The Core Language

 

 

 

 

 

 

 

 

 

 

Learn the C# language by coding it element by element

 

 

 

 

 

 

 

 

 

 

Tom Owsiak

 

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Beginning C# Hands-On – The Core Language

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

 

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

 

ISBN 978-1-78829-654-0

 

www.packtpub.com

Credits

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

About the Author

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.

www.PacktPub.com

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.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

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!

Preface

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.

What you need for this book

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.

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.

Conventions

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."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Reader feedback

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.

Customer support

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.

Downloading the example code

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!

Downloading the color images of this book

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.

Errata

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

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.

Questions

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.

Why C# and How to Download and Install the Visual Studio Community Edition

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:

Figure 1.1.1: The many job listings for C# programmers

Locating and downloading the Visual Studio Community edition

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:

Figure 2.1: Installing Visual Studio 2017

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:

Figure 2.2: The License screen

Click on Continue, which should take you through to the next screen:

Figure 2.3: Choosing download components

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:

Figure 2.4: Selecting .NET desktop development

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:

Figure 2.5: Selecting the following frameworks

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:

Figure 2.6: Installation in progress

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:

Figure 2.7: The Welcome screen

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:

Figure 2.8: The Sign in screen

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:

Figure 2.9: Choose color theme

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:

Figure 2.10: Getting Started

 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.

Summary

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.

Customizing Visual Studio to Make it Feel More Personal

In this chapter, we will configure the appearance of Visual Studio a little further.

Customizing Visual Studio

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:

Figure 1.2.1: Searching for font settings options

Selecting the text editor font and size

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:

Figure 1.2.2: Selecting the text editor font and size

Selecting the Statement Completion font and size

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:

Figure 1.2.3: Selecting the Statement Completion font and size

Selecting the Environment font and size

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:

Figure 1.2.4: Selecting the Environment font and size

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.

Positioning Visual Studio panels

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.

Figure 1.2.5: Positioning the Solutions Explorer window

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:

Figure 1.2.6: Positioning the Start Page panel

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:

Figure 1.2.7: Click on the pin at the top right-hand side of the Solutions Explorer window to enable Auto Hide

Summary

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.

Creating and Running Your First Page

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.

Starting a new project in Visual C#

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:

Figure 2.1.1: Be sure to select Visual C# as the language, not Visual Basic

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.

Working with Solutions Explorer

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>

Adding a document to your browser

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.

Working with HTML code in Visual Studio

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:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title></head><body> <form id="form1" runat="server"> <asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged"></asp:TextBox><br /> <asp:Label ID="Label1" runat="server" ></asp:Label> </form></body></html>

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.

Figure 2.1.2: Preview code with the mouse hover

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:

Figure 2.1.3: The tab of a browser

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">

Launching the HTML code

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: 

Figure 2.1.4: Select a browser

After a few seconds,

Our First Web Page

appears, as shown in the following screenshot:

Figure 2.1.5: Source code generated and sent to the browser
In Microsoft Edge, when you click the ellipsis at the top right-hand side of the screen and click on Zoom on the drop-down menu, it will zoom in and the text will appear larger. If you want to see what has actually been generated and sent to the browser, right-click and select View Source. As you can see in Figure 2.3.5, much has been generated.

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.

Summary

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#.

Creating and Running a Page That Incorporates 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.

Improving your first program

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

Figure 2.2.1: Default.aspx.cs in Solution Explorer

Open

Default.aspx.cs

, as shown in the following screenshot. This is where you place your C# code:

Figure 2.4.2: Default.aspx.cs is where you place 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:

Figure 2.2.3: Select and delete the grayed-out code

Working in the Design view

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:

Figure 2.2.4: Change to the Design view

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:

Figure 2.2.5: Use Toolbox to search for a visual element

Working in the Source view

In the next stage, switch back to the Source view. Here, you will see the code or markup generated for that item:

Figure 2.2.6: The code or markup generated for an item is selected here

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>

Adding comments

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:

Figure 2.2.7: Adding comments to your code

//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

Viewing the code in your browser

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:

Figure 2.2.10: Your code 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:

Figure 2.2.11: Click on the brown button in the toolbar to stop debugging

Summary

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.

Creating and Using a Single Variable

In this chapter, you will learn about variables. We will begin with a simple project already in place to save time.

Setting up Visual C# to deal with a variable

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:

Figure 2.3.1: Visual C# Design view
If you are missing Toolbox, remember to click on View and then on Toolbox (press Ctrl+Alt+X if you prefer to use key combinations), and then drag and drop Label into the Design view.

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:

Figure 2.3.2: Our Default.aspx.cs view

Variables represent change

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.

Matching variable types

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.

Figure 2.3.3: The data type on both sides must match

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.

Understand that here + does not mean add two numbers; it means combine two strings.

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:

Figure 2.3.4: String left refers to "John's height is " and object right refers to the quantity on the right side—the height variable

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:

Figure 2.3.5: The two data types must match, or else errors will be the result

Running the code

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:

Figure 2.3.6: Your code opened in Google Chrome

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:

Figure 2.3.7: The generated text is highlighted, and the label is converted into basic HTML

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+=

Running the code with the appended 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:

Figure 2.3.8: John's and Mary's heights need to be separated into two lines

Embedding a line break

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:

Figure 2.3.9: A line break <br> has been inserted to separate the text into two lines

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.

Summary

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.

String Interpolation and Updating Visual Studio

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.

Selecting a NuGet package

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:

Figure 2.4.1: Selecting Manage NuGet Packages

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:

Figure 2.4.2: The CodeDom package

Installing a NuGet package

From the items that appear, select the following and install it into your project by clicking on the Install