Thursday, January 22, 2015


Skip navigation
lynda.com

    Give a gift
    Hi, Celia

    Browse the library

    My courses

All courses »
Open Source »
C# »
C# Essential Training
C# Essential Training
Don Barnett
C# Essential Training
with David Gassner


add to playlist
bookmark
feedback

C# is an object-oriented language designed by Microsoft and used by systems engineers, desktop programmers, and mobile app developers the world over. In these tutorials, David Gassner takes you through C#'s history, its core syntax, and the fundamentals of writing strong C# code. After explaining C#'s relationship to .NET and Windows, David shows how to install Visual Studio, a great IDE for developing in C#, and then dives into the language itself. Along the way, he covers topics such as:

    Declaring and initializing variables with a variety of data types
    Exploring operators, expressions, constants, and enumerations
    Controlling flow with conditional code and loops
    Handling exceptions
    Managing data collections
    Creating custom classes
    Organizing classes by namespace
    Understanding inheritance

Whether you're choosing C# as your first step into programming or adding it your existing skillset, these training videos will help you understand the language and use it to build your own great software.

show more

author
    David Gassner
subject
    Developer, Programming Languages
software
    C#
level
    Intermediate

duration
    5h 2m
released
    Dec 18, 2014


Share this course
Upgrade your account

Other members also watched
Foundations of Programming: Fundamentals

Foundations of Programming: Object-Oriented Design

Up and Running with C#

JavaScript Essential Training

Java Essential Training

show more

    table of contents
    exercise files
    transcript
    author
    FAQs

Search the closed captioning text for this course by entering the keyword you’d like to search, or browse the closed captioning text by selecting the chapter name below and choosing the video title you’d like to review.
submit


expand all | collapse all
Introduction
Welcome
00:04    - Hi, my name is David Gassner,
00:06    and this is C Sharp Essential Training.
00:10    Microsoft Development Frameworks support many languages.
00:13    And C Sharp is among the most popular of them.
00:17    It's used to build everything from Desktop
00:19    to web to mobile applications.
00:22    I'll begin this course by showing you
00:24    how to install Visual Studio.
00:26    The essential Integrated Development Environment
00:29    or IDE for Microsoft programmers.
00:33    After a discussion of the relationship between C Sharp,
00:36    the .NET framework, and the Windows runtime,
00:39    I'll dive into the language itself.
00:42    I'll describe basic syntax
00:44    and then show you how to declare
00:45    and initialize variables using a variety of data types.
00:50    I'll show you how to control flow
00:52    in C Sharp using conditional code
00:55    and different kinds of looping statements.
00:58    And I'll describe different ways
00:59    of managing collections of data.
01:02    Then I'll move on to more advanced topics.
01:05    Including how to create your own custom classes
01:07    and how to organize them with name spaces.
01:12    Regardless of what kind of software you want to build,
01:14    I hope this course helps you get started with C Sharp.
Collapse this transcript
What you should know before watching this course
00:00    - This course, C# Essential Training,
00:03    is designed for programmers who want to get started
00:06    programming with C# to build applications
00:09    for the desktop, for the web, and for mobile devices.
00:14    The course is designed,
00:15    assuming that you understand
00:16    basic programming vocabulary already.
00:20    If you could answer these two simple questions,
00:22    you should be able to follow along with this course.
00:25    What is a variable and what is a function?
00:30    It's useful to know at least one other programming language,
00:33    but it doesn't necessarily have to be a C-based language
00:37    like C or C++.
00:40    If you're brand new to programming,
00:42    you might want to watch this course first,
00:45    Foundations of Programming: Fundamentals.
00:48    In this course, you'll learn about this basic vocabulary,
00:52    learning what statements are, how statements
00:54    are wrapped together and placed into functions,
00:57    and how variables are used to store data in memory.
01:02    Also, C# is an object oriented language,
01:05    and you'll need to understand the basics of OOP vocabulary,
01:09    and the course,
01:10    Foundations of Programming: Object Oriented Design,
01:13    can help you get started with that.
01:17    In this course, I'll be using
01:19    Visual Studio 2013 Professional,
01:22    and it's a product that has a lot of features to it.
01:26    I'll only be using a slender slice of its capabilities,
01:30    but Visual Studio is the standard
01:32    integrated development environment for C#,
01:34    and Visual Studio 2013
01:37    was the most recent version
01:39    as of the time of this recording.
01:41    If you want to follow along with the exercises,
01:44    any of the paid editions will work fine,
01:47    such as Visual Studio Professional,
01:49    or Visual Studio Ultimate, but there are also free editions
01:53    of Visual Studio available,
01:56    and you can use these
01:57    to follow along with the exercise files as well.
02:00    The Visual Studio Express products are totally free
02:04    and you can download them
02:05    and get started very quickly with them.
02:08    Most of the exercises in this course are built as Console
02:12    or Windows Presentation Foundation applications.
02:16    These are known as Desktop applications,
02:19    and to work with those exercises,
02:22    you can use the free edition,
02:23    Visual Studio Express for Windows Desktop.
02:27    There's also a couple of introductions
02:29    to other environments.
02:31    For example, if you want a free product
02:33    to work with ASP.net, get Visual Studio Express for Web,
02:38    and if you want to build Windows Store apps,
02:41    formally known as, Metro Apps,
02:43    you can use the free edition,
02:45    Visual Studio Express for Windows.
02:49    To learn more about Visual Studio,
02:51    you can watch these courses in the Lynda.com library.
02:55    For a general introduction to Visual Studio,
02:58    watch Visual Studio 2012 Essential Training.
03:02    If you want to get into web development,
03:05    you can watch Visual Studio 2013 for Web Developers.
03:10    All these Lynda.com courses can help you get started
03:13    with all the other things you'll want to know
03:16    in addition to learning about the C# programming language.
Collapse this transcript
Using the exercise files
00:00    This course is accompanied by exercise files
00:03    that you can use to follow along
00:05    with the demonstrations on screen.
00:08    I've copied the exercise files to my Windows desktop,
00:11    but you can place them anywhere on your hard disk.
00:14    The exercise files are organized by chapter.
00:17    Within each chapter,
00:19    you'll find folders for each of the exercises.
00:24    Each of these folders is a Visual Studio Solution.
00:28    Within the Solution folder,
00:30    you'll find a Solution file and a subfolder,
00:33    which is the project for that exercise.
00:36    To open the Solution in Visual Studio,
00:39    just double-click the Solution file.
00:44    You can open any of the exercise files
00:46    with one of the paid-for license
00:47    versions of Visual Studio.
00:49    I'm using Visual Studio 2013 Professional,
00:53    but you can open up all of those
00:55    exercise files with the free edition,
00:58    Visual Studio Express for Windows Desktop.
01:02    There's one exercise that uses ASP.NET,
01:05    and you can open that one with
01:07    Visual Studio Express for web.
01:10    And if you want to build Windows store apps,
01:12    you'll need the free edition,
01:14    Visual Studio Express for Windows.
01:17    In addition to the starting exercise files,
01:20    the exercise files folder has a Solutions folder,
01:24    and here you'll find the finished versions
01:26    of each of the exercises.
01:29    You can choose to start with the Starting folder,
01:32    and follow along with all the coding,
01:34    or you can go directly to the Solutions version
01:37    and just review the finished code.
01:40    Either way, these exercise files
01:43    are available so that you can easily
01:45    follow along with all the exercises
01:47    as I do them on the screen.
Collapse this transcript
1. What Is C#?
The history of C#
00:00    - C# was originally introduced in 2002 by Microsoft
00:05    as part of the initial release of the .NET framework.
00:09    C# is a C-style language.
00:12    That means that it shares syntax
00:13    with C and its other derived languages,
00:16    such as C++, Java, JavaScript, and even PHP.
00:22    C# is most directly derived from Java.
00:26    It barrows most of Java'a syntax,
00:29    but has some significant differences
00:31    in its key words, its data types,
00:33    and in many other nuances.
00:36    It also barrows many features from C++.
00:40    Here are some of the most important characteristics
00:42    that define the language.
00:45    C# is a strongly typed language.
00:49    That means that each value
00:51    represented by a variable, a field, or a property
00:54    is of a specific data type.
00:57    When you declare a variable,
00:58    you also declare its type
01:00    either through an explicit type declaration
01:03    or by something called implicit declaration.
01:07    And once a variable has been declared,
01:09    its type can't change.
01:13    C# is an object oriented language.
01:16    Everything is an object,
01:17    including simple types like numbers
01:19    and logical or bullion values.
01:24    C# is designed to support multiple programming styles,
01:27    including imperative, declarative,
01:29    functional, and generic programming.
01:33    In addition to C#, you can program for
01:36    .NET in Visual Basic, also known as Visual Basic .NET,
01:40    JavaScript, and many other languages.
01:45    The .NET framework is at the core
01:47    of such programming environments as
01:49    ASP.NET, Windows Forms,
01:51    and Windows Presentation foundation for the desktop,
01:54    and other Microsoft programming architectures.
01:58    You can also use C# with Windows Runtime or WinRT,
02:02    a newer framework that was introduced
02:04    with Windows 8 as the platform for Windows Store Apps.
02:09    With Windows 8 and WinRT,
02:11    you can program in C#,
02:13    Visual Basic, C++, and JavaScript.
02:17    WinRT supports x86 and ARM architectures.
02:21    So, these apps work with the two
02:23    different flavors of Windows,
02:25    Windows itself and WindowsRT.
02:29    And then there's the Windows phone operating system,
02:31    which as of the time of this recording,
02:33    uses a version of WinRT,
02:35    called the Windows Phone Runtime.
02:37    Like WinRT, you can program for Windows Phone
02:41    with C# and Visual Basic.
02:45    Here are the different versions of C#
02:47    that have been introduced over the years.
02:50    The original release was in 2002.
02:53    Then, four years later in 2006,
02:55    C# 2.0 introduced many programming architectures
03:00    that we take for granted today,
03:02    including generic declarations,
03:04    anonymous methods, decorator interfaces, and much more.
03:10    Each subsequent release of C#
03:12    has added to the language's capabilities,
03:15    including the most recent, C# 5.0,
03:19    released with Windows 8, simplifies the task
03:22    of Asynchronous programming
03:24    with very simple programming models.
03:28    And a new version of C# is on its way.
03:31    It's referred to sometimes as C# vNext,
03:35    but we now know this will be C# 6.0.
03:39    It was announced in May 2014
03:42    and it includes many new programming language features.
03:45    By the time you watch this course,
03:47    C# 6.0 might already be released
03:51    and Visual Studio will be there to support it.
Collapse this transcript
C#, the .NET Framework, and Windows Runtime
00:00    - The .NET Framework provides a universal platform
00:03    that lets Microsoft developers program in the same way
00:06    and with the same languages,
00:08    regardless of whether they're working for the web,
00:11    or desktop, or for mobile.
00:13    It includes an extensive class library
00:16    known as the Framework Class Library, or FCL
00:20    that provides core capabilities,
00:22    such as user interface management,
00:25    data access, security and cryptography, and more.
00:30    There are also class libraries available
00:32    for particular types of applications.
00:34    So, for example, if you're working on web-based applications
00:38    you'll find that there are libraries
00:40    for working over the Internet using sockets
00:42    and other communication standards.
00:46    C# runs in a managed code environment.
00:49    C# doesn't compile to machine code.
00:52    It compiles instead to something called bytecode.
00:55    A format that can be interpreted and executed
00:58    on multiple operation systems.
01:01    While the .NET Framework is built for Windows,
01:03    there have been a number of efforts to create environments
01:06    for C# that can be executed on other operating systems.
01:11    The bytecode is executed by a layer called
01:14    the Common Language Runtime, or CLR.
01:18    The CLR is a virtual machine,
01:21    similar to the Java virtual machine or JVM,
01:24    in the wold of Java.
01:26    It provides machine level security, memory management,
01:30    operating system level security, and much more.
01:36    Here's what the .NET Framework stack looks like.
01:39    We'll start with the operating system itself.
01:42    Normally, this is just plain old Windows,
01:45    and on top of that you have the CLR,
01:48    and then the Framework Class Library.
01:51    Then add the libraries that are unique
01:53    to each application framework, such as ASP.NET or WPF,
01:58    and then the Common Language Specification,
02:01    which is the interface to the programming languages.
02:05    And, finally, the languages themselves including C#,
02:09    C++, Visual Basic, JavaScript, and F#,
02:14    a functional language.
02:17    Available application frameworks include ASP.NET
02:21    for dynamic web-based applications.
02:24    Windows Presentation Foundation, or WPF.
02:27    Or, the older Windows Forms framework,
02:30    and there are other frameworks, such as Windows Phone,
02:34    Windows Communication Foundation, Silverlight,
02:37    and XNA Game Studio.
02:40    All of these frameworks support C#,
02:43    and you can also build Windows Store apps for Windows 8.
02:47    These are apps that run in full screen on Windows 8.
02:51    Even those these use Windows Runtime instead of .NET,
02:54    the style of programming with C#
02:56    on Windows 8 barely changes.
02:59    That's because WinRT is exposed to the .NET APIs
03:04    through an architecture called Projection.
03:07    So, even though WinRT is a native platform,
03:10    your C# code is still being written
03:12    for a managed environment.
03:15    Window Store apps run in a security sandbox;
03:18    similar in fashion to apps on a mobile device.
03:22    Window Store apps are at the core
03:24    of the Windows 8 architecture,
03:26    and in a recent tech preview of Windows 10,
03:29    they remain a valuable part of the Windows environment.
03:33    As a C# developer,
03:34    you'll be able to program Windows Store apps
03:37    along with all the other types of software
03:39    that I've described.
Collapse this transcript
Memory management and garbage collection
00:00    - Most programming languages can be categorized
00:03    as either native or managed languages.
00:07    A native programming language
00:09    is compiled to machine code.
00:12    This is code that's unique to a particular
00:14    operating system and can only be executed
00:17    in the environment for which it was compiled.
00:20    As a result, when you're dealing with
00:23    a native language you have to have
00:25    a different compiler for each operating system.
00:28    You'll have one compiler application for Windows,
00:31    another one for Mac, another one
00:33    for a distinct flavor of Linux, and so on.
00:37    Some of the most popular programming languages
00:39    are native languages.
00:41    This includes many of the C style languages,
00:43    C, C++, and Objective-C,
00:47    and also other languages such as Pascal.
00:51    In contrast, managed languages are compiled
00:54    to an intermediate format that
00:56    works across operating systems.
00:59    Typically, these languages are
01:01    compatible across operating systems,
01:04    and include languages such as C# and Java.
01:10    C# is a managed language.
01:13    When you create C# code and then compile it,
01:17    you're compiling to a format know as bytecode.
01:20    It's not machine language and
01:22    it's not unique to a particular operating system.
01:25    And then that bytecode is executed at Runtime
01:28    by the Common Language Runtime,
01:30    or CLR, that's a part of the .NET Framework.
01:35    In theory, that same bytecode can be executed
01:38    by a Runtime on another operating system
01:41    without having to be recompiled.
01:43    In practice, C# is mostly used
01:47    in the Windows environment,
01:49    but third parties have created compilers
01:51    that work on other operating systems.
01:56    One of the great advantages
01:57    of a managed language is that you don't
01:59    have to worry about specifically allocating
02:02    and deallocating memory.
02:05    In C, programmers are explicitly responsible
02:09    for figuring out how much memory
02:11    is going to be used by an object,
02:12    and then providing it and then reclaiming it
02:15    when it's no longer needed.
02:17    Other advanced languages use an
02:19    architecture known as "reference counting",
02:22    where when you create a variable
02:24    and point it at an object,
02:26    a count is maintained.
02:28    And when there are no variables still
02:29    pointing at an object, that memory
02:32    can be explicitly released.
02:34    But it happens at that moment.
02:37    In a managed language there's a common
02:40    architecture known as "garbage collection".
02:43    In these languages, including C#,
02:46    you as the programmer don't have to
02:48    explicitly allocate memory, and you don't have
02:51    to worry about when memory will be reclaimed.
02:54    It'll be done for you in the background
02:56    by the garbage collector process.
03:00    This process periodically checks memory.
03:04    Referenced objects are stored in memory heap.
03:08    Whenever that area of memory starts getting
03:10    filled up, the amount of memory available
03:13    in the heap will vary widely,
03:15    depending on the nature of the application
03:17    and more importantly the kind of hardware
03:20    that the application is running on.
03:23    So periodically the CLR checks the heap,
03:26    and finds out whether it's about
03:28    to run out of memory.
03:30    And if it does, garbage collection kicks in.
03:34    The CLR looks for unreferenced objects.
03:38    Objects that don't have any variables
03:40    pointing to them anymore and releases
03:42    resources such as memory.
03:45    That memory can then be reused for new objects.
03:49    So this constant cycle is going
03:50    on in an application.
03:53    Create more objects, release the references,
03:56    the garbage collector reclaims the memory,
03:59    and then the cycle starts again.
04:01    And again, the process is known
04:03    as garbage collection.
04:05    Java developers are very familiar
04:07    with this process.
04:09    It works pretty much the same
04:10    in the JVM, the Java Virtual Machine,
04:13    as it does in the CLR.
04:17    Here is the lifetime of an object,
04:19    and how it works with garbage collection.
04:23    Let's say you declared a variable,
04:25    but you didn't provide it with a reference object.
04:28    At this point, no memory in the heap has been used.
04:32    We've created a pointer,
04:34    but it's not pointing to anything.
04:37    Next, let's say that you instantiate an object
04:40    and point it at the variable.
04:43    Now there's an object in memory,
04:45    and it's referenced by the variable.
04:48    This object is not eligible for garbage collection.
04:53    But then let's say you executed this line
04:55    of code, setting the object to null.
04:58    That doesn't immediately destroy
05:00    the object in memory, but it does dereference it.
05:04    And so now that object is eligible
05:07    for garbage collection.
05:08    The garbage collector can find all such objects,
05:12    release their memory, and make that memory
05:14    available for future use.
05:17    So that's how garbage collection works
05:19    in the .NET framework.
05:21    But what about if you're building
05:22    a Window's store app?
05:24    These applications run on Window's Runtime,
05:27    or WinRT, which is a native environment,
05:30    not a managed environment.
05:32    But, the .NET Framework is integrated
05:35    as a sub-platform of WinRT.
05:39    When you program in C# for WinRT,
05:43    your WinRT objects are managed by
05:45    reference counting, not by a garbage collector.
05:49    But many of the WinRT objects you might create,
05:52    are really just thin wrappers,
05:54    or what are known as projections
05:56    to .NET Framework objects.
05:59    The WinRT objects might not be
06:01    taking much memory at all.
06:03    The real work might be done in the
06:04    background by the .NET Framework,
06:07    but all you need to know as the programmer
06:09    is that memory management is still automatic.
06:13    Your .NET objects, which are referenced by
06:16    the WinRT objects, are still
06:19    subject to garbage collection.
06:21    If you're building Window's store apps with C#,
06:24    you still don't have to manage memory directly.
06:27    But this tells you that understanding
06:30    what's going on under the covers
06:32    with your C# applications can be very useful.
06:36    Especially as applications grow
06:37    in size and complexity.
06:40    Understanding how objects are managed
06:42    in a C# based application can help
06:45    you build very memory efficient applications.
Collapse this transcript
2. Getting Started
Installing Visual Studio
00:00    - To follow along with the exercises in this course
00:03    you'll need a copy of Visual Studio.
00:06    I'm using Visual Studio 2013 Professional,
00:09    but you can also use the free Express editions.
00:13    You can find downloads of Visual Studio at this website,
00:17    visualstudio.com.
00:19    As of the time of this recording, the most recent version
00:22    was Visual Studio 2013, Update 3.
00:26    Click the download link,
00:28    and here you'll be able to choose
00:29    the version of Visual Studio you want.
00:32    You can either use one of the fee for license versions,
00:35    or if you want the free Express version,
00:38    click the Express link and then choose
00:41    Visual Studio Express 2013 for Windows Desktop.
00:46    This free edition will let you build
00:48    desktop applications using the Windows form,
00:52    Windows presentation foundation,
00:54    or console architectures.
00:56    If you also want to build Windows store apps,
00:59    you could also download the version for Windows.
01:02    This will let you build Windows store or
01:05    modern apps that run full screen on Windows 8,
01:09    and run in a security sandbox.
01:11    In this course I only have one exercise
01:14    that you would need that version for.
01:17    So I'm going to primarily focus here
01:19    on the version for Windows Desktop.
01:22    Follow through the prompts to install Visual Studio.
01:25    You'll start with this dialog box.
01:28    You'll need to agree to the license terms
01:30    and privacy policy,
01:32    and choose whether to join the
01:34    Visual Studio experience improvement program.
01:37    Then, click the install button.
01:40    And if prompted with the user account control
01:43    dialog, click yes.
01:45    It'll take a few minutes to download
01:47    and install Visual Studio,
01:49    but you'll see that it's a very simple installation.
01:53    Once Visual Studio Express is installed,
01:55    you can go to your Start Menu,
01:58    or on Windows 8, your Start Screen,
02:00    and look for the application starting with VS,
02:04    for Visual Studio.
02:06    The first time you start it up
02:07    you'll see a few prompts appear.
02:09    But then you'll be ready to start
02:11    building applications using the
02:13    C# programming language.
Collapse this transcript
Creating a console application
00:00    - The first step to learning any programming language,
00:03    is to learn how to say, "Hello World."
00:05    With C#, you can say "Hello"
00:07    in a number of different application frameworks.
00:10    I'll start with the simplest sort of application,
00:13    known as a console application.
00:16    I'll begin by opening Visual Studio.
00:19    I'm using Visual Studio Professional 2013,
00:22    but you can also use the free edition,
00:25    Visual Studio Express 2013 for Windows desktop.
00:30    From the menu, select FILE, New, Project...
00:35    Under the templates section,
00:36    open the tree icon for Visual C#.
00:40    Then go to Windows Desktop,
00:43    and from there choose Console Application.
00:46    Browse for your location.
00:49    I'll start at the Desktop, where I placed my exercise files.
00:53    Then I'll drill down to the 02_GettingStarted folder,
00:57    and select the folder.
00:59    And then I'll set the name of my new application as,
01:02    HelloConsole, and I'll click OK,
01:05    to create and open the new project.
01:08    A Visual Studio project,
01:09    is a member of something called a solution.
01:13    So when you create a new project,
01:14    you're creating both the solution, and the project.
01:19    You can add multiple projects to a solution,
01:22    but for these exercises,
01:24    I'll always have one project per solution.
01:27    A console application initially consists
01:30    of a single C# class.
01:33    At line 7, there's the keyword namespace.
01:37    Each class in C# is a member of
01:40    something called a namespace.
01:42    I'll talk about what a namespace is,
01:44    and how you can use it to organize your code,
01:47    later on in the course.
01:49    Within the namespace, there's the class.
01:51    The default name of a starting class
01:54    in a console application is always Program.
01:58    And that class always has something called the main method.
02:02    Any code you place inside the main method,
02:05    will be executed automatically as the application starts up.
02:09    Those are the rules for console applications.
02:13    The rules are different for ASP.net for the web,
02:16    Winforms or WPF for desktop,
02:19    or other application frameworks.
02:22    To say "Hello World" in a console application,
02:24    place your cursor inside the main method.
02:28    This method, which might be called a function
02:31    in other programming languages,
02:33    will be executed automatically.
02:35    To output some text to the console, type the word Console.
02:40    You'll see that it comes up
02:41    in a list of available identifiers.
02:44    It turns out that Console is the name of a class
02:48    that's a part of the application framework,
02:51    you're working in right now.
02:53    I'll type the beginning of the class name,
02:55    and then press the period key.
02:57    That auto-completes the class name, and puts in the period.
03:01    And now I can refer to anything
03:03    that's a member of the Console class.
03:08    I'll type 'wri', and I'll see that there are
03:11    two items here called Write and WriteLine.
03:16    These are both methods or functions of the console class.
03:21    And they'll output information to the Console.
03:24    The Write method will output just the text
03:26    I add in to it, and WriteLine will append
03:29    a new line at the end of the text.
03:32    I'll choose WriteLine, and I'll put an opening parenthesis.
03:36    And Visual Studio adds the matching closing parenthesis.
03:41    Then I'll type the text I want to output.
03:43    I'll start with a double quote.
03:45    Notice that Visual Studio
03:47    automatically adds the closing double quote.
03:50    And I'll type the text.
03:51    I'm almost done.
03:53    Notice the little squiggly line at the end of the statement.
03:57    That means there's some missing code.
03:59    And if I move the cursor over that,
04:01    I get a little bit of bubble help,
04:03    that tells me a semicolon is expected.
04:07    In C# every statement ends with a semicolon.
04:11    It's like a period in English.
04:14    It means, this is the end of the statement.
04:16    Go ahead ad execute this.
04:18    Now I'll save my changes by pressing CTRL + S.
04:22    And I'm ready to run the application.
04:24    Up on the toolbar, there's a start button.
04:27    Watch what happens if I click it.
04:30    I'll see a command window pop up and then instantly go away.
04:35    I'm running the application in debug mode.
04:38    And in Visual Studio when you do that,
04:40    the application window wont stick around.
04:43    You cant see it.
04:45    So here's how you can fix that.
04:47    And I'll show you a couple of different ways.
04:49    One approach, is to start the application without debugging.
04:53    You can do this by going through the menu,
04:56    selecting DEBUG,Start Without Debugging,
04:59    or you can press the keyboard shortcut, CTRL + F5.
05:03    And watch what happens when
05:05    you run the application this way.
05:07    You run the application, and you get a prompt.
05:10    Press any key to continue.
05:13    So, that will work with any console application.
05:16    But here's a way to build that kind of functionality
05:19    into the application itself.
05:21    I once again use the Console class.
05:24    But this time, I'll call a method named ReadKey.
05:29    Just like the WriteLine method,
05:31    it requires an opening and closing parenthesis.
05:34    I'll talk about that sort of syntax later,
05:37    as something that required when you call methods in C#.
05:40    But the ReadKey method, instead of outputting something,
05:44    looks for input, and specifically it'll keep on
05:48    reading input until the user presses the Enter key.
05:52    So now I'll save my change and run the application again.
05:55    And this time, I'll select start debugging, or press F5.
06:01    And now, I see the output on the screen,
06:03    but the window pauses for input.
06:06    And when I press Enter, the application finishes,
06:09    and the window closes.
06:11    I'll run the application again, this time pressing F5.
06:15    And I'll adjust my fonts.
06:17    I'll click the top-left corner to open the control menu,
06:21    and select Properties.
06:23    Then for the font, I'll choose
06:25    the largest available font and click OK.
06:28    And now I'll be able to see clearly
06:30    the result of my application.
06:33    Once again I'll press Enter, and the application closes,
06:37    and the window goes away.
06:39    You'll see that in many of
06:40    the starting applications in the exercise files,
06:43    I've placed a call to Console.ReadKey
06:46    at the bottom of the application.
06:48    This is only there to make sure that the window stays open
06:51    for the duration of the application.
06:54    It might not do anything functionally in the application,
06:58    and you could accomplish the same thing
07:00    as you're programming and testing,
07:02    by running the application without debugging.
Collapse this transcript
Creating a rich desktop application
00:00    - So far, I've shown how to say "Hello, world!"
00:02    in the simplest sort of application,
00:05    a console application.
00:07    But now, I'll describe how to create an application
00:10    for the Windows desktop
00:12    using Windows Presentation Foundation,
00:14    or WPF.
00:16    If you still have the console application open,
00:19    close it now by selecting File,
00:22    Close Solution.
00:24    Now you're ready to create your next solution.
00:27    I'll select File,
00:29    New, Project again.
00:31    This time, once again I'll make sure
00:33    I'm using Visual C#
00:35    and I'm creating applications for the desktop,
00:38    but I'll choose WPF Application.
00:41    And I'll name this application
00:43    "Hellowpf."
00:45    And I'll place it in the same folder,
00:47    the 02 Getting Started folder,
00:49    and click Okay.
00:51    A Windows Presentation Foundation
00:53    is a little bit more complex.
00:55    It has a visual interface.
00:58    It's meant to run on the desktop.
01:00    And if all you do is create the application
01:03    and then run it,
01:05    this is what you'll see.
01:06    I'll click the Start button,
01:08    and I get a window that pops up
01:10    and stays open until I close it.
01:14    The default title on the window is MainWindow,
01:17    but I have complete control over that.
01:19    I'll close that window,
01:21    and that takes me back to Visual Studio.
01:24    A Windows Presentation Foundation application
01:26    starts with two files
01:28    that have extensions of xaml,
01:31    which is pronounced "zammel."
01:33    And XAML is the mark-up language
01:35    that's used to define the user interface
01:37    for desktop applications written
01:39    with Windows Presentation Foundation,
01:42    but also with SilverLight applications
01:45    and for Windows Store applications built for Windows 8.
01:49    In a WPF application, there's an app.xaml
01:53    and a MainWindow.xaml.
01:56    You'll notice that MainWindow.xaml is already open.
01:59    The XAML file, or the user interface definition,
02:02    has an associated file called the "code-behind" file.
02:07    This XAML file's code-behind
02:10    has a file extension of .cs, for C#.
02:14    The code-behind file can be written in C#,
02:17    Visual Basic, or any other language that's supported
02:21    by the application framework you're using.
02:24    This is where you'll put your logic code
02:26    in a WPF file.
02:28    But I'm actually going to go back to the XAML file
02:32    and start by creating a visual control,
02:35    something that will help me output something to the screen.
02:38    With the Window Design Interface open,
02:42    I'll go over to the left side and find the toolbox.
02:46    If you're working in Visual Studio Professional,
02:48    you'll see a number of tabs over here on the left.
02:51    Toolbox should be one of them.
02:53    If you're working in the Express edition,
02:56    you might see just the Toolbox tab.
02:59    I'll click the Toolbox tab,
03:01    and then I'll click the pin icon.
03:03    That will cause the toolbox to stay on the screen.
03:07    Then I'll resize that panel,
03:10    I'll close this Output panel,
03:12    and then, down here, I'll select Fit All.
03:15    That will expand the design view of this window,
03:18    so I can clearly see what it's going to look like.
03:21    Next, over here on the Toolbox,
03:23    I'll open the common WPF controls,
03:27    and I'm going to choose a control called a TextBlock.
03:30    I'll click, and drag it into place.
03:33    After I've dropped it,
03:35    I'll then click and drag it again
03:37    and place it in the borders that are displayed.
03:40    That places the TextBlock 10 pixels from the top
03:43    and 10 pixels from the left side of the window.
03:46    I'll drop it there,
03:48    and then, with the TextBlock still selected,
03:51    I'll come over here to the Properties window
03:53    in the lower right corner.
03:55    Notice that the Properties panel
03:57    has a set of properties labeled as Common.
03:59    This is where you would set the text value.
04:02    I'll set that to "Hello, world!"
04:05    I'll press Enter,
04:06    and watch what happens in the design view.
04:09    It updates the appearance of the window automatically.
04:12    Now, to make this a little bit easier to read,
04:15    with the TextBlock still selected,
04:17    I'll open the Text category.
04:20    I'll change the size of my label
04:22    from 12 to 36 pixels.
04:25    I'll do that by setting the value to 36 px.
04:29    I'll save my changes
04:31    and run the application by pressing F5.
04:34    And there's the application in its current state.
04:37    I see my TextBlock control
04:39    displaying the text "Hello, world!"
04:42    But where's C# in all this?
04:45    The answer is, I'm not using C# to do any of this work yet.
04:49    I'm doing everything in XAML.
04:51    Let's take a look at how we can use C#
04:54    to affect the appearance of the application.
04:57    The default text that I'm displaying is "Hello, world!"
05:01    In order to manage this TextBlock control,
05:05    I need to give it a name.
05:06    In the Properties panel,
05:08    I'll click into the Name entry,
05:10    and I'll call this control "txtHello."
05:14    When I do that in the Properties panel,
05:16    I'll see in the XAML view down here
05:19    that my TextBlock element now has an attribute
05:22    called x:Name, set to the name txtHello.
05:27    Now that I've done that, I can address this control
05:29    and make it do something using C# code.
05:33    I can get to my C# file
05:35    through the Solution Explorer,
05:37    or, if it's already open, through the tab at the top.
05:41    As this application starts up,
05:43    it runs a method called MainWindow.
05:47    Remember, in the console application,
05:49    the automatic method was called "Main,"
05:52    but in a WPF application, it's called "MainWindow."
05:56    In object-oriented vocabulary,
05:59    this is the constructor method
06:01    for the MainWindow class.
06:04    If those phrases don't make any sense yet,
06:06    don't worry.
06:07    I'll be covering them later.
06:09    But this method will run automatically
06:11    when the application starts up.
06:14    So, to affect the appearance of the application,
06:17    I'll use this code.
06:18    TxtHello is now an object that I can address
06:22    from my C# code.
06:24    I'll type that much in and put in a period.
06:27    Then I'm going to set something called a property,
06:30    named "Text" to a certain value.
06:33    I'll set it to "Hello from C#!"
06:37    I'll type in that text,
06:38    and, as with all C# statements,
06:40    I'll finish with a semicolon,
06:42    and I'll run the application with F5.
06:45    And there's the result.
06:47    Now I can see that my C# code is being executed
06:51    and the value I'm setting there
06:52    is overriding the default value
06:55    that I set in my XAML code.
06:58    That tells me that in this environment,
07:00    my C# code in my code-behind file,
07:04    is executed after the default setting.
07:08    And now I'm manipulating the visual control
07:10    using C# code.
07:13    So that's a Hello World application
07:15    written in Windows Presentation Foundation.
07:18    Next, we'll take a look at another application framework,
07:21    asp.net for the Web.
Collapse this transcript
Creating a simple web application
00:00    - I've previously described how to use C#
00:03    to build applications for the desktop
00:05    both in the console environment,
00:07    and to build visual applications
00:09    using Windows Presentation Foundation.
00:12    Now I'll show you how to use C# to build
00:14    web based applications using asp.net.
00:18    To follow along with this demonstration,
00:20    you can either use one of the pay for license
00:23    versions of Visual Studio or the free edition,
00:26    Visual Studio Express for Web.
00:29    I'll select File, New, and this time I'll choose Website.
00:35    I'll make sure I've chosen Visual C#
00:37    from the templates list,
00:38    and then ASP.NET Empty Web Site.
00:42    I'll place my website in this folder,
00:44    02_GettingStarted WebSite.
00:47    You could place it anywhere on your hard disk
00:49    if you prefer.
00:51    When I click OK, that creates the folder
00:53    and adds a single file called Web.config.
00:57    It's up to you to add the various files
01:00    that you need to build the website.
01:02    I'll go to the WebSite project in the solution explorer
01:05    and I'll right click and choose Add,
01:08    Add New Item, and then I'll choose Web Form
01:12    as my file type.
01:14    A web form is an asp.net page.
01:17    You can add visual controls to it
01:19    in a very similar fashion to WPF,
01:22    but these visual controls will be translated
01:25    as HTML Markup after the page is generated
01:28    at the server and then sent back to the browser.
01:32    I'll accept a default name of the file,
01:34    Default.aspx, and click Add.
01:38    This is what the page looks like in its default state.
01:42    It looks basically like an HTML page,
01:44    but notice that some of the HTML elements
01:47    have a runat="server" attribute.
01:50    That means that these elements will be sent
01:52    to the server and processed there,
01:55    and HTML will be sent back to the browser.
01:58    Now to build the visual content of my form,
02:01    I'll go into design view and I'll click
02:03    the Toolbox panel and pin it so I can see
02:07    both the Toolbox and the full page.
02:10    Then I'll drag and drop a few controls.
02:13    I'll start with the TextBox control
02:16    and I'll place it inside the Div tag.
02:19    Then I'll do the same thing with the Button control.
02:22    I'll drop that right next to the TextBox.
02:26    And finally, I'll add a Label control,
02:29    and I'll put that at the bottom.
02:31    Now let's take a look at the source code
02:33    that was generated.
02:34    I don't need the Toolbox anymore, so I'll close that.
02:37    Here's the Markup.
02:39    Notice that each of these three visual controls,
02:43    the Textbox, the Button, and the Label,
02:45    are represented by Markup,
02:47    but they all have an asp prefix.
02:51    That means they're a part of the asp.net namespace.
02:55    They also all have the runat="server" attribute.
02:58    So they'll all be processed at the server level.
03:01    Next I'll add something called an event handler.
03:05    I'll click into the Button control,
03:07    and then over here I'll look at the properties panel
03:10    and I'll click the lightning bolt icon.
03:13    That gives me a list of the events that can happen
03:16    when I'm working with this control.
03:18    The first event is called the click event.
03:21    To generate some C# code, I'll just double click
03:25    in the text box next to the event name.
03:28    That generates an event handler method.
03:31    This code will be executed when the user
03:33    clicks the button.
03:34    Then I'll add some simple C# code.
03:37    I'll declare a string based variable that I'll call value
03:41    and I'll set it with the expression TextBox1.Text.
03:44    Let's take a look at how this expression
03:46    is put together.
03:48    I'll go back to the Web Form file,
03:51    and I'll see that TextBox has an ID of TextBox1.
03:55    I'll also see that this Label has an ID of Label1.
03:59    So I'm addressing the TextBox using its ID.
04:03    Next I'll set the value of the Label
04:05    using Label1.Text, and I'll set it
04:08    to the variable named value.
04:11    That's all the code I'm going to add.
04:13    Now I'm going to run the application,
04:15    and I'll do that by clicking the Internet Explorer
04:18    button in the toolbar.
04:20    In order to run an asp.net file,
04:22    you need a server.
04:24    Visual Studio includes a development server
04:27    that will fire up automatically.
04:29    When I click the button, that starts the server.
04:32    Notice in the url, it includes a port number,
04:36    which is dynamically generated.
04:38    So I'm addressing the file on the server
04:41    at port 49535.
04:44    Your port number might be different.
04:46    Now I'll test my C# code.
04:49    I'll type Hello World!
04:52    Then I'll click the button, and there's the result.
04:55    The value is read from the textbox
04:58    and then displayed in the label.
05:00    Now there's quite a bit going on in this process.
05:04    When the user clicks the button,
05:05    the value they type into that form control
05:08    is sent back to the server, and new HTML
05:11    is generated and sent back to the browser.
05:14    In a local environment though, it all happens
05:16    so fast that it feels like a desktop application.
05:20    So that's how a basic web application works.
05:24    Using asp.net web forms, you design your interface
05:28    and code your C# using very similar architecture
05:32    to Windows Presentation Foundation.
05:34    Instead of using XAML, as you do in WPF
05:38    and in Windows Store apps,
05:40    you use HTML and asp.net visual control tags.
05:45    But this is enough to give you a sense
05:47    that when you learn C#, you're learning
05:49    a language that can be used in a lot
05:51    of different environments.
Collapse this transcript
Reviewing the CodeRunner app
00:00    - The core of this course is about
00:02    the programming language C#,
00:04    but C# is mostly used to work with visual environments.
00:08    Web applications, desktop, mobile and so on.
00:12    And so even in the early parts of this course
00:14    I'm going to be teaching C# using a visual application
00:18    built with Windows Presentation Foundation.
00:21    You can find the base application here
00:23    in the CodeRunner folder under this chapter.
00:27    To open this project in Visual Studio
00:30    double click the solution file.
00:32    It should be identifiable by the graphic,
00:34    and when you move the cursor over it
00:37    it should say Microsoft Visual Studio Solution.
00:40    You could open this project in either a
00:42    pay-for-license version of Visual Studio
00:44    or in the free edition,
00:46    Visual Studio Express for Windows Desktop.
00:49    Here are the files that make up this solution.
00:52    First a XAML file that has a number of visual controls.
00:56    There's a Label with a Text value of "Enter a value",
00:59    a couple of TextBoxes, and two Buttons labeled Go and Clear.
01:05    And there's an associated code-behind file
01:08    named MainWindow.xaml.cs.
01:11    If you don't see this file make sure you've
01:14    opened up the tree control next to the XAML file.
01:17    You'll find a bit of existing code here.
01:20    There's a method named RunCode
01:22    that's executed when you click the Go button.
01:25    It calls a method called Output which passes a value in
01:29    and then displays that value by
01:32    appending it to the current output.
01:34    And finally there's a method named
01:36    ClearOutput that clears the current output.
01:39    I won't go through the specifics of this code yet
01:42    but by the time you finish this course
01:44    this will make all kinds of sense.
01:46    But I'll run the application by clicking
01:47    the Start button on the toolbar.
01:50    Then I'll click into the TextBox and enter a value,
01:52    "Hello from C#", then I'll click Go
01:56    and there's the result.
01:58    And I can click the Go button as many times as I want
02:01    and whatever value I've typed in will be displayed again.
02:05    And I can click the Clear button
02:07    and that will clear the display.
02:09    So this is the base application that
02:11    I'll be using for most of the course.
02:13    The goal here is to make it easy to learn the
02:15    programming language, but along the way you'll be seeing
02:19    how the language is used with the visual environments,
02:22    such as Windows Presentation Foundation.
Collapse this transcript
3. Language Fundamentals
Everything is an object
00:00    - C# is an object-oriented language.
00:03    This makes it similar to Java, C++ and many others.
00:08    Not all object-oriented languages are the same.
00:12    Some languages are mostly procedural and incorporate
00:15    some object-oriented features.
00:18    C#, however, is a strict object-oriented language.
00:22    That means that all values are stored as objects
00:25    or as members of objects.
00:28    We'll be talking about the nature of objects later,
00:31    but for now, we'll use this definition.
00:34    An object is an area of memory that stores
00:37    data and behaviors.
00:40    C# doesn't support the concept of global variables
00:44    or functions that you might find in procedural languages.
00:47    For example, in JavaScript in a browser,
00:51    you can define a variable that's global
00:53    to the entire web page.
00:55    And in Visual Basic 6, the predecessor to today's
00:59    Visual Basic for .NET, you could define variables
01:03    that were global to an entire application.
01:06    But in C#, everything belongs to something.
01:10    Objects in C# are instances of things called
01:14    classes and structures.
01:18    Classes and structures are very similar to each other
01:21    in that they both define member objects.
01:24    For example, if you want to work with some data in C#,
01:28    you would define it as a member of a class or a structure.
01:34    Persistent data is stored in something called a field,
01:38    which is defined as a member of the class or structure.
01:41    Fields are typically private to the class or structure,
01:45    that is, their values can only be read by code
01:48    within the class or structure.
01:50    But you can then expose those values as properties
01:54    that can be read and set by the rest of the application.
01:59    And behaviors are also defined as members
02:02    of classes or structures, encapsulated in methods.
02:07    A method is just like a function in a non-object-oriented
02:11    language, but like fields and properties,
02:14    it's a member of a class or structure.
02:17    Everything is a part of a class or structure,
02:20    and much of what you work with are instances
02:23    of these classes or structures.
02:25    These instances are the objects we're speaking of,
02:29    and so that's why we say everything is an object in C#.
02:35    Here's what the definition of a class looks like in C#.
02:39    It starts with a namespace declaration.
02:42    I'll talk about namespaces later but in brief,
02:46    a namespace is a way of organizing your code.
02:50    By placing each class in a namespace, you can avoid
02:53    conflicts in names or identifiers.
02:56    So for example, you could have two classes of the same name
03:00    in a single application, as long as their members
03:03    of different namespaces.
03:06    In C#, namespaces are defined purely in code.
03:10    Unlike say, in Java, which organizes classes in packages,
03:15    you don't have to relate the namespace
03:17    to a folder of the same name.
03:20    But many developers do follow this practice
03:23    and it's supported by Visual Studio.
03:25    It's just not required by the C# compiler.
03:30    Within the namespace, you declare the class or structure,
03:33    and you assign it a name.
03:35    Names of classes in C# are typically spelled
03:38    with Pascal casing.
03:41    That means it starts with an initial uppercase character
03:44    and then uses lowercase or CamelCase
03:47    for the rest of the name.
03:49    Within the class, you'll find the
03:51    member fields and properties.
03:54    This class has a single method called Main.
03:57    The reason we do that is because console applications
04:01    always start with a Main method, spelled just like this.
04:06    In a console application, your executable code
04:09    is placed within the Main method.
04:12    This code is writing some output to the console
04:15    and then waiting for some input.
04:18    In addition to the classes you write, your C# applications
04:22    have access to the framework class library.
04:26    As I previously described, this library contains classes
04:30    that are available for all application frameworks,
04:33    and it's included in both the .NET and WinRT frameworks.
04:38    Examples of such classes are file management tools,
04:42    mathematical functions and other common operations.
04:47    Here's an example.
04:48    Let's say you wanted to execute a mathematical operation.
04:52    In some languages, simple mathematical functions might be
04:56    implemented as a member of the language itself
04:59    or as a global function.
05:01    But in C#, these tasks are defined as part of a class
05:06    called System.Math.
05:08    System is the namespace and Math is the name of the class.
05:13    Most common mathematical operations are defined
05:16    in this class as something called a static method.
05:20    A static method is called as a member of the class itself,
05:25    and not from an instance of the class.
05:29    The Math class also has some common values
05:32    that are stored as fields, or constants.
05:36    So for example, if you wanted to call some functionality
05:39    from the Math class, first you would add
05:41    this line of code, using System.Math.
05:45    That's like the import statement in Java.
05:48    It means I want to use this class in my code
05:50    and make it available to the compiler.
05:54    Once I've declared the using statement, I can refer
05:57    to any of the member fields or methods of the class.
06:00    So if I wanted to get the value of the mathematical
06:03    constant pi, that's a field called Math.PI.
06:08    And if I wanted to round a numeric value,
06:11    I could use Math.Round, and then I could
06:13    output that value or do some other operation.
06:18    You'll find that a lot of the things you might want to do
06:20    in an application, such as mathematical operations,
06:23    working with files, communicating over the Internet,
06:26    and so on, are already implemented in the
06:29    framework class library.
06:31    And so it's a good idea to get to know that library.
06:34    There are a lot of namespaces and classes in it,
06:37    and you can't learn it all at the same time,
06:40    but as you need a particular class,
06:43    take a look at the documentation.
06:46    You can diagram your classes using
06:48    Unified Modeling Language, or UML.
06:51    This UML diagram for example, shows that there are
06:55    two fields in the Math class called E and PI,
06:59    and then many methods.
07:01    Again, most of them are implemented as static methods
07:04    that are called directly from the class.
07:08    As you get to know C# as a pure object-oriented language,
07:12    you'll find that learning the library is as much
07:14    a part of the process as the language itself.
07:18    You'll see that there are some parts of the library
07:20    that you use all the time, and you'll memorize
07:23    their functionality and syntax.
07:25    And then there will be other parts that you
07:27    only use occasionally, and you'll have to go back
07:30    to the documentation to learn the details as you need them.
Collapse this transcript
Understanding C# syntax
00:00    - C# shares characteristics with other C-style languages
00:05    including C, C++, Java and JavaScript.
00:09    Here are some of the key characteristics of C#.
00:13    First of all, C# is case sensitive.
00:17    Every keyword and every identifier, such as names of
00:21    variables, classes, methods, fields and so on,
00:25    is identified by a string of characters.
00:28    Examples of keywords include namespace, class,
00:32    static and void.
00:35    Examples of identifiers in this code include the namespace,
00:39    HelloConsole, the class name, Program,
00:44    the name of the method, Main, and so on.
00:47    Another thing to know about C# is that it's
00:49    not sensitive to white space.
00:52    In finished C# demonstrations, you'll typically see
00:56    very nice tabulation, indentation to make the code
00:59    easy to read, but that's not necessary for the code to work.
01:03    I could take this code and make it align
01:05    all the way to the left side,
01:07    and it would still work just fine.
01:09    I'll save that change and run the code,
01:12    and I'll see the output, "Hello World!"
01:15    I'm going to increase the size of this font
01:18    to make sure it's more readable.
01:22    And you can even run code together
01:24    so it's all on a single line.
01:27    That's because what separates statements from each other
01:30    is the semicolon.
01:32    Once again I'll save this and run it,
01:35    and I'll see it works exactly as before.
01:39    In C# the semicolon is critical.
01:42    It means this is the end of the statement.
01:45    Unlike in JavaScript in the browser, it is required,
01:50    and if you leave it out, the compiler will throw an error.
01:53    Now, if your code ends up looking like this
01:55    after you type it,
01:57    you might be tempted to put the indentation
01:59    back in manually.
02:01    But Visual Studio can do it for you.
02:04    Go to the menu and choose
02:05    Edit, Advanced, Format Document,
02:10    and you'll see that there's an associated
02:11    keyboard shortcut for that as well,
02:14    pressing ctrl + k, and then ctrl + d.
02:17    And it will return the indentation
02:20    to the standard appearance.
02:22    It may not pick up everything.
02:24    For example here, it's left these two statements
02:27    on a single line, but this is pretty easy for me
02:30    to fix manually.
02:32    So those are the two critical things to remember about C#.
02:35    It is case sensitive and it's not white space sensitive,
02:39    but you must put the braces and the semicolons
02:43    in the correct place so that the compiler can
02:45    interpret the code and turn it into byte code
02:49    that can be executed by the .NET framework
02:51    or the Windows runtime.
Collapse this transcript
Identifier naming conventions
00:00    - In every programming language you have
00:02    to decide how you're going to name your identifiers.
00:06    Those are the names of your variables,
00:07    classes, methods, properties, and so on.
00:11    In C# some of the naming rules are enforced by the compiler,
00:15    you have follow them.
00:17    And then there are unenforced guidelines
00:20    that are suggested by Microsoft
00:22    but you don't necessarily have to follow.
00:25    Whenever you deal naming guidelines,
00:27    there's always going to be some disagreement.
00:29    Some people care very deeply about this subject
00:32    but it's important to know what the compiler requires
00:36    and what you get to decide on.
00:38    If you're a solo developer, you can decide for yourself,
00:42    as long as you're the only one ever looking at the code,
00:45    it really doesn't matter.
00:47    But obviously in a team environment,
00:49    you really should discuss
00:51    and agree on your guidelines before you begin to code.
00:55    Here are the naming rules that are enforced
00:56    by the C# compiler.
00:58    You identifier names, and again this includes class names,
01:02    structures, fields, properties, and methods,
01:06    each of these can include alphanumeric characters,
01:09    A through Z and zero through nine.
01:13    But they can't include special characters
01:15    such as currency symbols, percents, and so on.
01:19    For purposes of naming identifiers,
01:22    the underscore is just like an
01:24    alphabetical character A through Z.
01:27    The first character of every identifier
01:29    must be an alphabetical character or an underscore.
01:33    It can't be a numeric value.
01:35    And as I've mentioned, C# is case sensitive.
01:40    The identifier, which again is the name
01:42    of the method, variable, property, and so on,
01:45    has to be unique within its scope
01:48    but because C# is case sensitive each
01:51    of the following identifiers is considered unique.
01:54    firstName with an uppercase N.
01:57    FirstName with uppercase F and N.
02:00    And all uppercase.
02:02    The case sensitivity of C# means that each of
02:05    these are considered unique identifiers
02:08    and each can represent a different value.
02:10    Now, I'm not recommending that you do this.
02:13    If you created three variables all named this way,
02:16    it would be incredibly confusing.
02:18    But if you follow the guidelines that I'm about to describe
02:21    you won't have this problem.
02:23    Here are the general recommendations from Microsoft.
02:27    First, choose easily readable identifier names.
02:30    First name for example, says exactly
02:33    what the data is: somebody's first name.
02:36    The letter N on the other hand might be brief
02:39    but you don't know what it represents.
02:42    And typically you want to favor readability over brevity.
02:45    It'll make your code easier to maintain in the long run.
02:49    Once again, no underscores, hyphens, or special characters.
02:52    The compiler enforces that.
02:55    And for C# code, it's recommended
02:58    that you don't use what's called Hungarian notation.
03:01    For example, a string starting with str
03:04    or an integer starting with i.
03:07    You'll see that many developers do use Hungarian notation
03:10    when naming their visual controls in XAML,
03:13    the mark up language that's used to define
03:15    the user interface in Windows Presentation Foundation,
03:19    Windows store apps, and Windows phone apps,
03:22    but in your C# code, Microsoft recommends
03:25    that you don't do that.
03:27    Instead, here are the recommendations.
03:30    For variables, fields, and parameters start
03:33    with a lowercase initial character
03:35    and then use camel-case to distinguish individual words.
03:40    An integer variable that's used
03:42    very briefly might simply be called i
03:45    but a variable that's going
03:46    to be used throughout a class
03:48    or an application should be named for readability.
03:51    And this is camel-case, the use of uppercase characters
03:55    to indicate the beginning of a new word
03:58    and this is another camel-case value.
04:00    Again, starting with an initial lowercase character,
04:04    and then using uppercase characters where it's useful.
04:08    For all other identifiers, use Pascal Casing.
04:12    That means you start with
04:13    an initial uppercase character
04:15    and then camel-case for the rest.
04:18    This variable represents an integer.
04:20    It starts with an uppercase initial character
04:23    and then uses camel-case for the rest.
04:26    Notice that it's a constant.
04:28    If you're coming from Java programming,
04:30    you might think, "Shouldn't that be all uppercase?"
04:33    And the response would be, "That's a java convention."
04:36    The C# recommended convention is to use Pascal Casing.
04:41    And we use this for constants and also for methods,
04:45    constants, properties, names of classes and structures,
04:49    and again everything but the transient values
04:52    such as variables and parameters.
04:55    As I've mentioned, you'll see in the examples
04:57    that Microsoft provides in the C# documentation
05:00    that Microsoft is pretty consistent
05:03    following these guidelines.
05:04    Not a hundred percent but pretty close.
05:08    And it's a good idea to follow the guidelines yourself
05:11    as you get started learning how to program in C#.
Collapse this transcript
Using the documentation
00:00    - The C# programming language
00:02    is accompanied by extensive documentation.
00:05    API docs, references and examples.
00:09    All of this documentation is available
00:11    in a couple of different forms.
00:13    By default, when you go to the menu in Visual Studio
00:17    and select HELP and then View Help,
00:20    you'll open the documentation in a web browser,
00:23    and you'll be viewing the documentation set
00:26    on the Microsoft website.
00:27    The advantage to this is that the documentation
00:30    is always guaranteed to be up-to-date,
00:33    but it's a little bit slow sometimes
00:35    and also, you have to have web access
00:39    whenever you need to look something up.
00:41    I find it easier to download the content to my computer
00:44    and then open the documentation locally.
00:48    To do that, go back to Visual Studio and choose HELP again
00:52    then Set Help Preference,
00:55    Launch in Help Viewer.
00:58    Then try opening the HELP again
01:00    and this time you'll open the Help Viewer application,
01:04    a local application that lets you see the documentation
01:08    that's stored on your local hard disk.
01:11    The first time you do this,
01:13    you'll be prompted to download some content.
01:16    That will be in the Manage Content tab.
01:19    You'll see a listing of all the content that's available.
01:22    For this course, I recommend downloading the sections
01:25    on Visual Basic and Visual C#,
01:28    Visual Studio 2013 Fundamentals
01:31    and the .NET Framework 4.5.
01:35    Select the categories you want,
01:37    then click the download button,
01:39    answer any security requests
01:42    and then wait for a moment
01:43    for your content to download.
01:45    Once the download is complete,
01:47    you should then be able to go to the menu again
01:50    and select View Help and you should go to the
01:53    Visual Studio documentation.
01:55    From there, you can select Visual Basic and Visual C#.
02:00    You can go directly to the Visual C# section
02:04    and then you'll find links to all the different subjects
02:06    to learn about the language,
02:08    including the Programming Guide,
02:10    the Reference, Sample Applications,
02:13    Walkthroughs and more.
02:15    Within the View Helper, whenever you find something
02:18    you want to be able to come back to easily,
02:20    you could right click on it
02:22    and click Add to Favorites.
02:24    Then you'll see that item listed in your Favorites
02:27    and you can easily get to it whenever you want.
02:31    For example, if I closed the View Helper,
02:34    then went to View Help,
02:36    I would start once again at Visual Studio
02:38    but I could click on Favorites
02:40    and go directly to C#.
02:42    Finally, Visual Studio supports
02:44    extensive context-sensitive help.
02:47    That means, you can place the cursor
02:50    in the identifier for anything for which
02:52    there's documentation and then press F1.
02:56    That will open the Help system
02:58    and jump directly to the documentation
03:01    for the selected identifier.
03:03    If you've changed your Visual Studio preference
03:06    to use Help with the Help Viewer application
03:09    and you've downloaded the content to your local hard disk,
03:12    you'll find that getting to the documentation
03:14    is very fast and very easy.
03:17    There are lots of other ways to get help,
03:19    to learn how to program with various classes,
03:22    methods, properties and so on,
03:25    but I'll talk about some of those tricks
03:27    as I continue through the course.
Collapse this transcript
4. Declaring Variables
Using built-in data types
00:00    - In C Sharp, when we store data
00:03    we have to say what type of data we're storing.
00:06    Each variable has a data type.
00:10    A data type defines what you can
00:11    put into the variable.
00:14    A variable can be numeric,
00:16    it can be a string value,
00:17    it can be a logical value like true false.
00:20    But it can't be all of the above,
00:23    you have to choose.
00:25    And it's up to you as the programmer
00:26    to decide what each variable can contain.
00:29    We say that C# is a strongly typed language.
00:33    That's because once a variable's data type
00:36    is declared, it can't change.
00:39    That's different from a dynamic language,
00:42    such as JavaScript, where a variable's type
00:45    can change from one moment to the next
00:47    depending on what value you assign it.
00:50    In C# we have a whole set of built in data types.
00:55    Data types that are a part of the framework,
00:58    and that you use extensively
01:00    to represent simple values.
01:03    These data types fall into categories such as
01:05    logical, that's true false values, numeric,
01:10    characters and strings, and objects.
01:14    And an object is an instance
01:16    of a class or a structure.
01:18    In C#, each and every data type
01:21    is represented as either a class or a structure.
01:25    That's different from some other languages.
01:27    For example in Java, you distinguish between
01:31    primitive data types such as numeric values
01:34    and boolean values, and reference types
01:38    which are instances of classes or structures.
01:41    In C#, everything is an instance
01:44    of a class or a structure.
01:46    And therefore, every variable is an instance
01:49    of some class or structure that has
01:52    properties and methods.
01:54    And that extends to the simplest of data types,
01:57    such as boolean and integer values.
02:00    As I've mentioned previously,
02:02    it doesn't matter for the purpose
02:04    of instantiating something,
02:06    whether it starts as a class or a structure,
02:09    but there are differences between the two.
02:13    Structures are what we call value types.
02:16    This is similar in concept to Java's primitives,
02:20    in the sense that if you start with one variable,
02:24    and then you declare and assign a second variable
02:27    from the first, you're making a copy.
02:31    If you now change the value of v2,
02:34    it won't affect v1,
02:37    if the data type started off as a structure,
02:39    and that's true of integers.
02:42    On the other hand, classes are reference types.
02:46    The object class is a class, not a structure.
02:50    And so, if I declare an object,
02:53    which I named here o1,
02:55    and then I declare a second object
02:58    and I reference o1, now if I change properties
03:01    of o2 I will also affect o1.
03:05    Because in this case both variables
03:08    are pointing to, or referencing,
03:11    a single object in memory.
03:14    In general, structures are value types
03:16    and classes are reference types.
03:19    But there are some exceptions,
03:21    and I'll talk about that in a moment.
03:23    Here are some of the most commonly used
03:24    structures you'll use in your C# programming.
03:29    The data types that represent numeric
03:31    and logical values in C# are defined as structures
03:36    that is as value types.
03:38    For example, booleans, integers,
03:41    floating-point values, and decimals
03:44    are all defined as structures in the
03:46    .NET framework and the windows runtime,
03:49    and represented in C# that way as well.
03:53    Here are some examples of structures
03:54    you'll use very frequently.
03:56    Each data type is represented as its
03:58    native type and as a C# alias.
04:03    The first column here is the alias.
04:06    It's a key word in C# that represents
04:09    an underlying class or structure,
04:12    in this case structures.
04:14    For the first one, the C# alias or type is bool
04:18    and the equivalent .NET type is Boolean.
04:22    Because this is a structure it starts
04:24    with an uppercase "B", but the C# alias
04:27    starts with a lowercase character.
04:29    Boolean variables only have two
04:31    possible values, false and true.
04:34    There is no numeric equivalent to these.
04:37    You refer to Boolean values with
04:39    the keywords true and false.
04:42    A character type represents a single
04:44    numeric or alphabetical character.
04:46    The C# alias is char, c-h-a-r,
04:50    all lowercase, and the .NET type is the same,
04:53    but with an uppercase initial character.
04:55    All .NET data types are members
04:58    of the system namespace.
05:00    So the fully qualified structure name would be
05:03    System.Boolean, or System.Char,
05:06    but in your code you'll typically refer
05:09    to these with a C# alias, bool or char,
05:13    all lowercase.
05:15    Here are the integer types,
05:16    and there are eight of them.
05:18    Starting with the smallest value "byte",
05:21    and finishing with the longest "long".
05:24    For each of the four basic types there's
05:26    a signed and an unsigned version.
05:29    The signed version can have both
05:31    negative and positive values,
05:33    while the unsigned version only
05:35    has zero or positive values.
05:39    The ranges change depending on whether you're
05:40    working with signed or unsigned values.
05:44    Byte for example can start with
05:45    zero and go to 255.
05:48    An assigned byte, or sbyte,
05:50    can start at -128 and go to positive 127.
05:55    And each of these types then shows
05:57    the potential range.
06:00    For most of the programming I use in this course,
06:03    I start off with an "int" value.
06:05    That gives you a very broad range,
06:07    or a "uint" if I need negative values.
06:10    And I typically only go to bytes and shorts
06:12    if I have a specific need for it.
06:16    Floating-point and decimal types include
06:18    float, double, and decimal.
06:21    The most commonly used of these
06:22    is the double value, but there are issues
06:25    you'll run into with double values
06:27    when you're doing precise mathematical operations.
06:30    For example, if you're working with
06:32    currency values, it's strongly recommended
06:35    that you use the decimal data type for these.
06:38    Decimal is a 128-bit, high precision type.
06:42    It will accurately reflect and calculate
06:45    currency values in situations where
06:48    doubles and floats might not be reliable.
06:51    And finally that brings us to strings.
06:54    A string is exactly what it says,
06:57    a set of characters, and as you see here
07:00    string data types have a very long
07:03    potential maximum length.
07:05    But that's only theoretical actually,
07:08    because you really need to pay attention
07:10    to available memory.
07:12    For example, if you're working in a mobile app
07:14    on a phone device, you don't have that much
07:17    memory available so creating a string
07:19    that's that long might cause
07:21    the device to run out of memory.
07:24    Also, string is kind of unique.
07:27    It's defined as a class, not a structure,
07:31    but in actual use it behaves
07:33    more like a structure.
07:35    A string variable is immutable,
07:38    that is, it can't really be changed
07:40    after it's been created.
07:42    But the C# compiler has some very
07:44    special ways of dealing with strings
07:47    that make it look like you can modify it
07:48    after it's been created, and compare
07:51    strings to each other in ways that don't
07:54    really make sense for most classes.
07:56    I'll talk about strings a lot more later,
07:59    but for now it's important to know that string,
08:02    along with all these others,
08:04    is a built in data type in C#,
08:07    and it's represented like all the others
08:10    by a .NET data type.
08:12    And if you're working in window's store
08:14    apps with C#, you'll use the same identifiers
08:18    to refer to the string, integer types,
08:21    logical types, and so on.
Collapse this transcript
Declaring variables
00:00    - One of the most important things you need
00:02    to know how to do in a programming language
00:04    is to declare variables.
00:06    Places where you can store data in memory.
00:10    I'll show you how to do this in this project
00:12    Declare Variables.
00:13    Which is in the 04_Variables Chapter.
00:17    I'll go to the folder for this chapter
00:19    in the exercise files and double click the solution file,
00:23    and that will open it in Visual Studio.
00:26    This is a WPF application.
00:29    It's the code runner application
00:31    that I described previously.
00:33    This application will allow us to
00:35    add arbitrary code and then output
00:38    the results to the screen.
00:40    I'll start in the file mainwindow.xaml.cs,
00:43    and I'll press alt + shift + enter
00:46    to look at the code in full screen.
00:48    When I click the go button
00:49    I'll be running this method RunCode.
00:52    So this is where I'll place all the code.
00:54    To make this a little bit easier to work with,
00:57    I'll collapse all the other methods around it.
01:00    And now I'll know exactly where
01:02    I'm supposed to put my code.
01:04    To declare a variable in C#
01:06    you start with the data type.
01:08    I'll start with int which is the C#
01:12    alias for the Int32 class.
01:14    That's the Data Type Declaration,
01:17    and next is the Variable Name or Identifier.
01:21    And I'll name it I for Integer,
01:24    and I'll give it a value of 42.
01:28    So this Declaration is in four parts.
01:31    First the Data Type int,
01:33    then the Identifier I,
01:35    then Assignment Operator which is the equal sign,
01:39    and then value I'm assigning which
01:42    in this case is a Literal Value of 42.
01:45    Notice the squiggly mark under the variable name.
01:49    That's a warning that tells me
01:51    I haven't used that value.
01:54    That wouldn't stop me from compiling
01:56    my application but it's a warning that says
01:59    if you really don't need this variable
02:02    you probably don't want to declare it.
02:05    But I'm going to output something here
02:06    using that variable so I'll use my Output
02:09    method and I'll pass in a literal string
02:13    of the value is and then I'll add a plus
02:17    character after the literal string
02:19    and then the variable name, I.
02:22    And finally I'll add the semicolon
02:25    to finish this statement.
02:26    Then I'll run the application.
02:28    From this screen you can just press the F5
02:31    key and that'll run the application in debug mode.
02:35    I'll click the Go button,
02:36    and there's the result.
02:38    Now here's what's actually happening.
02:40    I've declared an integer value.
02:43    It's name is I; its value is 42,
02:45    and then I'm appending that value
02:47    to the string "The value is."
02:50    The plus character is both the mathematical
02:53    Addition Operator and the Concatenation
02:56    Operator for strings.
02:58    And when you append the value typically
03:00    you can work with any kind of value
03:03    because that value will be automatically
03:04    turned into a string for you.
03:06    So that's the simplest sort of Declaration,
03:09    but you can also Declare variables
03:12    and initialize them using the classes
03:14    and structures themselves from the C# Libraries.
03:19    Here's another variable Declaration.
03:22    I'll create a variable and I'll call
03:23    it meaningOfLife and I'll instantiate it
03:27    with the keyword new and then the name
03:30    of the structure I want to instantiate, Int32.
03:34    You might remember from the table
03:37    I presented earlier that int is a C#
03:40    Alias for the Int32 structure,
03:43    and so now I'm creating an instance
03:46    of that structure and it'll have
03:47    whatever the structure's default value is.
03:51    I'll make a copy of my output statement,
03:55    and this time I'll output the value
03:56    of meaningOfLife.
03:59    I'll save the change and run the code.
04:03    I'll click the Go button and now I see
04:06    that the second value is zero.
04:08    That's the default value for a new Int32 object,
04:13    and you'll find that the same thing
04:15    is true for all the numeric structures.
04:17    Doubles, floats, and so on.
04:20    If you initialize them this way
04:22    by instantiating the structure itself
04:24    the default value is always zero.
04:28    So far I've been using explicit data typing.
04:32    That means that I use a C# Alias
04:35    or a .net structure or class name
04:37    to declare the type but in C# you
04:40    can also do Implicit Typing using
04:42    the keyword var.
04:46    I'll create a variable called implicitValue.
04:48    At this point the compiler doesn't have
04:51    any way of knowing what the Data Type
04:53    of this variable is but I'll pass it a value of 56.
04:58    Now the compiler is going to look at Literal
05:00    Value and decide that it can be an Integer.
05:05    So I can once again output the value
05:09    and I'll use the Implicit Value Variable
05:11    this time and I'll run the application.
05:14    And there's the result.
05:16    Everything is still working as expected,
05:19    but now if I'd like to find out what
05:20    the Data Type of this variable is
05:23    I can add a little bit more code.
05:25    I'll start with a Literal String.
05:28    The variables type is...
05:30    Then I'll use the Implicit Value Variable,
05:33    but then instead of outputting the value
05:35    I'll use a method called GetType.
05:40    It needs an opening and closing parenthesis
05:42    after the method name and it returns
05:45    something called a Type Object.
05:47    And then from there I'll put in another dot
05:50    and I'll call a method called ToString.
05:55    And this is how I'll discover what
05:56    the Data Type of the Implicitly Typed
05:59    Variable is and now when I run the code
06:02    I find that the Type is system.int32.
06:06    The same Data Type as the other
06:07    three variables, but this time the
06:09    compiler figured it out for me.
06:13    You can control the Data Type of
06:15    and Implicitly Typed Variable by
06:17    adding a suffix to the Literal Value.
06:20    56 By itself is seen as an Int32,
06:23    but take a look at what happens
06:25    if I add an L after 56.
06:28    You might think "Well, an L is an
06:30    "alphabetical character. It can't be
06:32    "interpreted as a number."
06:34    But the compiler sees this as a part
06:36    of the Literal and explicitly a statement
06:39    that this is a Long Integer not a 32bit Integer.
06:44    So now when I run the code the
06:47    Variables Type is Int64.
06:49    A 64bit Data Type that has a much broader
06:52    range than the 32bit version.
06:55    Finally, let's take a look at what happens
06:57    when you exceed the range of a variable.
07:00    I'll start with a Byte Value.
07:03    Now Bytes can only go from zero to 255.
07:09    So I'll declare the variable and
07:11    I'll give it a value of the maximum 255,
07:15    and I'll output "The byte value is,"
07:18    and then I'll use the Variable Name, byteValue.
07:24    I'll run and see the result,
07:26    and so far so good.
07:29    But with these numeric values if you
07:31    exceed the value of the range,
07:34    that is if you go above or below the available range
07:37    it'll cause the value to wrap around.
07:40    Right now my Byte Value Variable is
07:43    set at the maximum of the Byte range.
07:45    Watch what happens if I exceed it.
07:48    I'll say byteValue++.
07:52    That means increment the value
07:54    of this variable by one.
07:56    Then I'll copy and paste this bit of code.
08:00    I'll modify the message and run the code again,
08:03    and now after I try to increment the value
08:06    the variable's value is now zero.
08:09    So it's wrapped around.
08:11    It's gone from the highest possible value
08:13    for that range to the lowest possible value.
08:17    There are some circumstances in C#
08:19    where this kind of operation would cause
08:21    an exception or an error but with Integer
08:24    Values if you try to exceed the range
08:27    you'll just wrap around to the other side of the range.
08:30    So that's a look at how to declare variables in C#.
08:34    Using both Explicit and Implicit
08:38    Data Typing and also using either C# Aliases
08:42    such as int, bool, and char or
08:46    their equivalent .net class and structure names.
Collapse this transcript
Working with characters
00:00    - I've previously described
00:01    how to work with numeric values
00:03    in the video on declaring variables.
00:06    Now I'll talk about another data type called "char,"
00:10    which stands for "character."
00:12    The char data type represents a single character,
00:15    a single character that has to be a member
00:18    of the Unicode character set.
00:20    I'm working with a project named Chars,
00:22    or Chars (pronounces it "shars") that you'll find
00:24    in the exercise files folder for this chapter.
00:28    I'll start in the run code method
00:30    in the C# cobehind file for this project.
00:34    I'll start by declaring a variable
00:36    with a data type of char.
00:39    I'll give it a name of c1,
00:41    and I'll set its value to the letter a.
00:44    Notice that I'm wrapping the value in single quotes,
00:47    not double quotes.
00:49    Those are reserved in C# for strings, not characters.
00:55    Then, I'll call my output method,
00:58    and I'll start with a literal string, a label,
01:01    "The value of c1 is,"
01:03    and then I'll append to it the value of the variable.
01:07    I'll add the semicolon at the end of the line
01:10    and run the code.
01:12    And there's the result.
01:13    "The value of c1 is a."
01:17    I can put any alphanumeric character or special character
01:21    in this position,
01:22    and I'll output it using my output method.
01:26    That's the simplest use of a character variable.
01:29    But characters can also be translated as numeric values
01:33    using what are known as Unicode strings.
01:37    This kind of notation has the fancy name
01:39    of "hexadecimal ASCII."
01:42    It always starts with a \u
01:45    and then has a four-digit numeric value.
01:48    I'll declare another variable
01:49    that I'll call c2,
01:52    and I'll assign its value as \u0061.
01:58    Then I'll copy and paste my output statement.
02:02    I'll change both the label
02:03    and the variable I'm outputting to c2.
02:08    Now when I run the application,
02:10    I see exactly the same value,
02:12    that c2 is a,
02:14    and that's because 61 is the ASCII equivalent
02:18    of the letter a in lowercase.
02:22    Now, if I take that value and increment it by one ...
02:25    I'll set it to 62 and then run it again ...
02:30    this time I get the letter b.
02:32    You can find the numeric equivalent of any character
02:35    using an ASCII character chart.
02:38    They're easily findable and available on the Web.
02:42    Now, as with all data types in C#,
02:45    the char data type is represented
02:47    by a .net structure.
02:50    That structure has a number of valuable tools.
02:54    Let's take a look at the documentation
02:56    for the char structure.
02:58    I'll place the cursor in char
03:00    and press F1.
03:02    That takes me to the Help viewer
03:04    and to a link to system.char,
03:08    the underlying .net framework type.
03:11    Here you'll find a whole list of methods
03:14    that you can call from the char structure.
03:17    Notice all the different icons that are listed here
03:20    that tells you where these methods can be called.
03:23    Specifically, look for the big S icon.
03:26    That means that a method is a static method.
03:29    It's called from the structure itself
03:32    and not from an instance of the structure.
03:35    Let's say, for example, that I wanted to look at
03:38    any particular character
03:39    and find out whether it's a number
03:42    or an alphanumeric value.
03:44    I'll scroll down a bit
03:46    and find all these different methods
03:47    that start with the word "is."
03:50    They all return Boolean values, true or false.
03:53    Here's an interesting one called "is letter or digit,"
03:57    which takes a char value
03:59    and returns a Boolean value.
04:02    I'll try that one out.
04:04    I'll go back to my code
04:05    and look at it in full screen.
04:08    I'll declare a char variable
04:10    that I'll call "symbol,"
04:12    and I'll set it to a value of a dollar sign.
04:15    Once again, notice I'm using single quotes around the value.
04:19    Then I'll use my output method
04:22    and I'll start with the literal string
04:24    "Is number or letter."
04:27    Then I'll append to that Char.IsLetterOrDigit,
04:33    and I'll pass in my symbol variable.
04:35    I'm calling the method IsLetterOrDigit
04:38    as a member of the char structure,
04:41    not as a member of my symbol object.
04:44    That's a very important distinction.
04:46    You need to keep in mind
04:47    when to call something
04:49    as a static member of a structural class
04:51    and when to call it as an instance member.
04:55    I'll save that change and run the code.
04:58    And there's the result.
04:59    It tells me that the dollar sign character
05:01    is not a number or a letter.
05:04    And that's correct.
05:06    That's a brief look at the char data type.
05:09    A char variable represents a single character,
05:13    not a whole bunch of characters.
05:15    That would be a string.
05:17    That's what we'll look at next.
Collapse this transcript
Working with strings
00:00    - As I described, the char data type,
00:02    is used to represent a single character.
00:05    But if you need to represent a full string,
00:07    you need another class called string.
00:10    In this project named Strings,
00:12    I'm starting with an array of characters at line 19.
00:16    This is the first time I've used an array in a course,
00:19    so it bears some explanation.
00:21    An array in C# is a fixed length set of data.
00:25    This is an example of a set of five character objects.
00:30    You declare an array starting with the data type
00:33    of the items within the array, in this case char,
00:36    and follow that with a pair of brackets,
00:39    then the identifier, the array name,
00:42    and then the assignment, and then the array initialization.
00:47    There are a couple of ways of doing this, but the simplest,
00:49    is to wrap the items in a pair of braces,
00:53    and then list them separated by commas.
00:56    So I have five individual characters.
00:59    Now, you can't deal with a character array
01:02    in the same ways you can a string.
01:04    And I'll show you why.
01:06    I'll use my Output method,
01:08    and I'll pass in a literal string, The value of charArray,
01:12    and then I'll append to that, the array itself.
01:17    I'll run the code, and here's the result.
01:21    I don't see the actual value.
01:23    Instead, I see the data type.
01:26    An array of System.Char.
01:29    And that's how a lot of classes in
01:31    the world of C# are going to behave.
01:33    They don't transform instantly or easily into a string.
01:37    So, in order to transform this
01:40    array of characters into a string,
01:43    I'll declare a string variable.
01:46    The name of the underlying .NET data type,
01:48    is System.String with an upper case S because it's a class.
01:53    But in C# you typically refer to it
01:56    with the alias string, all lower case.
02:00    So that's my data type declaration.
02:02    And I'll give my variable a name of hello.
02:05    And then I'll create a new instance of the string class.
02:10    Notice that there are a number
02:12    of different ways to create a string.
02:15    I'm pressing the down arrow to loop
02:16    through all the different constructor methods.
02:20    A constructor method, is a method of a class or structure,
02:24    that you can use to initialize or instantiate an object.
02:29    So, I'm seeing a bunch of different ways to do this,
02:32    and I'm going to use the second version,
02:34    the one that accepts an array of characters.
02:38    And I'll pass in my array.
02:40    Then I'll copy and paste the call to the output method,
02:43    and I'll output the string.
02:46    And now, I'm outputting the actual values of the characters.
02:50    I've transformed an array of characters into a string.
02:56    Once you've created an array,
02:58    you can do a lot of things with it,
03:00    because the string class has an enormous number of methods.
03:05    I'll go to the documentation for the string alias,
03:08    and from there I'll click on String in the .NET framework.
03:12    And I'll scroll down and I'll see
03:14    all the constructor methods.
03:16    That's how you can create a string.
03:18    And then all of the methods.
03:20    As I mentioned before, the S means that
03:23    this is a static member,
03:25    something you call from the class itself.
03:27    There are also many instance methods,
03:30    methods that you call from objects
03:32    that are instances of the string class.
03:35    So we have a method named Contains.
03:38    It indicates whether a specified substring
03:40    is within the current string.
03:43    Or Equals, that lets you compare strings to each other.
03:48    I'll go back to my code,
03:49    and I'm going to use a method called toUpper,
03:53    which will take any string and transform it
03:56    into the all uppercase version of that string.
04:00    I'll create a new variable that I'll name helloUpper,
04:03    and I'll assign it with hello.toUpper.
04:09    Then I'll output the value of that new variable,
04:12    and lets see the result.
04:16    It's the same value, but now all uppercase.
04:20    In addition to the toUpper method, there's also toLower,
04:23    and variations on those methods as well.
04:27    Take a look at the documentation,
04:28    for all the versions of these methods that are available.
04:32    And you can also use tools to parse strings.
04:35    Here's one simple example.
04:37    The substring method.
04:40    I'll create a new variable that I'll name sub.
04:43    And I'll get it's value by calling hello.Substring.
04:49    There are two versions of the substring method.
04:52    One that just takes an integer, a starting index,
04:55    and one that takes a starting index and a length.
04:59    I'll pass in a starting index of three, and a length of two.
05:04    The starting index starts at zero,
05:06    so the first character is zero, the second is one and so on.
05:11    Then I'll output that value.
05:13    I'll paste in my output call.
05:15    And I'll change the name of the variable I'm looking at,
05:18    in both the label and the output.
05:21    And I'll run the code.
05:22    And there's the result.
05:25    The character at index three, is the fourth character.
05:29    The second 'l' in 'hello' and I asked for a length of two.
05:33    So I get 'lo'.
05:36    There's so much more that you can do with the string class.
05:39    I'll show later, when I talk about Boolean expressions,
05:43    how you compare strings to each other.
05:46    But it's also very important to understand,
05:48    that a string is called an immutable object.
05:52    That is, once it's been created, you can't change it.
05:56    And that's a memory management technique
05:58    that's used by both C# and by Java.
06:02    It appears in the compiler like you can do this.
06:05    For example, I'll say hello += " world";
06:12    And this means, append this literal string
06:14    to the existing string.
06:17    This code makes it look like
06:18    you can change the variable at runtime.
06:21    But in the background, the .NET framework or WinRT
06:25    are actually discarding the old object,
06:28    and creating an entirely new one.
06:31    I'll output the value of that variable,
06:33    and again this code works fine.
06:36    But as you'll see later, there are better ways of
06:38    appending text values to each other,
06:41    using C# and the foundation class library.
Collapse this transcript
Building strings with StringBuilder
00:00    - The string class is an immutable object.
00:03    That means that once a string object has been created,
00:06    it's value can't be changed.
00:09    The compiler gives you shortcuts to make it look like
00:11    you can change it
00:13    but, in fact, as I've previously mentioned,
00:15    in the background, you're discarding the original object
00:19    and creating a new one
00:20    and that's not really great for memory management.
00:24    I'm working in the project BuildingStrings
00:26    and I've placed some code that's already there
00:29    where I'm creating a string variable named "Hello",
00:32    then appending a value using the += operator
00:35    and then outputing the value.
00:38    And when I run the code, it all works fine.
00:42    But, that's not the best way to build a string at run time.
00:46    Instead, it's recommended that you use a class
00:48    called StringBuilder.
00:51    The StringBuilder is a member of the name space System.Text
00:55    and I've already placed a using statement in this file,
00:59    so, I can easily use the class.
01:02    I'm going to place the cursor
01:03    at the beginning of all this code
01:05    and I'll create an instance of this StringBuilder class
01:09    and I'll name it "builder" and I'll instantiate it
01:13    with a constructor method of the class.
01:16    Now, there are a number of different constructors available
01:20    and these give you different ways of managing
01:22    the memory and usage of the StringBuilder,
01:25    but, I'm going to use the simplest one,
01:27    the one that takes no arguments, or parameters.
01:31    Then, I'm going to say "builder.Append".
01:36    Notice that there are a few different append methods.
01:39    One called "Append, AppendFormat, and AppendLine",
01:44    but, I'm going to stick with just Append
01:46    and I'll pass in a string of "Hello",
01:48    then I'll call the Output method
01:51    and I'll pass in the builder object ToString method.
01:55    That means I'm getting the current string
01:57    from the builder object
01:59    and I'm going to delete the existing code.
02:03    I'll run the code and there's the result.
02:06    So far, I haven't done anything that you couldn't do
02:09    with the simple string variable.
02:11    But, now, let's add some more code.
02:14    I'll call the builder method Append method a few more times.
02:18    I'll pass in a comma and a space
02:21    then I'll call it again
02:23    and I'll pass in the word "World"
02:26    and I'll call it one more time
02:28    and I'll pass in an exclamation mark.
02:31    Then I'll copy and paste my call to the Output method
02:34    and I'll run the code.
02:38    And I see that I'm building the string
02:40    one piece at a time.
02:42    Finally, I'll show you a way of making your code
02:44    much more efficient.
02:46    I have an extra space in here,
02:47    so, I'll get rid of that.
02:49    But, if you move the cursor over the name of the method,
02:53    you'll get a little bit of bubble help
02:54    that tells you about how the method works.
02:57    Notice that the type that's in front
02:59    of the method name is StringBuilder.
03:02    That's the return data type,
03:04    the value that's returned when you call the Append method.
03:08    The Append method is returning a reference
03:11    to the current StringBuilder object.
03:14    So, it turns out that you don't need to reference
03:17    the builder object over and over again.
03:20    Instead, you can get rid of the references
03:22    to the builder object
03:24    on the last calls and then remove the semicolons
03:28    on the first calls.
03:30    And now you've turned these three calls to append
03:33    into a single C# statement.
03:36    I'll run the code one more time
03:39    and the result is the same
03:42    but, now your code is efficient and readable
03:45    and more importantly, you're only creating
03:48    a single object in memory, so, you're not overusing
03:51    memory resources and you're building strings
03:55    in the most efficient way possible.
Collapse this transcript
Parsing strings as numbers
00:00    - So far, I've dealt with string,
00:02    and number, data types.
00:04    Now, I'm going to talk about how to convert them,
00:07    taking a string, and turning it into a number.
00:10    I'll start, by declaring a string variable,
00:12    that I'll name, just s, for string.
00:15    I'll give it a value of 255.
00:19    String literals are always wrapped in double quotes.
00:23    Next, I'll declare an integer.
00:25    I'll name it, intFromString.
00:28    The process of turning a string into a number
00:30    is called parsing.
00:32    Each of the .NET data type structures,
00:34    that represents one of the numeric values,
00:37    has a set of parse methods.
00:40    I'll use the Int32 class.
00:43    I'll call its Parse method,
00:45    and I'll pass in the string.
00:47    Then, I'll call my Output method.
00:50    I'll pass in a literal string
00:51    of "Value of intFromString",
00:55    and I'll append the variable.
01:00    I'll run the code.
01:02    By doing this, I'm actually turning this
01:04    back into a string.
01:07    Let's try a mathematical operation on it,
01:09    to verify that I really have a number.
01:12    I'll create another integer variable,
01:14    that I'll call doubled.
01:16    I'll calculate the value by multiplying
01:18    intFromString by 2.
01:21    Once again, I'll call my Output method,
01:24    and verify the result.
01:26    I've successfully taken a string value,
01:29    and converted it, or parsed it,
01:31    into a numeric value.
01:33    You can do the same sort of thing with doubles,
01:36    floats, and other numeric data types.
01:39    Let's create another string, that I'll call, s2.
01:42    I'll give it a value of "19.99".
01:46    If I try to parse that as an integer,
01:49    it won't work.
01:50    This number has a fractional value.
01:53    But instead,
01:54    I'll create a double value, and I'll name it,
01:57    doubleFromString.
01:59    I'll get its value, by calling the Double structure,
02:03    and its Parse method,
02:05    and I'll pass in s2.
02:08    Then, I'll Output the result,
02:11    starting with the label of "Value of doubleFromString,"
02:15    and I'll append doubleFromString.
02:18    I see that I'm converting the string
02:20    to a number, successfully.
02:22    There are times when you can
02:23    run into trouble with this.
02:26    For example, what would happen
02:28    if I added some alphabetical characters
02:31    to the end of this numeric value?
02:34    I'll run that code again,
02:35    and click the Go! button.
02:38    This time, I'm causing an Exception.
02:42    I'm getting a FormatException.
02:44    Visual Studio stops the code,
02:46    pauses the application,
02:48    and takes me into the Debugger.
02:51    Now, we haven't dealt with debugging yet,
02:53    so I'm going to skip that process, for the moment.
02:56    I'm going to Stop the application.
02:59    I'll click the Stop Debugging button, up here,
03:01    or you can press shift + F5 to do the same thing.
03:05    I'll change the nature of this code a bit.
03:07    Each of the numeric data type structures
03:10    also has a method, called TryParse.
03:14    The goal of the TryParse method
03:16    is to do exactly what it says.
03:19    Try parsing the value.
03:21    If it's successful,
03:22    it'll convert the value for you.
03:24    If not, it'll return a false,
03:27    and tell you that it didn't work.
03:30    Here's how this works.
03:31    First of all, I'm going to comment out this code.
03:35    I'll select those lines, and then choose Edit,
03:38    Advanced, Comment Selection.
03:41    Then, I'll declare a variable that I'll name, double.
03:45    I'll call it, doubleFromString, again.
03:48    But, this time, I won't initialize it at all.
03:51    I'll just declare it, for the moment.
03:54    Then, I'll use an if statement.
03:57    I'll type the word, if, lowercase,
04:00    and then press the tab key a couple of times.
04:04    That creates the if statement template.
04:07    An if statement evaluates a Boolean expression,
04:11    an expression that returns true or false.
04:14    If it finds a true condition,
04:16    it then executes the code.
04:18    I'm going to replace the word, true,
04:20    with the following expression:
04:23    Double.TryParse.
04:26    There are a couple of different versions of this method,
04:28    and I'm going to use the first one.
04:31    I'll pass in s2, the string I'm trying to parse,
04:36    and then the keyword, out,
04:38    and then the name of the variable
04:40    that I want to set when I call the method.
04:43    I'll be sure to put in the closing parenthesis at the end.
04:46    I don't need a semicolon,
04:47    because this isn't a finished statement.
04:50    Then, I'll move the cursor within the braces.
04:54    Within the braces,
04:55    I can assume that the parsing was successful.
04:59    I'll go get this Output statement,
05:02    and I'll paste it down here.
05:04    I'll remove the slashes, the comments,
05:07    and then close up the code.
05:10    Then, I'll put in an else clause.
05:13    In an if-else clause,
05:15    the else section will execute
05:17    if the condition is false.
05:20    Here, I'll output the string,
05:22    "Couldn't parse the value!"
05:25    I'll try the code.
05:26    I get back, "Couldn't parse the value!"
05:29    Then, I'll go back up here,
05:31    to where I've declared the string,
05:33    and I'll remove those alphabetical characters.
05:36    I'll run the code again.
05:40    Now, I'm successfully parsing the string,
05:42    and turning it into a double value.
05:45    That's parsing.
05:47    Again, each of the numeric data type structures
05:50    has a Parse method and a TryParse method.
05:54    If you know, for sure, that your string can be parsed,
05:57    use the the Parse method.
05:58    But, if you're in a condition
06:00    where it might be pars-able as a number,
06:02    and it might not be,
06:04    declare the variable you want to set, first.
06:07    Then, call TryParse.
06:09    It'll return a Boolean value, a true or a false.
06:12    If you get back true,
06:14    then your variable will have been set.
06:16    If you get back false,
06:18    you can handle it however you need to.
Collapse this transcript
Using mathematical operators
00:00    - An operator, in a programming language,
00:03    is a character or set of characters
00:05    that represent an operation of some kind.
00:08    There are mathematical operators, equality operators,
00:13    and a few other different types.
00:15    I'm going to focus here on math operators.
00:18    C-style languages share a common set of operators,
00:22    operators that show up in C, C#,
00:25    Java, JavaScript, and so on,
00:27    and then C# has some of its own operators as well.
00:32    I'll start with the additive and multiplicative operators.
00:36    These operators are the common math operators
00:38    you see in just about every language.
00:41    The plus character for addition,
00:43    the hyphen or minus character for subtraction,
00:46    asterisk and forward slash for multiplying and dividing,
00:49    and the percent character, which is the remainder operator.
00:54    When you put a percent between two values,
00:57    you're dividing the values and returning what's left.
01:00    So, nine remainder two equals one.
01:04    In addition to these, C# also supports the unary operators.
01:09    These are the increment and decrement operators,
01:12    plus plus and minus minus,
01:14    they add or subtract one to the current value,
01:18    and then, the add and assign
01:20    and subtract and assign operators.
01:23    The add and assign and the addition operator,
01:27    the plus character, are both overloaded in C#.
01:31    They're used both for mathematical
01:33    and for string operations.
01:35    When applied to numbers, you're doing mathematical addition.
01:39    When applied to strings, you're doing concatenation,
01:42    appending the strings to each other,
01:45    but the characters you use are the same.
01:47    When dealing with the increment and decrement operators,
01:51    it's important to note that the placement of these operators
01:54    determines when the mathematical operation will occur.
01:58    Here's some example code.
02:00    I've declared a variable named i and set it to 42.
02:04    Then, in a console application,
02:07    I'm outputting the value,
02:09    followed by the ++ increment operator,
02:12    meaning add one.
02:14    By placing the ++ operator after the variable,
02:18    I'm saying, give me the value of the variable,
02:21    then increment it.
02:24    Then notice I'm outputting the value again on the next line.
02:28    Here's what the output would be from these lines of code.
02:32    The first output would show me
02:35    the original value of the variable,
02:37    because the increment operation
02:39    is happening after the output,
02:41    but then the second output would show me
02:43    the new value after incrementing.
02:46    If I take that ++ operator and move it before the variable,
02:51    then the output would be 43 both times,
02:54    because I would have added the value and then output it.
02:59    So, let's turn to Visual Studio again
03:02    and take a look at some actual code.
03:05    I'm working in a project named Math Operators,
03:08    and I've started off with some existing code,
03:11    where I've declared two double values,
03:13    named value1 and value2.
03:16    I'll go to each of these output statements,
03:19    and I'll add + and then a pair of parentheses,
03:24    and within those parentheses,
03:25    I'll execute a mathematical operation.
03:29    For add, I'll use value1 + value 2.
03:33    I'll run that bit of code, to make sure it's working okay,
03:37    and I see that the sum of the two values is 54.
03:41    Now, I'll copy this bit of code
03:44    and paste it into the four other output calls,
03:48    and then I'll change the operator for each one.
03:52    I'll use the hyphen for subtraction,
03:54    the forward slash for division,
03:57    the asterisk for multiplication,
03:59    and the percent character to get the remainder,
04:03    and I'll run the code.
04:05    And there's the result.
04:08    Next, I'll demonstrate the increment
04:10    and decrement operators.
04:13    I'll place the cursor at the end of the code,
04:16    and I'll say value1 ++.
04:20    Then I'll call my output method,
04:22    and I'll output New value1 and then value1.
04:29    And after incrementing, the new value is 43.
04:34    Then I'll demonstrate the importance of the position
04:37    of the increment or decrement operators.
04:40    I'll call my output method and pass in a label,
04:44    and then I'll append to that value2 minus minus.
04:49    Now remember, value2 starts at 12,
04:53    and then I'll output again,
04:55    and the label will be New value of value2.
05:01    And notice that I get the original value
05:03    in the first statement and the new value in the second.
05:08    But if I take that minus minus operator and move it,
05:11    so that it's placed before the variable,
05:14    then I'm saying, do the mathematical operation
05:17    and then give me the result,
05:21    and I see the value 11 in both positions.
05:25    So, those are the standard mathematical operators
05:27    that are available in C#.
05:30    The standard adding, subtracting,
05:32    multiplying, and dividing, the remainder operator,
05:35    and the increment and decrement operators.
Collapse this transcript
Working with Boolean values and expressions
00:00    - A Boolean expression in C#
00:02    is an expression that returns true or false.
00:06    The words true and false are keywords in C#.
00:10    They're always spelled all lower case.
00:13    To represent a Boolean value as a variable,
00:16    you'll create an instance of the Boolean Structure.
00:20    It can be represented in your C# code
00:23    by the C# alias, bool, B-O-O-L, all lower case.
00:30    If you create a Boolean value by instantiating it
00:33    with the Boolean Structure's constructor method,
00:36    as seen here, the default value will be false,
00:40    and as I described previously in this course,
00:44    a Boolean value does not have an equivalent numeric value,
00:47    as it does in some other languages.
00:50    In order to construct more complex Boolean expressions,
00:54    C# supports common equality operators.
00:58    The double equals operator compares two values,
01:01    and if they're equivalent, it returns true,
01:04    and if they're not equivalent, it returns false.
01:08    When you use these with numeric values,
01:10    integers, doubles, and so on,
01:13    you're comparing the values to each other,
01:15    but when you use the double equals operator with objects,
01:19    that is, instances of structures or classes,
01:23    most of the time you're asking the question,
01:26    do these two variables point to the same object,
01:29    not do the objects have the same value.
01:33    There's an important exception to this rule,
01:35    but I'll get to that in a moment.
01:37    The opposite of the equals operator,
01:40    that's the double equals character set,
01:42    is exclamation equals, or not equals.
01:46    If you take two values
01:48    and you compare them to each other with this operator,
01:52    if they aren't equal, you get back true,
01:54    and if they are equal, you get back false.
01:58    And then, there's the negation operator.
02:01    You can place this before any other Boolean value,
02:05    and it will reverse the value.
02:07    If it was true, now you'll get false,
02:10    and if it was false, now you'll get true.
02:13    Again, those are standard operators
02:15    that you see in all C-based languages.
02:19    The next two operators also occur in all C-style languages,
02:23    the double ampersand, which is the and operator,
02:27    and the double pipe character, which is the or operator.
02:31    If you wrap the double ampersand into Boolean values,
02:35    they both have to be true in order to get back true.
02:38    If either or both are false, you get back false,
02:42    and the or operator does what it says.
02:45    Only one of these values has to be true
02:47    to get back a true value.
02:50    The double question mark is a special operator in C#.
02:55    It doesn't occur, say, in Java.
02:56    It's called the Null-coalescing operator.
03:00    It examines the first value,
03:02    the value on the left side of the operator,
03:05    and asks whether it's null.
03:07    If the value isn't null, it returns that value,
03:11    and if it is null, then it returns
03:13    the value on the right side of the operator.
03:16    Again, this is unique to C#.
03:19    There are also standard relational
03:21    and type-testing operators.
03:23    The less than and greater than symbols
03:26    and the less than or equals
03:27    and greater than or equals symbols.
03:29    These are standard across languages.
03:32    C# also supports an operator called is.
03:36    It checks for type compatibility.
03:39    So, if you have a variable,
03:41    you can ask whether this variable is compatible
03:44    with a particular class or structure.
03:48    Now, back to those exceptions to equality testing.
03:53    A string is a class, not a structure,
03:56    but in comparing strings, it behaves,
03:59    for the most part, like a structure.
04:01    That is, you're comparing the values of the strings.
04:04    The compiler's doing some special tricks
04:06    in the background with strings to make this work.
04:10    So, even though a string is a class, not a structure,
04:14    the double equals looks at the values of two strings
04:17    and not whether they point to the same object.
04:21    The following two if conditions are the same.
04:25    You can either compare strings with the equals method,
04:29    or you can use the double equals operator.
04:32    Either way, you're doing a case-sensitive comparison
04:35    of the two strings.
04:38    Now, if you want to do a case-insensitive comparison,
04:42    you can't use the double equals operator.
04:44    That's always case-sensitive.
04:46    But you can do non-case-sensitive comparisons
04:50    using the equals method, by passing in a second argument,
04:54    and the second argument would be a constant named
04:58    StringComparison.OrdinalIgnoreCase.
05:02    You'll see in the documentation
05:04    that there are some other options for this,
05:06    but this is the one that's been recommended since .NET 2.0.
05:11    So, for case-sensitive string comparisons,
05:14    you can use either the double equals operator
05:16    or the equals method, just passing in the second string,
05:20    and for non-case-sensitive comparisons,
05:23    use the equals method and passing a second argument
05:27    of OrdinalIgnoreCase.
Collapse this transcript
Using constants and enumerations
00:00    - So far I've focused on declaring variables within methods.
00:04    When you declare a variable within a method
00:06    it's local to that method but when you declare it
00:10    outside the method as a part of the class itself
00:13    it becomes either a Field or a Constant.
00:16    I'm going to focus on Constants here.
00:20    A Constant is a value that never changes
00:23    after it's been initialized.
00:25    We use Constants to represent values
00:27    that stay the same for the life time
00:29    of the application.
00:31    And again their typically declared
00:32    as members of classes or structures.
00:37    I'll demonstrate this in the Project ConstsAndEnums.sin
00:41    I'll place the cursor inside the class
00:43    and make a little bit of extra space.
00:46    Then I'll start with key word Const.
00:49    By placing this before a variable declaration
00:52    you're saying this value can't change
00:55    once it's been initially set.
00:58    Then I'll put in the Data Type and the Identifier.
01:03    The Identifier or the name of the constant
01:05    follows Pascal Casing.
01:07    So you typically start with an
01:09    uppercase character and then use
01:11    camel casing for the rest.
01:15    I'll name my Constant Meaning of Life
01:18    and I'll give it a value of 42.
01:21    Now this constant is available any where in the class.
01:25    So I can refer to it in my Run Code Method.
01:29    I'll call my output method and I'll pass in
01:32    a string of the Meaning of Life is
01:36    and then I will append the value 42.
01:40    And I'll run the code.
01:42    And I'll test it.
01:43    And show that I can access that value
01:45    from within the method.
01:48    To make a constant publicly available
01:50    for the entire application
01:52    just add the keyword public before
01:54    the const keyword.
01:56    And now this constant is available
01:58    to the entire application as a member of this class.
02:03    So that's Constants.
02:04    They make it easy to declare values
02:06    that will never change and you can give
02:08    the identifier something meaningful.
02:11    So that it's easy to remember and
02:13    easy to type in your code.
02:15    Another architecture that's very helpful to code readability
02:18    and maintainability is called an Enumeration.
02:22    An Enumeration is represented by
02:24    the keyword enum and it's a way
02:26    of declaring a list of available values.
02:30    Where you can choose one of the values from the list.
02:33    For instance I'm going to declare an
02:35    Enumeration named Flavors.
02:38    You start with the keyword enum,
02:40    then the identifier for your Enumeration,
02:44    and then you follow that within the braces
02:46    with a comma delimited list.
02:48    Notice that there's no Assignment Operator here.
02:51    We're not saying Flavors = Chocolate,
02:54    Vanilla, and Strawberry.
02:56    We're saying that this Enumeration contains
02:58    these three possible values.
03:01    Now I'll go down to my method and I'll
03:04    refer to these values starting with flavors
03:07    as the identifier of the Enumeration,
03:10    and then after a doc I'll be able to use
03:12    any of the three declared values.
03:16    So I'll use output again and then I'll say
03:20    my favorite ice cream is,
03:22    and then I'll append a value to that.
03:25    I'll start with the beginning of the Enumeration name.
03:29    I'll type FL and there's the name
03:32    of the Enumeration.
03:33    Then I'll type a period and I see
03:35    the three possible values listed.
03:39    I'll choose Chocolate,
03:40    I'll finish the statement,
03:42    and run the application and there's the result.
03:46    My favorite ice cream is Chocolate.
03:49    Notice that C# automatically
03:51    transforms this value which really is
03:55    and integer in the background into
03:57    it's string equivalent.
03:59    And here's one of the great things you can do.
04:02    Because this is now a identifier name
04:05    you can rename it and all references to it
04:08    will automatically change.
04:10    So I'm going to right click, choose Refactor, Rename,
04:16    and change this to Dark Chocolate.
04:20    Notice that it's changed in both
04:21    the Declaration and into the Reference.
04:24    You can do this sort of renaming on any identifier.
04:28    Changing the names of Methods, Variables,
04:31    Fields, Properties, Enumerations, and Constants.
04:35    And by using Constants and Enumerations
04:38    you can make your code more readable
04:40    and more maintainable.
Collapse this transcript
Working with dates and times
00:00    - So far I've described how to create variables
00:03    that store numbers, booleans,
00:06    characters, and strings.
00:08    Now I'll describe another very common data type:
00:11    the DateTime object.
00:14    A DateTime object is an instance
00:16    of a structure named DateTime,
00:19    and you can store either date and time information,
00:22    or just date information, or just time information.
00:26    I'm working in the project dates and times,
00:29    and I'll start by declaring a DateTime object
00:31    that represents a specific date.
00:34    I'll start with the name of the structure,
00:36    DateTime, and I'll name it dt.
00:40    Then I'll put in the key word new,
00:43    and then I'll use a constructor method
00:46    of this structure.
00:48    After I put in the parentheses, I'm shown
00:50    a list of all the different versions
00:52    of the constructor.
00:54    You can create a DateTime object with a variety
00:57    of bits of information.
00:59    If you pass in six integer values,
01:02    you'll be creating an instance
01:03    of the DateTime structure that's accurate
01:06    down to the second.
01:08    If you pass in three integer values,
01:11    then you're only representing the date.
01:14    I'll pass in three.
01:15    I'll pass in 2014, a one, and a one.
01:20    That's January first, 2014.
01:25    Next I'll output that information,
01:28    and I'll say the date is,
01:31    and then I'll append dt to it
01:34    and I'll run the code.
01:36    When I click go, I see the date is,
01:39    and then I see both the date and a time value.
01:43    I didn't initialize the time,
01:45    so 12 o'clock midnight is the default value
01:48    for the time.
01:50    If I want to format the DateTime value,
01:53    I can use the ToString method
01:55    of the DateTime structure and pass in
01:58    what's called a mask,
01:59    a description of how that DateTime value
02:02    should be formatted.
02:04    I'll put in a dot and a ToString,
02:07    and then within the parentheses
02:09    I'll pass in a literal string.
02:11    I'll pass in an uppercase M for the month,
02:14    a lowercase d for the date,
02:16    and four y's for the year.
02:19    I'll add one more closing parentheses
02:20    to complete the statement and run the code.
02:24    And now I see the version of the date that I want.
02:28    I'll change the mask to something else.
02:31    This time I'll put in four uppercase M's,
02:35    I'll put in a space instead of the slash,
02:38    and then a comma space instead
02:39    of the second slash.
02:42    And now I'm using a fully formatted
02:43    version of the date.
02:45    You can find documentation for all
02:47    the different characters and what they mean
02:50    in the DateTime documentation.
02:53    Let's say that you wanted to create
02:54    a DateTime object that represents
02:57    the current DateTime on the current computer.
03:00    In a desktop application,
03:02    that would be the user's computer.
03:04    In a web-based application, it would be
03:06    the server that's processing the code.
03:10    I'll create another DateTime object
03:12    and I'll name it now all lowercase.
03:16    I'll get this value by calling a property
03:18    of the DateTime class called now.
03:22    Then I'll copy and paste my output code,
03:25    and I'll change the label to now is,
03:29    and I'll change the variable that I'm examining
03:31    to now.ToString.
03:34    I'll run the code, and there's the result.
03:38    That's the day on which I'm recording this course.
03:42    Finally, let's take a look at how to do
03:43    some math with dates, how to add and subtract
03:46    days, months, years, and so on.
03:50    I'll create another variable that I'll call
03:52    another day, and I'll calculate it
03:56    by calling dt.AddDays.
04:00    Notice that there are methods called AddHours,
04:02    AddMilliseconds, Minutes, Months, Ticks, and Years.
04:07    I'll pass in a value of negative one,
04:10    meaning I'm subtracting a day.
04:13    Then once again, I'll paste in my output code
04:17    and I'll change the variable that I'm examining
04:19    to anotherDay, and I'll run the code,
04:23    and the last line now shows me
04:25    December 31st, 2013, one day before
04:29    January first, 2014.
04:32    So those are some tips on getting started
04:34    using the DateTime structure.
04:37    Again, you can store a date, a time,
04:40    or a combination of the date and time
04:42    so you can represent that sort of information
04:45    in your C# application.
Collapse this transcript
5. Managing Application Flow
Getting input in a console application
00:00    - So far in this course the focus has been
00:02    on storing data in memory,
00:04    declaring different types of variables
00:07    and referring to them in your code.
00:09    Next we'll turn to the flow of an application,
00:12    how to control when execution of code happens
00:15    and how to make code execute more than once.
00:19    For this chapter, I'll work in console applications,
00:23    a simpler form of application
00:25    than the WPF applications
00:27    that I've been working on so far.
00:29    I'll start with the solution named ConsoleInput
00:33    and I'll open the Program.cs file.
00:36    This is a starting solution.
00:39    The namespace is ConsoleApp,
00:41    the class is Program
00:43    and the main method is named Main
00:45    with an uppercase M.
00:48    It follows the standard for console applications,
00:51    in that the main method is static and void,
00:54    that is, it doesn't return anything
00:56    and it receives, as an argument, an array of strings.
01:00    The name of that parameter
01:02    can be anything you want.
01:03    Visual Studio sets it as args
01:06    but the critical thing is that
01:08    it does receive an array of strings.
01:10    As long as that main method exists,
01:13    that's where our program will start.
01:14    My first goal is to show you how to get
01:17    some input from the user.
01:19    I'll be using that sort of input
01:20    throughout the rest of this chapter.
01:23    The console class has a method named ReadLine.
01:27    It will allow the user to type anything they want
01:30    and then it will finish when the user presses enter.
01:33    It will then return the value
01:35    that the user typed in as a string.
01:38    I'll create a new variable that I'll call input
01:41    and I'll type it as a string
01:43    and I'll get its value by calling Console.ReadLine.
01:48    Now, this method doesn't receive any arguments.
01:51    You can't pass anything into it
01:53    but, again, it will return whatever the user types in.
01:58    Then out, output the value.
02:00    I could type out Console.WriteLine,
02:04    but here's a shortcut,
02:06    I'll type cw, all lowercase,
02:09    then I'll press tab twice
02:12    and that expands to the full statement
02:15    Console.WriteLine
02:16    and places the cursor between the parentheses.
02:20    I can type in my string "You entered:"
02:24    and then I'll append to that the value input.
02:28    I'll save that change
02:30    and I'll run the application.
02:32    Now, I'm going to run the application
02:33    by pressing control F5.
02:36    That means run it without debugging
02:38    and that will cause the application
02:40    to pause for a moment
02:42    after it's finished executing
02:44    and I can see the results on the screen.
02:46    I'll type a value, I like chocolate,
02:50    and I'll press enter and I get back the response
02:54    You entered: I like chocolate.
02:57    The console class has a couple of other
02:59    read methods such as the ReadKey method
03:01    that only waits for a single character
03:04    but this is the one that's most useful to us
03:06    in putting together simple console applications.
03:10    Now that we know how to get
03:12    some input from the user,
03:14    next, we'll take a look at how to evaluate it
03:17    using if statements and switch statements.
03:19    The two most common approaches
03:21    to creating conditional code blocks.
Collapse this transcript
Evaluating conditions with if and else
00:00    - One of the most common tasks
00:01    you have to do as a programmer
00:03    is to decide when to execute certain bits of code
00:06    and when to ignore it.
00:08    C# supports a number of conditional statements,
00:12    statements you can use to evaluate conditions
00:15    and then decide whether to execute a bit of code.
00:19    I'll start with the if and else keywords
00:22    which you can use in different combinations
00:24    to evaluate various conditions.
00:27    I'm working in the if else solution,
00:29    and I'll start in the program class.
00:32    This is a console app.
00:33    First I'll get some input from the user.
00:37    I'll create a string variable named input,
00:40    and I'll get its value with Console.ReadLine.
00:43    Now I'll evaluate it.
00:46    I'll start with the if keyword.
00:49    I'll type if and press tab twice to insert a code snippet.
00:54    The if keyword is followed by a pair of parentheses,
00:58    and then within the parentheses
00:59    you place a Boolean expression, an expression that equates
01:03    to either true or false.
01:05    To evaluate this string, I'll use its equals method,
01:09    and I'll pass in a literal string of "Hello".
01:13    So now, if that expression is true,
01:15    then all the code within the braces will be executed.
01:19    And I'll put a literal string to the console.
01:22    I typed CW and pressed tab twice
01:25    to bring in the Console.WriteLine snippet,
01:28    and I'll output, "You said hello!"
01:32    Next I'll add in an alternative output.
01:35    I'll put in an else statement.
01:38    I'll type else and press tab twice,
01:41    and then within the code block
01:43    I'll output, "You said something else!"
01:46    I'll save my changes and run the code,
01:49    and I'll make sure to run with Control-F5
01:51    so that the application will pause when it's finished.
01:55    I'll type Hello and press enter,
01:58    and I get back the confirmation,
02:00    "You said hello!"
02:01    Now I'll run it again and I'll type something else,
02:06    and I get, "You said something else!"
02:08    It's worth remembering that the equals method
02:11    of the string class does a case sensitive comparison.
02:16    So if I run the application and type in hello all lowercase,
02:19    I get back, You said something else!"
02:23    To make this a non-case sensitive comparison,
02:26    add in another argument to the equals method
02:29    as I described earlier in the course.
02:32    I'll open up the editor to full screen
02:34    with alt + shift + enter.
02:36    Then I'll pass in
02:37    StringComparison.OrdinalIgnoreCase.
02:41    I'll run that code.
02:44    I'll type in hello all lowercase,
02:47    and this time it says I typed in the expected string.
02:51    In addition to the if and else clauses,
02:53    you can also add in as many else ifs as you want.
02:58    This lets you evaluate specific conditions
03:00    in addition to the first one.
03:03    The else if clause goes after the initial if
03:06    and before the else.
03:08    I'll type else if separated by a space
03:11    and press tab twice,
03:13    and just like the if keyword on its own,
03:15    I'm asked for a Boolean expression.
03:18    I'll come up here an grab this one
03:20    because it worked pretty well,
03:22    and I'll copy it to the clipboard.
03:24    Then I'll go down here and replace the keyword true
03:27    with that expression.
03:30    And in this version, I'll replace the string
03:32    I'm looking for changing it from hello to Goodbye.
03:37    Then I'll output to the console,
03:39    and I'll say, "You said goodbye!"
03:42    I'll save my changes and run the application.
03:46    In typing the code, I missed a closing parenthesis
03:50    so I'll fix that up.
03:51    Then I'll run the application again.
03:54    I'll type hello, and I get, "You said hello!"
03:58    I'll run it again and type goodbye,
04:01    and I get, "You said goodbye!"
04:04    Finally, I'll type in something else entirely,
04:08    and I get, "You said something else!"
04:11    You can add as many else ifs as you need,
04:14    and again it goes after the initial if
04:17    and before the else.
04:19    The else if and else clauses are completely optional.
04:23    You don't have to use them,
04:25    but they're useful ways to evaluate conditions
04:27    in addition to the initial if statement.
Collapse this transcript
Evaluating conditions with switch statements
00:00    - I've already described how to use the if and else
00:03    keywords to evaluate conditions
00:06    and execute conditional code.
00:09    Next I'll show you how to use the switch statement,
00:11    another conditional code construct designed to
00:15    evaluate an expression and then look for specific
00:19    values that it would match.
00:22    I'm working in the project Switch,
00:24    and it already has code to get some information
00:27    from the user.
00:28    There's a prompt that says, "Enter an operation"
00:31    and then it offers four possibilities.
00:34    The four mathematical operators for addition, subtraction,
00:38    multiplication and division.
00:40    Then the ReadLine method collects data from the user
00:44    and stores it in the variable named operation.
00:48    My goal is to evaluate that variable.
00:52    I'll start with the keyword switch,
00:54    then I'll press Tab twice,
00:56    and that fills out the code snippet for that keyword.
01:00    Place the expression you want to evaluate
01:02    inside the parentheses.
01:04    That'll be operation.
01:07    When I moved the cursor off that line,
01:09    that completed the snippet, adding the keyword break
01:12    after the word default.
01:15    I'll get to what default means in a moment,
01:17    but first, I'll talk about how to evaluate
01:20    the different possible values.
01:23    For each value, add the keyword case
01:27    and then the value you're looking for.
01:30    I'll put in the plus character wrapped in double quotes.
01:33    Even though it's a single character,
01:35    I'm dealing with it as a string.
01:38    If the operation variable matches that string
01:41    then any code I place after this case will be executed.
01:46    For now, I'm just going to write some information
01:49    to the screen you chose to add.
01:52    You can add as many lines of code here as you want to
01:55    and they'll be executed one line after the other,
01:58    but at the end, be sure to add the keyword break.
02:02    That means, jump to the end of the current code block.
02:07    In this case, the code block is owned by
02:09    the switch statement itself, and that will ensure
02:12    that you don't continue on to execute everything
02:15    that's below it within that code block.
02:18    Now, I'll copy those lines of code
02:21    and I'll past them in three times,
02:23    and I'll fill out the other possibilities.
02:27    I'll put in a minus,
02:29    and then I'll change this one to subtract.
02:32    This one will be an asterisk,
02:35    and this will be multiply.
02:38    And finally, a forward slash,
02:40    and this one will be for division.
02:43    So for each case, I look for the value,
02:46    then I take an action and then I call the break keyword.
02:50    And again, that means jump to the end of the code block.
02:54    The default statement is where you put code to execute
02:57    if none of the case statements match the value.
03:01    So, I'll add code here and I'll output the string,
03:05    "No such operation".
03:08    And now I'm ready to test my application.
03:11    I'll press ctrl + F5, I'll enter an asterisk,
03:16    I'll press Enter and I get back "You chose to multiply".
03:20    I'll test another of these cases.
03:22    This time I'll put in a plus character,
03:25    and I get back, "You chose to add".
03:27    And I'll run it one more time,
03:30    and this time I'll put in a percent character,
03:32    which is a valid C# operator,
03:35    but which I haven't handled in my code.
03:38    And I get back, "No such operation".
03:42    So that's the switch statement.
03:44    The switch statement lets you evaluate an expression
03:47    and then match it up with its possible values.
03:50    Typically, you use a switch statement
03:53    where you have a finite set of values you're looking for
03:56    or an if and else statement if you need more flexibility.
Collapse this transcript
Looping with for statements
00:00    - Most programming languages give you a way
00:02    of repeating a set of statements many times
00:05    using looping constructs.
00:08    You might loop through some commands a fixed number of times
00:11    or you might have a collection of data items
00:14    and you might want to deal with each one of those data items
00:17    one at a time.
00:18    Either way, you would need a loop.
00:21    There are a few different looping construct in C#.
00:25    I'll start with the simplest; the for loop.
00:28    I'm working in a project named ForLoop
00:31    and I'll start with a cursor above this statement
00:33    that's creating an array.
00:36    I'll start with a simple for loop
00:38    that iterates a fixed number of times.
00:41    To create a for loop, type the word for and press tab twice.
00:46    That brings in the code snippet for the for loop.
00:50    A for loop has a three-part statement
00:52    inside a pair of parenthesis.
00:55    The first part is called the initializer,
00:58    the second is the condition,
00:59    and the third is the iterator.
01:03    The initializer starts by declaring a variable.
01:06    It's right here.
01:08    Typically, this is an integer,
01:09    but it can really be anything you want.
01:12    And because it's declared within the for loop,
01:14    its lifetime will expire when the for loop is done.
01:18    When you create a for loop using the code snippet,
01:21    the initializer sets the variable at zero.
01:25    That's because indexing in C# starts at zero.
01:29    For example, if you have an array of three items,
01:32    their indexes are at zero, one, and two,
01:35    not at one, two, and three.
01:37    But it's also very common to want to start counting at one.
01:41    For this first for loop,
01:44    I'll change my initializer to set value i to one.
01:48    Next, is the conditional statement.
01:51    This is a Boolean expression.
01:53    It returns true or false.
01:55    If it returns true, that means execute the statement again
01:59    and if it returns false, that means finish the statement.
02:03    Jump to the next statement after the code block.
02:07    This value can be anything you want.
02:10    I'm going to set it to 11.
02:14    Next is the iterator.
02:15    This is a statement that's executed after each loop
02:19    and typically, you just increment the variable by one.
02:23    But again, it could be anything you like.
02:25    You could implement by a larger value.
02:28    You could decrement to walk backward through a set of data
02:31    or do any other iterating operation you want
02:34    to control your loop.
02:36    Now within the loop, I'll add in some console output.
02:40    I'll start with a literal string of Number
02:44    and then I'll append the index or countervariable i.
02:48    I'll run that code using ctrl + f5,
02:52    and there's the result.
02:53    I'm iterating over this statement, executing it repeatedly
02:58    until the conditional statement,
03:00    that's the second part of the for statement,
03:03    returns a false value.
03:05    Then, I jump past the for loop and I continue
03:08    executing the rest of the program.
03:10    Here's another way to use a for loop,
03:13    this time, on a collection of data.
03:15    I've declared an array of strings.
03:18    I've name it fruit and I've assigned it three items.
03:22    You declare an array in C#
03:24    by declaring the data type of the items in the array
03:28    and following that with a pair of brackets.
03:31    Then, the actual array is initialized using a pair of braces
03:35    and a comma-delimited list.
03:37    Now, I'll loop through this array.
03:41    Once again, I'll bring in a for loop.
03:43    Notice that I'm re-using the variable i.
03:46    Because the original variable i expired
03:49    when this for loop was finished,
03:51    I can re-use the variable name here.
03:54    Next, to control the number of times I execute my loop,
03:57    I'll use the expression fruit.Length.
04:02    Length is a property of the array.
04:04    It returns the number of items in the array,
04:07    in this case, three.
04:09    So that means I'll keep looping
04:11    as long as i is less than the length.
04:14    I'll be able to iterate with indexes zero, one, and two.
04:18    But if I get to three, that means,
04:21    there's no such index in the array.
04:23    Within the array, I'll once again use some console output
04:27    and I'll refer to the item in the array
04:31    using the name of the array, fruit,
04:34    and then I'll put in the index variable wrapped in brackets.
04:38    I'll save and run the code,
04:41    and there's the result.
04:42    I'm outputting the items in the array.
04:46    Now again, I can control the iteration.
04:49    For example, if I wanted to walk backward through the array,
04:53    I could set i to the length of the array.
04:56    I could keep looping as long as i is at least zero.
05:00    And then I would use a decrement operator
05:02    and I'd walk backward through the array that way.
05:06    Try it if you like in your own code.
05:08    That's how you use the for loop.
05:11    You can either loop a fixed number of times
05:14    or you can look at the number of items
05:16    you want to loop through
05:17    and use that in your conditional statement.
Collapse this transcript
Looping with while and do statements
00:00    - The next looping construct I'm going to describe
00:02    is called a while loop.
00:04    There are a couple of forms of it;
00:06    a simple while loop and a do-while loop.
00:10    The while loop examines a condition
00:12    and keeps looping as long as that condition is true.
00:16    It's different from a for loop
00:18    in that it doesn't have iteration built in.
00:21    You can use iteration if you want to, though.
00:24    I'm working in the project WhileLoop
00:27    and I'll start by declaring a couple of integer variables.
00:31    The first one will be named counter
00:33    and it'll be set to one.
00:36    And the second one would be called maximum,
00:38    and it'll be set to 10.
00:41    Next, I'll set up a while loop.
00:43    I'll type the word while and press tab twice.
00:47    Just like with the for loop,
00:49    I'm starting with a code snippet.
00:51    The code snippet for a while loop is simpler though.
00:54    It's just looking for a Boolean expression.
00:57    My expression would be counter <= maximum.
01:03    Now, I can put any code I want to
01:05    within the while loop's code block
01:08    and that code will be executed
01:10    as long as that expression remains true.
01:13    I'll use console output
01:15    and I'll start with a literal string of "Loop number"
01:19    and I'll append the counter variable.
01:22    Now, if that's all I did, I would create an infinite loop.
01:26    I haven't put any code in that would change
01:29    that expression from being true.
01:32    So it's up to me as the programmer
01:34    to make sure I put in logic
01:36    that will change the condition somehow.
01:39    And I'll do that by incrementing the counter variable by one
01:42    with counter++.
01:45    I'll run that code and there's the result.
01:48    I'm looping 10 times, starting from one,
01:51    the beginning number, and going through 10, the maximum.
01:55    Now you can evaluate any Boolean expression you like.
01:59    I'm comparing two numbers to each other,
02:02    but any expression that returns a true or false
02:05    can be used with a while loop.
02:08    I'll demonstrate this with a collection of data.
02:11    This time, my collection will start with a string.
02:14    I'll name it welcome and I'll set it to "Hello world."
02:18    I'm going to treat this string
02:19    as a collection of characters.
02:22    I'll start by resetting my counter variable
02:25    and this time, I'll set it to zero.
02:28    Then, I'll use a while statement
02:30    and I'll set my expression to counter < welcome.Length.
02:36    You can use this sort of code with an array, a list,
02:39    or other kinds of collections.
02:41    I'm looking at the length property of the welcome string.
02:45    It tells me how many characters there are in that string.
02:49    Then within the loop, I'll do some console output.
02:54    I'll output the character at that position of the string
02:58    with [counter].
03:02    This syntax treats the string as though it were an array,
03:05    an array of characters.
03:08    Then once again, after I've executed that statement,
03:12    I'll increment the counter variable and I'll run that code.
03:17    I see after the looping, one through 10,
03:21    then I'm not outputting the string, "Hello world"
03:23    one character on one line at a time.
03:27    Finally, I'll show you how to use the do-while loop.
03:31    A do-while loop can be used when you want to put
03:34    the evaluation of a condition at the end of the loop
03:38    instead of at the beginning.
03:41    Start with the word do, press tab twice,
03:44    and you'll see that the while statement is placed
03:47    after the do code block.
03:50    Now, I'll take the code from the original while loop,
03:53    I'll select it, copy it,
03:56    and paste it into the do loop.
03:59    I'll also take the initialization code,
04:02    that's setting counter to zero,
04:04    and I'll paste that here as well.
04:07    Then I'll go to my while statement
04:09    and I'll set the expression to
04:11    the same expression that I used before also.
04:15    Now, I'm saying, start at the counter value of zero,
04:19    write the output, increment the counter,
04:22    and then evaluate the condition.
04:25    If the Boolean expression returns false,
04:28    I won't go back to the do statement again,
04:30    I'll just continue on with the rest of the application
04:33    or if that's the end of the application,
04:36    I'll finish and exit.
04:39    I'll run that code and now see that I'm
04:41    outputting "Hello world" twice.
04:43    One's for the simple while loop
04:45    and one's for the do-while loop.
04:48    Now we've looked at a few different ways of
04:50    looping through content using the for loop, the while loop,
04:54    and the do-while.
04:56    And I have one more looping construct to show you
04:59    called foreach, and I'll show you that in the next video.
Collapse this transcript
Looping with foreach and in
00:00    - The last looping construct
00:01    I'll describe is called foreach.
00:05    The foreach keyword let's you define a loop
00:08    with a collection of data
00:10    and you'll deal with each item
00:12    in the data collection one at a time.
00:15    To demonstrate this I'm working in the foreach project
00:18    and I've declared an array of strings named fruit.
00:22    Below that line of code I'll type foreach
00:25    and press tab twice
00:27    and that brings in the code snippet
00:29    for this keyword.
00:31    The foreach expression let's you declare a variable.
00:35    The variable represents the current item
00:38    in the collection you're working with.
00:40    My collection is my array of strings named fruit.
00:45    You can name the variable anything you want.
00:48    By default this expression
00:50    is using implicit data typing
00:53    using the var keyword.
00:55    The assumption is that the data type is declared
00:58    as part of the collection itself.
01:00    In this case each item will be a string.
01:04    Within the foreach loop you can
01:06    deal with that variable
01:08    and the variables availability will expire
01:11    when the foreach loop completes.
01:14    Within the foreach loop
01:16    I'll do some console output
01:18    and I'll output the item.
01:21    I'll save and run the code.
01:23    And there's the result.
01:25    I'm outputting the items one at a time.
01:30    If I add an item to the list,
01:32    I'll add Avocados
01:34    and then run the code again,
01:36    the foreach loop now deals with four items
01:39    instead of three.
01:42    The foreach loop is an incredibly convenient way
01:44    of dealing with each item in a collection
01:47    when you don't care about the order
01:49    in which you're dealing with it.
01:51    If you're dealing with an ordered collection of data
01:54    you should see the items processed in their correct order
01:57    but if you're dealing with an unordered collection,
02:00    say items that are stored in what's called a dictionary
02:04    which would be a hash table in some other languages,
02:07    the order of those items is not guaranteed.
02:10    But the foreach construct lets you loop
02:13    with a small amount of code.
02:15    It lets you deal with each item in a collection of data
02:18    without having to worry about index numbers
02:21    or other aspects or for loops and while loops.
Collapse this transcript
Creating reusable code with methods
00:00    - So far most of the code that I've been executing
00:02    has been within a single method.
00:04    Either the main method what I've been working
00:07    in a console application or in a method
00:10    that's triggered by a user clicking a button.
00:12    In a visual application built with
00:15    widows presentation foundation.
00:18    But as an application gets more complex
00:20    or as you create code that you want to comb
00:23    more than once you need a way of organizing your code
00:26    into reusable snippets.
00:29    Those snippets get placed into methods.
00:33    Just like the main method, but methods
00:35    that you create and name yourself.
00:38    I'll call these custom methods.
00:40    Custom Methods can either be static
00:43    or they can be what we call Instance Methods.
00:47    If you're working within Static Code
00:49    such as within this Main Method
00:52    and you want to call other code within the same class
00:55    that code also has to be in a static method.
00:59    I'll talk about Instance Methods later on
01:01    when we talk about creating your own custom classes.
01:05    But for now all the methods I'm about
01:08    to create will be marked as static
01:10    to make them usable from the Main Method.
01:12    I'm working in the project Custom Methods,
01:15    and I've already declared a couple of Constants
01:18    named Value1 and Value2, both Data Tactic Integers
01:23    with one set of 12 and the other at 24.
01:27    Now before I start adding code into the Main Method
01:31    I'll go down here after the main method
01:34    and I'll create a new Custom Method.
01:36    I'll start with the keyword static
01:39    and then I'll indicate what type of data
01:42    this method will return because I'll be
01:45    working with two Integer Values,
01:47    I'll say that I'll be returning an Integer.
01:50    I can name the Method anything I want
01:53    but I should use Pascal Casing.
01:55    That means I start with a uppercase A
01:58    and then use mixed case for the rest
01:59    of the method name.
02:01    A method can have parameters also known
02:04    as arguments, and these are set
02:07    with a Data Type and a name.
02:10    My Add Method will receive two parameters
02:12    both integers.
02:14    So I'll declare the Data Type for the first one,
02:17    and set the name as Value1 and the Data Type
02:21    for the second one and set that as Value2.
02:25    Because these are local variables they have
02:27    an initial lowercase character
02:30    following Microsoft Conventions
02:32    for variable naming in C#.
02:35    That's called the Method Signature.
02:37    It includes the static key word if necessary,
02:41    a return Data Type, and the name of the Method,
02:45    and then within the parentheses
02:47    any parameters you want to pass in.
02:49    I indicated that this method would be returning
02:52    data with this Data Type Declaration.
02:55    So I have to return something,
02:58    and I'll do that with the return keyword.
03:00    And then I'll add an expression of Value1 plus Value2.
03:06    And now my add method is ready to use.
03:09    Next I'll go up to the Main Method.
03:12    I'll create a variable Data Typed as an Integer.
03:15    I'll set its name as Total and I'll assign
03:19    it by calling my Add Method.
03:22    Notice that when I start typing the name
03:23    of the Method it's listed in the Available Methods.
03:27    I'll put in the parentheses and
03:29    Visual Studio shows me the Method Signature.
03:32    It's expecting two Integer Values,
03:36    and I'll pass in my Constants Value1 and Value2.
03:41    Next I'll output my total to the screen starting with
03:45    a string, total and depending, the variable.
03:50    I'l save and run the code and there's the result.
03:54    The total is 36.
03:58    So that's one way to create methods
03:59    that return values, but you can also
04:03    create methods that affect values
04:05    that are passed in by reference.
04:07    That is, you declare a Variable in your main scope,
04:11    and then you pass it in and you
04:13    let that method effect the variable
04:15    instead of returning it.
04:18    This is just a different style of coding,
04:20    and its one that you don't have
04:21    to use in your own code, but it's useful
04:24    to know it can be done because you'll see
04:26    it used in parts of the C# Libraries.
04:31    I'm going to create a second method down here.
04:34    Once again it'll be static, but this time
04:37    it's not going to return anything.
04:39    And in order to indicate that, I'll use the keyword void.
04:43    That means this is a method that does
04:45    something but doesn't return any values.
04:49    I'll name this method add to OutParam.
04:53    And I'll declare it with three parameters or arguments.
04:58    The first two will be the same arguments
04:59    I passed into the add method.
05:01    Value1 and Value2, but the third
05:05    parameter will be special.
05:08    I'll start with the keyword out.
05:10    That means I'm expecting an argument
05:13    that's being passed in by reference and I'll be
05:16    effecting it within this method.
05:19    Then I'll declare the Data Type
05:22    and then I'll give it a name, Result.
05:25    Now within the method I'll execute
05:27    the same mathematical operation addition.
05:30    But instead of returning it from the method
05:32    I'll just assign the result of
05:35    the mathematical operation to the out parameter.
05:39    Now I'll show you how to use that Method.
05:42    I'll go back up here to the Main Method
05:45    and I'll declare a local variable in Main
05:47    that I'll call result, and then I'll call
05:50    the new method add to OutParam.
05:54    I'll once again pass in my two contants
05:57    Value1 and Value2.
06:00    And then then when I pass in the variable
06:02    that I want to be changed, I'll start once
06:04    again with the out keyword
06:06    and then the name of the variable.
06:10    Notice that I have to use the out keyword in both places.
06:15    In the method signature, when I declare the method,
06:18    and when I use the method passing
06:20    the variable into it.
06:23    Then I'll display the results.
06:25    With the answer is and then the
06:28    name of the variable result.
06:30    I'll run the code, and I see that the result
06:33    is exactly the same, but the way I've organized
06:37    my code is a little bit different.
06:39    It's up to you whether you use
06:41    conventional methods that return values
06:44    or methods that receive out parameters
06:47    and effect those parameters within the method.
06:50    If you use the second version, remember
06:53    that you're passing a variable in by reference,
06:56    and then letting the method effect that variable.
06:59    So it isn't always obvious how things are
07:02    happening from the outside.
07:04    It's up to you as the developer
07:05    whether you want to use that architecture,
07:08    but both conventional return methods
07:11    and methods that effect out parmeters
07:13    are available and supported in C#.
Collapse this transcript
Managing variable visibility and scope
00:00    - As you design your C# based programs,
00:02    it's critical to understand variable scope.
00:07    Where variables are visible, and available to your code,
00:09    and when they aren't.
00:11    And I'm going to talk here,
00:12    about three different way of declaring variables,
00:15    and when those variables are available,
00:18    and when they're hidden from your code.
00:21    In this application, in the project, VariableScope,
00:25    I've created a for loop.
00:27    I've already talked about how a for loop
00:29    uses a counter or index variable.
00:32    It's declared in the initialization part of the statement
00:36    in the for loop's parenthesis.
00:39    The i variable is only available
00:42    for the duration of this code block.
00:45    Once the code block is done,
00:47    the variable is de-referenced, and it goes away.
00:51    I'ts eligible for garbage collection.
00:54    So, when the runtime wants to clean up and re-gather memory,
00:57    that variable can be cleaned out,
01:00    because it's no longer in use.
01:02    So, understanding variables and when they're available,
01:06    can help you design your applications
01:07    for the best memory usage,
01:09    but also for the best readability, and maintainability.
01:13    Lets take a look at different places to create variables.
01:18    I'm going to declare a variable within the main method.
01:21    And I'll name it, localVar.
01:24    And I'll give it a value of one.
01:26    When you declare a variable within a method,
01:29    it's available only within that method.
01:32    It's called a local variable.
01:34    When the method is finished executing,
01:37    that variable goes away.
01:39    Because I declared it within the method,
01:41    I can reference it inside the for loop.
01:45    I'm going to change this line of code,
01:47    so that instead of looking at the value of i,
01:49    I'm looking at localVar.
01:53    And then, I'll add a line of code to increment localVar.
01:57    I'll save and run the code, and there's the result.
02:02    I'm successfully seeing and manipulating that variable.
02:07    But lets see what happens if I create a custom method.
02:10    I'll go down here, and declare static, void, CustomMethod.
02:17    this method won't receive any parameters.
02:20    It's just going to execute a little bit of code,
02:22    and it won't return anything.
02:25    I'll use Console.WriteLine,
02:27    and I'll type "value of localVar: "
02:31    And when I start typing the word local,
02:33    Visual Studio doesn't find that variable.
02:37    And if I type it in completely,
02:39    and then try to build my application,
02:42    and I'll do that by going to build, build solution,
02:46    I get an error.
02:48    The name localVar doesn't exist in the current context.
02:52    And again, that's because this variable was declared
02:56    locally to the main method.
02:59    So what if you want to declare variables
03:01    that are available to all methods within a class?
03:04    Well the right way to do that, is to create a field.
03:08    A field is a variable that belongs to the class,
03:11    but not to any particular method.
03:15    Now because I'm working in static methods,
03:18    in order to deal with a field, it has to be static too.
03:22    That is, it belongs to the class,
03:24    and not to an instance of the class.
03:28    So I'll move the cursor up here to the class,
03:31    and I'll start with static, then the data type int,
03:35    then the name of the variable which will be localField,
03:39    and I'll assign it a value of 15.
03:43    Then I'll go back down here to the custom method,
03:46    and I'll change this reference from localVar, to localField.
03:51    I press CTRL and the spacebar,
03:53    to bring up a list of available identifiers.
03:57    And that works.
03:59    Because I declared it as a member of the class,
04:02    that field is available to all methods of the class.
04:07    Now to test that, I'll come down here,
04:10    and I'll put in a call to CustomMethod.
04:14    I'll put in the name of the method and
04:16    the opening and closing parenthesis
04:18    followed by the semicolon.
04:21    I'll save that, and run the code, and there's the result.
04:25    Now my label isn't quite right.
04:27    It still says localVar.
04:29    So I'll come down here and correct that method,
04:32    to localField, and I'll save and run it.
04:36    And now I'm correctly seeing references to localVar
04:39    from within the main method,
04:40    and a reference to the field within the CustomMethod.
04:45    Now at this point, the field is available
04:47    only within the current class.
04:50    But if I wanted to make it available
04:52    to the entire application, I would go up here
04:55    and I would add the keyword, public.
04:59    This is called the access identifier.
05:02    And it's a way of saying how available this field
05:05    or variable is to the rest of the application.
05:09    The keyword public means exactly what it says,
05:12    and if you wanted to make something strictly available
05:15    only to the current class,
05:17    you would say that that's private.
05:20    I'll talk more about access identifiers a little bit later,
05:23    when we talk about creating your own custom classes.
05:27    But working within a single program,
05:29    this gives you the information you need
05:31    to control when data is available.
05:34    With local variables within a method,
05:37    and local fields within a class.
Collapse this transcript
Managing flow with break and continue
00:00    - At this point in the course,
00:02    I've shown how to use various data types
00:04    and how to use flow control methods,
00:06    such as loops and conditional code.
00:10    Here are two more tools to use
00:12    before we get into building our first full application.
00:16    I'm working in a project named BreakContinue
00:19    and I'm going to describe two keywords in C #
00:22    that are enormously helpful in controlling
00:24    when code is executed.
00:27    The keywords are break and continue.
00:30    We've seen the break keyword before
00:32    in the use of the switch statement.
00:35    In a switch statement, you place the keyword break
00:39    at the end of each case.
00:41    The goal is to prevent execution from continuing
00:44    into the next case after that
00:46    and the one after that and so on.
00:49    But, the break keyword specifically is an instruction
00:53    to jump to the end of the current code block.
00:56    So, if I hit the break command on line 20,
00:59    I would then jump to whatever code is at line 34,
01:03    after the code block.
01:04    And if there is no code, as is the case here,
01:07    that would mean finish the program.
01:10    The break keyword can also be used
01:12    in other kinds of code blocks, such as within loops.
01:16    In this example, I'm using an enumeration called Fruit,
01:20    which has three possible values.
01:22    Apple, Orange and Fig.
01:24    And then I'm evaluating those values
01:26    in the switch case statement.
01:29    Now, I'm going to create an array.
01:32    I'll place the cursor after the switch statement
01:35    and I'll create an array with the data type
01:37    set as my enumeration, Fruit.
01:41    And I'll call it groceries.
01:43    Then, between the braces, I'll create my shopping list.
01:47    Two Apples and one Orange.
01:50    Next, I'll put in a foreach loop
01:54    and I'll say that I want to loop through my grocery list
01:57    and deal with each item one at a time.
02:00    I'll add some WriteLine code
02:03    and I'll output the current item.
02:05    Now, I'll run the code
02:07    and the first bit of output, You chose Apple,
02:10    came from the switch statement,
02:12    but then, I'm showing the two Apples and the Orange.
02:16    Now, here's how break and continue work within a loop.
02:19    I'll place the cursor before the call to
02:21    Console.WriteLine and then I'll add an if statement.
02:26    And I'll say if item == Fruit.Orange
02:29    and remember to use the double equals operator,
02:32    not the single equals, because that would be an assignment.
02:35    Then, I want to break.
02:38    Again, the break command means
02:40    go to the end of the current code block.
02:43    So, that would jump to line 44.
02:46    And I'll just add a little bit of output here
02:48    saying "End of grocery list".
02:51    I'll run the code and now, I'm showing the two Apples,
02:55    but I'm not showing the Orange
02:58    because I broke out of the loop when I hit that item.
03:01    So, the break keyword can be used in any code block.
03:05    The continue keyword means go back
03:07    to the beginning of the current code block
03:10    and execute the next version of the loop.
03:13    So, let's change this logic a bit.
03:16    First of all, I'll declare an integer variable
03:19    that I'll call Apples and I'll set it to a value of 0.
03:23    Then, I'll add some more logic.
03:26    I'll say if item == Fruit.Apple
03:31    and within the if clause,
03:32    I'll increment apples++;.
03:35    Then, I'll do a nested loop.
03:37    I'll say if apples > 1
03:41    and within that if statement,
03:43    I'll use the continue keyword.
03:45    The continue command means go back to the beginning
03:48    of the current loop and go to the next item.
03:52    I'm going to comment out this if block.
03:55    I'll select the if block and then press ctrl + k, ctrl + c
03:59    to comment that out.
04:01    Then I'll run the code again
04:03    and this time, I only list Apple once.
04:06    But, then I go on to list the Orange.
04:10    The idea is that I only wanted to print each item once.
04:14    And so, the continue command is being used
04:16    to go back to the beginning of the loop.
04:19    So, that's break and continue.
04:22    The break command can be used in switch statements
04:25    and in loops to take you to the
04:27    end of the current code block,
04:29    while continue is only used within loops
04:31    and it means skip the rest of the current item
04:34    and go back to the beginning of the loop for the next item.
Collapse this transcript
Challenge: Building a simple calculator application
00:00    "(cymbal swell)"
00:03    - Now it's time to put your new C# skills to work,
00:06    creating a simple console application.
00:10    The challenge is to program a simple
00:12    mathematical calculator.
00:15    It'll support just the four standard math operations:
00:18    adding, subtracting, multiplying, and dividing.
00:22    There is some tasks that you'll need to program first.
00:25    You'll need to accept user input.
00:28    It'll be up to the user to provide the numerical values
00:32    and then, choose a mathematical operation.
00:35    But, it's up to you as the programmer to validate the
00:38    user input to make sure that the text values
00:41    the user provides, can be parsed as numbers.
00:45    I recommend using the Tryparse method for that,
00:49    and then, making sure that they've selected
00:51    a valid character to indicate
00:53    a supported mathematical operation.
00:57    Within your code, create a custom static method
01:00    for each mathematical operation.
01:03    You could do this in all one big method,
01:06    but that kind of code is hard to maintain.
01:09    So, break things down into small pieces.
01:12    One method for adding.
01:13    One for subtracting, and so on.
01:17    Let's take a look at my version of the application
01:20    being run in a command window.
01:23    When the application starts,
01:25    I have to enter a value, so I'll type '12'.
01:29    Then, I have to enter another value, and I'll type '5'.
01:34    And then, I have to select an operation,
01:37    and in this version of the application,
01:39    I'm being asked to enter a single alphabetical character.
01:43    A, S, M, or D
01:45    and I'll choose 'S' for subtraction,
01:48    and I get a value of '7'.
01:51    Now, if I enter invalid values,
01:54    here's what happens.
01:55    This time I'll choose '12' again,
01:57    but for the second version, I'll type 'XYZ',
02:01    and I get back a message 'Value can't be parsed as a number'
02:05    and I'm asked for the value again.
02:08    The program doesn't just exit, it tells me what I did wrong,
02:12    and gives me another chance.
02:14    Think about using loops and the break and continue keywords
02:18    to manage that flow.
02:20    So, that's the challenge.
02:22    Build a simple console based mathematical calculator
02:26    application that accepts input from the user,
02:30    validates that input, and then executes
02:32    one of the four standard mathematical operations.
02:36    Take a look at the next video for my solution.
Collapse this transcript
Solution: Building a simple calculator application
00:00    (gentle music)
00:03    - The challenge was to build a simple console-based
00:06    calculator application that gathered user input
00:10    and executed one of four standard mathematical operations.
00:15    My solution is here in
00:16    the SimpleCalculatorSolution in the Exercise Files.
00:21    In the main method, I start by creating two double values
00:25    and I'm getting those values
00:26    by calling my own custom method name GetValue.
00:31    I'll jump to that method by selecting
00:32    one of the method names.
00:34    And then pressing F12 and
00:37    that takes me to the method definition.
00:40    In this method, I'm declaring a double value
00:43    and then executing a while loop.
00:46    My while loop has a condition of true,
00:49    which means it's an infinite loop.
00:51    It's going to keep going over
00:53    and over again until I break out of it.
00:56    You can break out of the loop either with the break command
00:59    or because we're within a custom method
01:01    with the return statement.
01:04    I'm using a return statement.
01:06    Within the loop, first I'm outputting a label.
01:10    This is a string parameter that's passed into the method.
01:14    Then I'm using Console.ReadLine() to gather the input.
01:18    Then I'm parsing it.
01:20    I'm using the Double class's TryParse method.
01:23    I'm passing in the input and then passing
01:26    in the value variable as a reference.
01:29    Notice the use of the out key word.
01:32    If TryParse returns true, then I know I parsed
01:35    the value successfully and I can return the value.
01:39    But if it returns false, then I output the error message
01:43    and loop and ask for the data entry again.
01:47    So, I'm calling that method twice to get the two values.
01:51    Next, I get ready to do the calculation.
01:54    I declare a variable named result.
01:57    My first two values were doubles
01:59    so I'm declaring the third value as double
02:01    as well to make it compatible.
02:04    Then once again, I create a loop,
02:07    and it's condition is true, so it'll be
02:10    an infinite loop until I break out of it.
02:14    The first task is to tell the user what to do.
02:17    So, I use Console.Write and I output the message:
02:21    Choose one of these characters.
02:23    Then I gather the input.
02:26    Instead of using the ReadLine method,
02:28    I chose to use ReadKey, a method I haven't shown so far.
02:32    But it's goal is to allow the user to type just a single key
02:36    and then return that information to you.
02:40    It comes to you as an instance
02:41    of a class called ConsoleKeyInfo.
02:45    That class has a property called Key
02:47    which has a method named ToString.
02:50    I'm using that expression to find out
02:52    what the user asked for.
02:54    Next, I evaluate the input starting at line 24.
02:58    I'm using the String class's ToUpper method
03:01    to uppercase the entry.
03:04    That allows the user some flexibility.
03:06    They can type in either a lower
03:08    or an uppercase character and it'll still work.
03:12    For each of the four supported operations,
03:15    I have a case statement.
03:17    Within the case statement, I'm calling
03:19    my own custom method passing the two double values in.
03:24    The methods are down here.
03:26    They're named Add, Subtract, Multiply, and Divide.
03:30    The first three methods are very simple.
03:33    They just do the operation and return the result.
03:36    I have a little bit more logic, though,
03:38    in the Divide method to prevent problems
03:41    if the user has typed zero for either of the values.
03:45    My logic says if either of these are equal zero,
03:50    just return zero, don't try to do the division operation
03:53    because it could cause problems.
03:55    But if both of them are non-zero,
03:58    then I execute the divide operation and return the result.
04:03    Coming back to my main method.
04:05    So, that's how I handle each of the four operations.
04:08    If I get to the default statement,
04:10    that means they typed a character I didn't recognize.
04:13    And so I tell them: Choose from supported operations,
04:17    and then I execute the continue keyword.
04:21    That causes the execution flow to go back
04:23    to the top of the loop and ask them to choose again.
04:27    But if I get passed the switch statement,
04:30    then I know I've done a mathematical operation
04:33    and I output it to the screen using the WriteLine method.
04:37    Then I have a call to the Read method
04:40    and that causes the application to pause
04:42    and let them see their result regardless
04:45    of whether they're running in debug or non-debug mode.
04:49    So, let's run the application again.
04:51    Once again, I'll type in a numeric value
04:54    and this time I'll type in a fractional value
04:57    and I'll choose division and I get back the result.
05:01    So, try different things with this application
05:04    and see if you can improve it.
05:07    And if you worked through the challenge on your own
05:09    compare it to the code that you created
05:11    and see how the two approaches differ.
Collapse this transcript
6. Exception Handling and Debugging
Understanding runtime exceptions
00:00    - One of the incontrovertible rules of programming
00:03    is that there are always bugs.
00:06    Programmers aren't perfect.
00:08    We can't anticipate all the possible conditions
00:10    that might happen in our applications.
00:13    We test to the best of our ability
00:16    but bugs will still be out there
00:18    and you need the tools to find them and fix them.
00:21    Fortunately, C# has the a robust
00:24    exception handling framework
00:27    and Visual Studio offers a rich set of debugging tools.
00:32    To demonstrate how to work with exceptions in your code,
00:35    I've created this project named Exceptions.
00:39    In the main method of this console application
00:42    there's an array of strings named fruit
00:44    that has three items.
00:45    Then there's a for loop, that loops through the items
00:48    and outputs each of the items to the console.
00:51    I'll run the application with control F5
00:54    and I'll see that it works as expected.
00:56    Now I'll introduce an intentional problem.
01:00    I'll go to my for loop
01:02    and I'll go to the conditional expression.
01:05    I'll change the less than operator
01:07    to less than or equals to.
01:10    That's going to allow the loop to iterate
01:12    one too many times.
01:14    I'm going to be taking the value
01:16    of the length of the array, that's three,
01:19    and trying to use it as an index,
01:22    and because index are offset to zero in C#,
01:26    that will break my code.
01:29    Now, I'll run the application again.
01:31    This time by pressing F5,
01:34    running the application in debug mode.
01:37    I momentarily see the output,
01:40    but then Visual Studio pauses the application.
01:44    Placing the cursor on the line that threw the exception
01:47    and it throws up a window
01:49    that tells me exactly what kind of exception I got.
01:52    It's something called an index out of range exception.
01:56    This is an object,
01:58    and as a full object,
02:00    it has properties that I can examine,
02:03    but before I get into working with
02:05    exception objects in detail,
02:08    I'll describe how to debug this
02:10    using Visual Studio
02:12    and show you some tips and tricks
02:14    that will make the debugging process go faster.
Collapse this transcript
Debugging exceptions in your code
00:00    When Exceptions happen in your applications,
00:03    you have a lot of tools in Visual Studio
00:06    that can help you find out the reason.
00:08    I'm now working in a solution, named Debugging,
00:11    that has the same Exception that I'd introduced earlier.
00:15    If I run this application without debugging,
00:17    by pressing ctrl + F5,
00:19    here's what happens.
00:22    I go into my Command window,
00:24    and the application starts.
00:26    But then, I hit the unhandled exception.
00:29    Momentarily, I see this dialogue box that pops up,
00:32    and Windows goes to work in the background,
00:35    trying to find out if it knows about this problem.
00:38    Because it's my own custom application, it doesn't.
00:41    So, I'll close this program,
00:43    and I'll come back to my Command window,
00:46    and I'll see my Exception listed.
00:49    I'll close that.
00:50    Now, I'll run, with debugging, by pressing F5.
00:54    As I showed earlier,
00:56    when you run with debugging,
00:58    Visual Studio catches the problem,
01:00    and shows you the line of code
01:02    where the Exception occurred,
01:04    and also shows you the name of the Exception.
01:06    In this case, it's named, IndexOutOfRangeException.
01:11    Let's take a look at some debugging tools you can use.
01:15    First, I'll Stop my application,
01:18    by clicking the Stop Debugging button,
01:20    or pressing shift + F5.
01:23    You can Pause your application at any point,
01:25    by adding a breakpoint.
01:28    Breakpoints are only respected
01:29    when you're running in Debugging mode.
01:32    In order to find out what's going on,
01:35    I'll place the cursor before the line
01:37    that's creating the problem.
01:39    I'll add a line of code that uses the Debug class.
01:44    When I type the name of the class,
01:45    I get a squiggly line, indicating that it's not recognized.
01:49    But I'll press "ctrl + .".
01:52    That offers help.
01:54    It tells me that the Debug class
01:56    is a member of a namespace,
01:58    named System.Diagnostics,
02:00    that I'm not currently using in my application.
02:03    I'll select the first option,
02:05    using System.Diagnostics,
02:08    and that adds that using statement
02:10    at the top of my code.
02:12    Now, I can use the Debug class.
02:15    The Debug class has a lot of methods you can use
02:18    to find out what's going on,
02:20    and to assert issues in testing.
02:23    I'm just going to use the WriteLine method,
02:26    and output a message saying, "Value of i : ",
02:31    and then I'll append the value, i.
02:34    I'll save those changes.
02:36    Then, I'll run in Debug mode again.
02:39    I'll, once again, hit my Exception.
02:42    Then, I'll close that dialog.
02:44    I'll go to the Output window, by pressing ctrl + alt + o.
02:50    I see the output from the Debug class.
02:53    Value of i equals 0, 1, and 2.
02:57    This is telling me that all that succeeded,
03:00    as long as my index went up to 2.
03:02    But then, it broke.
03:04    Now, we already know why it broke.
03:06    The length of the array is three,
03:08    and I tried to use that as an index.
03:11    But let's pretend, for a moment,
03:12    that we don't know what the root issue is.
03:15    Here are some more tools that we can use.
03:18    While you're in a breakpoint,
03:19    you can inspect all available variables,
03:22    such as local variables and fields.
03:26    You can do this in this tab, named Locals.
03:30    This shows me that I have an array of strings, named args.
03:33    That's the parameter that's passed into the main method.
03:37    I have my array of strings, named fruit.
03:40    That's the thing I created myself.
03:42    Here's my index variable, i.
03:45    It's telling me that the Value is 3.
03:48    You can also look at variables using watches.
03:52    Here's how you can do that.
03:55    Select the variable, i.
03:57    Then, right-click, and say Add Watch.
04:01    That adds that variable to the Watch pane.
04:05    Now, I'm going to Stop Debugging,
04:08    and I'm going to place a breakpoint right here,
04:10    by clicking on the troff next to the line number.
04:14    Then, I'll run with Debugging again.
04:17    This time, I pause at that line.
04:21    I look at the Watch pane,
04:23    and it tells me the Value of i is 0.
04:27    At this point, I can step through my code.
04:30    Up here, on the toolbar,
04:32    there's a set of stepping commands.
04:34    Step Into, Step Over, and Step Out.
04:38    Step Over is what I want.
04:41    There's a method here, named WriteLine,
04:43    and if I chose Step Into,
04:45    I might go into the internals of that method,
04:48    which is actually a part of the .NET Framework.
04:50    I don't want to do that.
04:52    I just want to debug my own code.
04:54    So, I'll click Step Over.
04:57    I go to the next line.
04:59    I'll click Step Over again,
05:01    and I'll keep going, and keep going,
05:03    and keep going.
05:05    If you know the basic problem that you're looking for,
05:08    but you just want to pause the application at that point,
05:11    you can set the breakpoint to be conditional.
05:15    That is, it'll only stop the application
05:18    when a particular condition is true.
05:21    There are a few ways to do that.
05:23    I'll go down here, to the Breakpoints panel.
05:26    Then, I'll go to this breakpoint.
05:28    I'll right-click, and I see
05:30    all of these different things I can do with breakpoints.
05:34    I'll select Condition.
05:36    I'll set it to a Boolean expression,
05:39    of i = = 3.
05:43    I'll click OK.
05:45    Then, I'll stop my application.
05:48    I'll run it again in Debug mode.
05:51    Now, I only hit the breakpoint
05:54    when the value is 3.
05:56    I can now Step Over my code.
05:59    I see that that line of code didn't cause a problem.
06:02    I'll Step again.
06:04    Now, I know exactly when my problem is happening.
06:07    It's happening when the value of i is 3,
06:10    when I try to access the item in the fruit array,
06:13    at that index, which doesn't exist.
06:17    That's a lot of steps to find a problem
06:19    that we really, already understood.
06:21    But, the point is to understand how
06:23    these debugging tools can help you find out
06:26    what's going on in your application.
06:29    When Exceptions happen,
06:30    it's up to you, as the developer, to find and fix them.
06:34    But, C# and Visual Studio
06:36    give you lots of tools to do it.
Collapse this transcript
Handling exceptions with try/catch
00:00    - Visual Studio provides the tools to debug exceptions,
00:04    but the C# programming language provides tools
00:07    that let you handle exceptions at run time
00:10    when you know that they might be possible.
00:12    The most important tool is a set of keywords
00:15    called try and catch.
00:17    This architecture is common to C style languages.
00:21    It's implemented in almost the exact same way in Java.
00:26    To use try/catch, first wrap the code
00:29    that you think might generate an exception
00:31    inside a try code block.
00:35    I'll start off by typing the word try,
00:37    then I'll press tab twice to insert a code snippet.
00:41    That creates a code structure starting with try
00:45    followed by a catch clause,
00:47    and within the catch clause, the keyword throw.
00:52    Now, I'll take this code,
00:54    and I'll cut and paste it,
00:56    and place it inside the try block.
00:59    Right now I'm saying, "Run this code.
01:02    "If it runs without any problems,
01:05    "jump to the end of the try and the catch block."
01:09    So your application's flow would pick up here,
01:11    after the catch.
01:14    "But if there are any exceptions,
01:16    "jump into the catch block
01:18    "and execute any code we find there."
01:21    Notice that the catch block has a pair of parentheses,
01:24    and the name of a class, Exception.
01:28    This class, System.Exception, is the super class,
01:32    or parent class for all Exception classes in C#.
01:37    So that exception that I saw earlier,
01:40    the "index out of bounds" exception
01:42    is a subclass of Exception.
01:44    By placing the name of the super class here,
01:47    we're saying that this catch block can handle
01:50    any exception that can happen,
01:52    no matter what type of exception it is.
01:54    I'll clean up my code a little bit,
01:57    and now, let's see what happens when I run the code
02:00    without debugging, with Control F5.
02:03    The same problem happens!
02:05    And that's because of the throw keyword
02:08    that's in the catch block.
02:10    This is now saying,
02:12    "Let the flow go into the catch block,
02:14    "but then throw the exception again."
02:17    So it's like the try/catch block isn't even there.
02:21    To make try and catch really useful,
02:24    you want to name the exception object
02:26    that you're being passed
02:28    when the catch block takes over.
02:31    I'll go to the name of the Exception class,
02:34    and I'll add an identifier, a variable name.
02:37    And this is how I'll refer to that exception object.
02:40    Then I'll move down here
02:42    and I'll take out the throw keyword,
02:44    and instead, I'll use output
02:47    with Console.WriteLine,
02:50    and I'll output the exception object.
02:53    Now with any object, when you just pass the object
02:56    into a method that's expecting a string,
02:59    it'll call the object's ToString method.
03:02    So, the output we're about to see
03:04    is what the Exception class does
03:07    when you call ToString.
03:09    Here we go.
03:11    I'll run the code.
03:13    If I run the code with debugging,
03:15    I don't get an exception now,
03:17    and that's because the catch block is taking care of it.
03:21    But, in a console application,
03:23    that results in the application going away really quickly.
03:27    So now I'll run without debugging,
03:29    and I see a really ugly output.
03:33    This is what an Exception class does all by itself
03:37    when you call its ToString method.
03:39    It includes line numbers, full package and class names,
03:43    and a lot of other information
03:45    that might not be useful to the general user.
03:48    So instead, if you're showing information
03:50    from that exception object to the user,
03:53    you might choose to use the Message property.
03:57    The Message property is a string.
04:00    It's a message that describes the current exception
04:02    in the user's local language.
04:05    I'll choose that instead,
04:07    and I'll run Control F5 again,
04:10    and now I see a simple, clean message,
04:13    "Index was outside the bounds of the array."
04:17    That's something that's still a little bit computery,
04:19    and the general user might not understand it,
04:22    but it's sure a lot easier to read.
04:25    The Exception class has a bunch of other properties
04:29    and methods that you can call.
04:30    You can learn about them
04:32    by going to the documentation for the Exception class.
04:35    I'll put the cursor in the word Exception,
04:38    then I'll press F1, and I'm taken
04:41    to the documentation for the class.
04:43    You'll find Constructors information,
04:46    Properties, and Methods.
04:49    The try/catch architecture is an incredibly valuable tool
04:53    for all C# programmers.
04:56    It lets you anticipate exceptions
04:58    and handle them at run time
05:00    so that your application doesn't just crash
05:03    when it encounters them.
Collapse this transcript
Using multiple catch statements
00:00    - The tryCatch architecture is designed
00:03    so you can have distinct catch blocks
00:05    for different kinds of exceptions.
00:08    Right now, the code in this solution, TryMultiCatch,
00:11    only generates a single exception.
00:14    It's the problem that happens
00:16    when you try to use an index that's out of bounds.
00:19    When I run this code,
00:21    my flow is jumping into the catch block
00:24    and I'm outputting the exception's message.
00:27    But now let's see what happens when we generate
00:29    another kind of exception.
00:33    First, I'm going to change one of the values in this array
00:36    from a literal string to the key word null.
00:40    Then, I'm going to go back to the standard operator
00:42    for the for loop, only running the for loop
00:45    while the index variable is less than the array's length.
00:49    When I run the application now,
00:51    I get a blank output on the line where the null object is.
00:55    That's because, simply having a null object
00:59    and passing it where you expect a string,
01:01    doesn't generate an exception on it's own.
01:04    But if you want to generate an exception for that, you can.
01:09    Here's how we'll do it.
01:11    I'll place the cursor inside the for loop
01:13    before console.WriteLine
01:16    then I'll add an if statement.
01:19    And I'll set the condition to,
01:20    if the item in the fruit array is null.
01:23    Now, if that's the condition,
01:25    then I'm going to throw my own exception.
01:29    And I'll do this with the throw keyword,
01:31    but this time, I'll use it as a method.
01:35    I'll pass in an instance of a class
01:37    called ArgumentNullException.
01:40    I'll add the parentheses
01:41    as the end of that class' constructor method.
01:45    And now I'm saying,
01:46    if this object is null, throw an exception.
01:50    Right now, I'll catch it because my catch block is looking
01:54    for the superclass, the exception class.
01:58    All exception classes are children
02:01    or subclasses of that class,
02:03    so this exception will be caught as well.
02:06    I'll run the code without debugging.
02:09    I output the first item of the array,
02:12    then I get the error message, "Value cannot be null."
02:15    So far so good.
02:17    But now, I'll go back to the condition
02:20    where I might run into an index out of bounds exception.
02:24    I'll run the code again
02:26    and I'm still getting the null exception.
02:29    Now, here's how you can add more catch clauses.
02:33    First, I'll change the name of the exception I'm looking for
02:36    in my first catch clause to IndexOutOfRangeException.
02:41    Then, I'll add another catch block,
02:44    and this one will be for ArgumentNullException.
02:48    Just like the first one, I'll listen for the exception
02:52    and name the exception object ex.
02:55    You might think,
02:56    "Haven't you already used that variable name?"
02:59    But remember the variable scoping rules.
03:01    If a variable's declared in the keyword
03:04    within the parentheses,
03:07    that variable is only available for that code block.
03:10    So this ex is only available for the first catch
03:14    and this one will only be available for the second one.
03:17    Once again, I'll output the message
03:20    and now, I'm handling both exceptions.
03:23    To make sure I know which exception I'm seeing,
03:26    I'll add a little bit more console output.
03:29    For this one, I'll say, "Index problem"
03:32    and for the ArgumentNullException catch clause,
03:36    I'll say, "No problem."
03:38    I'll run the code and once again I get to the null problem
03:43    because I haven't gotten to the
03:44    IndexOutOfRangeException yet.
03:47    Now, I'll comment out these three lines of code.
03:50    So I'm no longer explicitly throwing the exception.
03:54    I'll comment with ctrl + k, ctrl + c
03:58    and run the code again,
04:00    and this time, I get to the "Index problem."
04:04    So, having multiple catch clauses with a single try
04:08    is strongly supported in C#.
04:10    It's a great way of distinguishing between the exceptions
04:13    that might occur from a particular bit of code.
04:17    And remember that if you want to catch all exceptions
04:20    in exactly the same way, just catch exception,
04:24    the superclass of all exceptions.
Collapse this transcript
Cleaning up with finally
00:00    - There's one more important part
00:02    to the Try Catch architecture.
00:04    It's a key word named Finally,
00:07    which allows you to add code that will execute
00:09    at the end of a Try Catch block,
00:11    regardless of whether an exception is thrown.
00:15    To use the Finally clause,
00:17    go down to the end of the Try Catch block.
00:20    Place it after the last Catch block
00:23    and start with the key word finally.
00:26    Then add a code block, a pair of braces.
00:30    You can place any code in here that you'll need
00:33    to clean up from the code that
00:35    was executed in the Try block.
00:37    For now, I'm just going to show that it works
00:40    by adding some console output.
00:43    I'll add the string, Finally block has been reached.
00:47    Now, in the current code,
00:48    I still have the wrong operator
00:50    when I'm comparing my index variable
00:52    to the length of the array.
00:54    So, I'm going to be throwing
00:55    the index out of range exception.
00:58    I'll run the code.
01:00    And I see that I get into the Catch block,
01:03    but then I see the Finally block has been reached.
01:07    Now, I'll fix the bug
01:09    by changing back to the > operator.
01:12    Now I'm only referencing the items
01:15    that are actually in the array.
01:17    I'll run the code again.
01:19    And I see that I run the code
01:21    without hitting any exceptions,
01:23    but I'm still executing the code in the Finally block.
01:27    And finally, I'll un-comment this code.
01:31    I'll select those four lines of code
01:33    and press ctrl + k, crtl + u
01:35    and that removes the comments.
01:38    I'll run the code again
01:40    and this time, I get into the null exception.
01:43    And once again, I'm hitting the Finally block.
01:46    So, that's how you can use the Finally block
01:49    in a Try Catch architecture
01:51    to execute code regardless of whether
01:53    you hit an exception.
01:54    This is a valuable tool for making sure
01:57    you clean up any conditions
01:59    that might have been created
02:01    while you're in your Try block.
Collapse this transcript
7. Managing Collections of Data
Using simple arrays
00:00    - Most programming languages give you a way
00:02    of saving sets of data in memory.
00:05    These are called collections.
00:08    In C#, there were a few different
00:10    kinds of collections to work with.
00:13    I'm going to be talking about arrays,
00:15    lists, and dictionaries.
00:18    An array is a fixed-size ordered collection.
00:22    It's fixed-size, because once you declare an array
00:25    with a certain number of items,
00:27    you can't change the number of items in that array.
00:30    In contrast, a list is also an ordered collection,
00:35    but it's resizable.
00:37    In this demonstration,
00:39    I'll show you how to declare an array
00:41    with a few different types of syntax,
00:43    and then how to address the items in the array.
00:47    In previous videos, I've worked with arrays of strings,
00:50    using syntax like i have at line 14,
00:53    in this project, named SimpleArrays.
00:57    You start with the datatype of the items in the array,
01:00    and follow that with a pair of brackets.
01:03    That means it's not just one item.
01:04    It's a set of items.
01:06    Then, you give it a name,
01:08    and you assign it a comma-delimited list
01:10    wrapped in braces.
01:12    In this case, I have literal strings.
01:15    As I've shown previously,
01:17    you can use various looping constructs
01:20    to loop through the items in the array,
01:22    and deal with them in your programming tasks.
01:25    I'll simply output each item in the array.
01:29    There's the result.
01:32    But, there are other ways of dealing with arrays.
01:35    Let's take a look at another way
01:37    of setting up an array.
01:39    This time, I'm going to declare a string array,
01:43    and I'll call it, names.
01:45    I'll initialize it, using this syntax:
01:48    new string[3].
01:54    That means I want to declare the array,
01:57    but put three items into it.
01:59    Initially, those items will be null,
02:02    but they're placeholders.
02:04    They're places where I can now
02:05    place strings when I need them.
02:07    Next, I'll assign the individual elements of the array.
02:11    I'll declare the first one, using the syntax, names[0].
02:15    I'll assign it a value of "Joe".
02:18    Now, I'll copy this line of code,
02:21    and I'll paste it a couple of times.
02:24    I'll change the indexes for the other two items,
02:27    to [1] and [2].
02:30    I'll change the names to "Mary" and "Martha".
02:35    These four lines of code do basically the same thing
02:38    as the single statement on line 14.
02:41    I declare the array, and then I fill in the values,
02:44    but now I'm doing them one at a time.
02:48    If I try to do this ...
02:49    If I say, names[3] ...
02:54    Then, I'll assign my own name, "David".
02:58    Then, I try to build my application
03:01    with ctrl + shift + b,
03:03    I'll see that everything succeeded okay.
03:06    But, when I try to run the application,
03:09    I'll get an error.
03:10    It's our friend, the IndexOutOfRangeException.
03:14    You can't assign a new item in the array
03:17    in an index that hasn't already been declared.
03:20    Again, an array is of a fixed size.
03:25    So, I'll comment out that line of code.
03:28    It's not going to work the way I wanted it to.
03:31    Arrays have some advanced features
03:32    that are worth knowing about.
03:34    The array is a class in and of itself,
03:37    and it has methods, like sum and average,
03:40    that you can use to work with arrays of numeric values.
03:45    I'll declare an array of integers that I'll name, weights,
03:49    and I'll give it these values:
03:51    {12, 34, 56, 12, 23}.
03:58    Now, I'll get the sum of those two values.
04:01    I know this will be an integer value,
04:04    so I'll declare a variable, named sum,
04:07    typed as int,
04:09    and I'll get its value from weights.Sum.
04:13    Then, I'll output the result.
04:16    "The sum is",
04:18    and I'll append the variable.
04:22    The sum of those numbers is 137.
04:26    You can do the same sort of thing with averages.
04:30    I'll create a double variable,
04:32    that I'll name, average,
04:34    and I'll get its value with the expresssion
04:36    weights.Average.
04:39    I'll output that to the console.
04:43    The average of those values is 27.4.
04:49    Finally, you can also pass arrays to custom methods.
04:54    I'll declare a new, static custom method down here,
04:58    after the main method.
05:00    I'll name it, UseArray.
05:03    I'll start with static, then void,
05:05    and I'll name the method, UseArray.
05:08    I'll pass in a string array.
05:11    I'll name it, simply, values.
05:13    Within the UseArray method, I'll output a label,
05:17    Values in method.
05:19    Then, I'll use a foreach loop.
05:21    I'll loop through the array, using its name,
05:24    as it's been passed in as a parameter,
05:27    into the method.
05:28    Within the foreach loop,
05:30    I'll output the name of the item.
05:33    Now, I'll come back up here,
05:35    and add some space at the end of the code.
05:38    I'll call my UseArray,
05:41    and I'll pass in the names array.
05:44    I'll run that code, and there's the result.
05:47    I see Values in method,
05:49    and then the list of the items in the array.
05:52    An array is an object, too.
05:55    It's an instance of the array class,
05:58    and that array object has its own objects,
06:01    which are the items in the array.
06:04    You can pass the array around as you need to,
06:06    and deal with it as its own object,
06:09    or you can deal with the individual items within the array,
06:12    whatever you need to do for your application.
Collapse this transcript
Using multidimensional arrays
00:00    - All of the arrays that I've demonstrated so far
00:02    have been single-dimensional arrays,
00:05    where the array has a fixed number of items
00:08    and each item is an object of some kind,
00:11    a string, a number, and so on.
00:14    In C# you can also create multidimensional arrays.
00:18    These are arrays where each item in the array
00:21    is also an array, and it's a good way
00:24    to store a matrix of information.
00:27    I'll show a demonstration of using multidimensional arrays
00:30    in this solution named MultiArrays.
00:33    To declare a two-dimensional array,
00:36    start with the data type of the items within the array,
00:40    and then put in a comma.
00:43    A single comma means it's a two-dimensional array.
00:46    Two commas would mean it's a three-dimensional array,
00:49    and so on.
00:51    I'll keep this simple and only do a two-dimensional array.
00:55    I'll name my two-dimensional array "sections"
00:59    and I'll initialize it like this.
01:01    First with the keyword "new"
01:04    then once again with the data type
01:06    of the items within the array,
01:08    and then the two-dimension sizes.
01:11    I'll be creating a two-dimensional array
01:14    with three items in the first dimension,
01:16    and within the second dimension,
01:18    three items within each of the top level items.
01:22    So I'll have a total of nine items in my array.
01:26    Next, I'll assign the items.
01:29    Each item is indexed by two values.
01:32    The index of the first dimension
01:34    and the index of the second dimension.
01:37    So, if I put in sections, bracket, bracket,
01:40    and set my index expression at 0,0,
01:44    that means this is the item in the first dimension
01:48    and its first item, and I'll set it to
01:51    a string value of "top left".
01:54    Now, I'll copy that line of code,
01:57    and I'll paste it in a couple of times,
02:01    and then I'll change this second dimension index
02:03    for both of those new ones
02:05    to 1 and 2,
02:08    and this one becomes "top center",
02:10    and this one becomes "top right".
02:13    Next, I'll copy all three lines of code,
02:16    and then I'll paste that in once, and twice,
02:19    and for this second section,
02:20    I'll change the top level dimension to 1,
02:23    and this one to 2,
02:25    and then I'll change the strings to match.
02:28    For index number one in the first dimension,
02:31    I'll use the word "middle",
02:33    and for item two in the first dimension,
02:35    I'll use "bottom".
02:38    So now I have a place to store each item
02:41    in a particular area of a grid.
02:45    Next I'll create a looping section
02:47    where I'll deal with each item
02:49    in the multidimensional array.
02:52    This is going to be a two part nested loop,
02:55    a for loop within a for loop,
02:58    I'll start with a for loop,
03:00    and I'll set the length to a fixed value of 3,
03:04    that means I'm looping on indexes zero, one, and two.
03:09    Within the for loop, I'll create another for loop.
03:13    Once again, I'll type the word for and press tab twice.
03:16    Then, for the second for loop,
03:18    I need to use a different index variable name.
03:22    The variable i will be for the outer loop,
03:25    so I'll use j for the inner loop.
03:28    I typed j and pressed tab,
03:30    and that resulted in refactoring, renaming,
03:34    the other items that referenced j.
03:38    Once again, I'll set the length to a literal value of 3.
03:42    Now, I'm ready to address each item within the array.
03:47    I'll use Console.Write,
03:49    and I'll pass in the name of my array, sections,
03:53    and I'll use a two-part index, i, comma, j.
03:58    And that addresses the item in that quadrant,
04:02    and then after the reference to the item in the array,
04:05    I'll append a tab character
04:07    with backslash t.
04:10    Now, I want to find out where I am in the loop,
04:12    and I'll use a little bit of calculation.
04:15    I'm going to use the remainder operator
04:18    and determine whether the current value of j
04:21    is divisible by three.
04:24    I'll put in an if clause,
04:26    and within the if clause,
04:28    I'll use the expression j + 1.
04:32    Remember, j is a zero offset index.
04:35    I want to calculate it as a one-based number.
04:39    So I add 1, then I put in the percent character,
04:44    and then 3.
04:45    And now, I'm looking for the remainder
04:47    of that division operation.
04:50    If it returned zero, then I know I'm on the third item,
04:55    and I'm going to respond to that
04:57    by writing an extra line into my output
05:00    with just a double quote.
05:03    Up here, I'm going to change
05:05    the WriteLine method reference to simply Write,
05:08    and the idea is that I'll write out the items
05:11    in the top level of the array first,
05:13    then the middle on the next line,
05:16    and then the bottom on the last line.
05:18    And I'm read to save and run.
05:21    I'll run the application without debugging,
05:23    and there's the result.
05:25    I'm placing items on the grid
05:28    using a multidimensional array and a nested for loop.
05:32    Now, think about the kinds of ways
05:34    you can use a multidimensional array.
05:37    If you were building a simple tic tac toe game,
05:40    you could store the references to the X's and O's
05:43    using this sort of indexing.
05:45    Or any other grid-based application,
05:49    where you need to deal with a screen in sections.
05:52    Multidimensional arrays are incredibly useful
05:55    when you're doing this sort of visual programming
05:58    and you need to keep track of the items
06:00    that you're working with.
Collapse this transcript
Managing ordered data with lists
00:00    - An array, which I've previously described,
00:02    has a fixed number of items.
00:05    Once you declare it, you can't change the number of items.
00:08    You can set an item to null.
00:10    But if an array has three items, it always has three items.
00:15    In contrast, the list class
00:17    lets you create a re-sizeable array.
00:20    It lets you add and remove items as you need to.
00:23    And it can accommodate a large amount of data.
00:27    This will introduce a new style of programming
00:30    known as 'generic data typing'.
00:32    And I'll describe it when I get to it.
00:34    To create a list, you can start off with the list data type,
00:39    like this, or you can do implicit typing
00:42    with the keyword var.
00:44    I'll do that, so that I don't have to
00:45    repeat the data type twice.
00:48    I'll name my list, fruitList.
00:51    And I'll initialize it using the keyword, new,
00:54    then the name of the list class.
00:58    Notice that the list class is a member of a package named,
01:02    System.Collections.Generic.List,
01:06    and it has a less than and greater than symbol,
01:09    that are called the diamond.
01:12    This is where you declare the data type,
01:15    of the items within the list.
01:18    It represents a strongly-typed, list of objects.
01:21    Once you declare the data type,
01:23    that's the only kind of item you can put into the list.
01:27    I'll say that my list will contain strings.
01:31    And then, because I'm starting with the keyword, new,
01:34    I'm calling the list class's constructor method.
01:37    So I also need the parenthesis at the end.
01:41    When you first create the list,
01:43    it doesn't have any items in it.
01:45    But you can then add items as you need to.
01:50    I'll start with fruitList,
01:51    and then I'll call a method named Add.
01:55    Notice that there is an Add method.
01:57    There's also a set of Remove methods,
01:59    including Remove, RemoveAll, and Remove Add.
02:04    There's Reverse method, and there's much, much more.
02:09    I'm going to Add an item, and it has to be a string.
02:12    So I'll type in 'Apple'.
02:14    Now, I'll copy that line of code,
02:16    paste it in a couple of times, and then change the strings.
02:21    And so now there are three items in my list.
02:26    Just as with an array, you can loop through a list,
02:29    using the foreach loop.
02:32    Typically within the foreach loop,
02:33    you start with the keyword var, using implicit typing.
02:37    And then, you can name the item anything you want.
02:41    The data type of this item will be derived
02:43    from the generic declaration up here.
02:47    That is, each item will be a string in this case.
02:50    And, I'll use Console output, and I'll output the item.
02:55    I'll run the code, and there's the result.
02:59    I'm now putting three items, one at a time.
03:03    Just like an array, the list is an ordered collection.
03:07    But you can sort it very easily.
03:10    I'll call the fruitList object's Sort method.
03:14    There are four different versions of this method.
03:17    There's the default version,
03:19    which sorts things in ascending order.
03:21    And then there are more complex versions,
03:24    where you can create something called a comparison object.
03:28    I'll stick with the simplest version,
03:30    calling the Sort method.
03:32    Then I'll copy and paste my foreach method call.
03:36    And I'll run the code.
03:38    And the first time it comes out as Apple Orange and Fig.
03:42    And the second time, Apple, Fig, Orange.
03:45    It's now in alphabetical order.
03:48    When you call the sort method,
03:49    you're affecting that list directly.
03:52    You're not returning anything.
03:54    And so, you want to make sure, that the order it ends up in,
03:58    is going to be okay,
03:59    for what you need to do in your program, after that.
04:03    Just like an array, you can take a list
04:05    and pass it to your own custom methods.
04:09    I'll go down here, after my main method,
04:11    and I'll create a new static method.
04:14    It won't return anything, so I'll use void as the return
04:18    type, and I'll name the method, ReportOnFigs.
04:24    I'll set the one and only parameter to a list of strings.
04:28    And I'll call it Items.
04:31    I wont call it fruit or fruits.
04:33    I'll assume only that I'm getting a list of strings.
04:37    Now I'll determine whether there are any Figs.
04:40    And I'll use a method of the list class, called Contains,
04:44    which will look for an item.
04:47    In the case of strings, I can pass in a literal string,
04:50    and it'll decide whether that item is in the list.
04:55    I'll create a string that I'll call figReport.
04:59    Now on the next line, after the equals operator,
05:02    I'll call items.contains.
05:08    I'll pass in the word Fig,
05:09    and then if I want this to be a non case-sensitive match,
05:13    I'll pass in a constant of StringComparer.OrdinalIgnoreCase.
05:20    That returns a Boolean value.
05:23    And I'l going to use that expression,
05:24    as the first part in a three-part assignment.
05:28    This is the conditional operator.
05:31    I'll put a question mark here.
05:33    And then I'll say, if that expression returns true,
05:36    I'll create a string of "Yes there are Figs."
05:40    And then I'll put in the colon character.
05:43    And if the expression returns false,
05:45    the string will be, "No there are no figs".
05:49    And that's the end of the whole statement.
05:52    Then, I'll output the result, using Console.WriteLine,
05:56    and I'll output the figReport string.
06:00    Now I'll use that method.
06:02    I'll go back to my main method,
06:04    at the end of the existing code,
06:06    and I'll call my custom method, ReportOnFigs.
06:10    And I'll pass in my fruitList.
06:13    I'll save the change, and run the code.
06:15    And it tells me, "Yes there are figs."
06:19    But now I'll come back up here, and change 'Fig', to 'Date'.
06:24    And I'll run the code again, and this time I'll get back,
06:27    "No there are no figs."
06:29    Take a look at the documentation for the list class,
06:32    for all the other things you can do,
06:34    with this incredibly flexible class.
06:37    I placed my cursor inside the name of the class,
06:40    and pressed F1.
06:42    And then within the Help viewer,
06:43    I'll click on the link to the class.
06:46    And here you'll find all sorts of documentation,
06:48    about the properties, methods, constants,
06:52    and other capabilities of the list class.
Collapse this transcript
Managing unordered data with dictionaries
00:00    - A dictionary in C# is like a hash table
00:03    in some other applications.
00:05    It's an unordered collection of data.
00:09    Each item in the collection
00:10    has a key and a value.
00:13    In C#, both the key and the value
00:16    can be of any data type.
00:18    It's very common, though,
00:19    to use a string for the key
00:21    and then use any object as the data type for the value.
00:25    I'll show you how to declare and use a dictionary
00:28    in this Solution named "Dictionaries."
00:31    I'll start by creating a variable
00:33    that I'll name "inventory."
00:36    I'll use var as the data type declaration.
00:39    The actual data type
00:40    will be in the constructor method, Dictionary.
00:45    Just like the list class,
00:46    a dictionary looks for generic data typing.
00:50    But you need to declare two data types,
00:53    one for the key
00:54    and one for the value.
00:56    I'll say my key is a string,
00:59    and my value will be a double.
01:01    I'll close the generic declaration
01:03    and follow that with a pair of parentheses.
01:07    So I'm using the constructor method
01:09    for the dictionary class.
01:12    My dictionary object, inventory,
01:14    is currently empty.
01:16    But now I can add items to it.
01:18    I'll use the object reference,
01:21    and I'll call its add method.
01:23    You'll see that there are methods to add items,
01:26    but also methods to remove items
01:28    and otherwise manipulate the dictionary.
01:31    The add method takes two arguments,
01:33    the key and the value.
01:35    The data types are determined by your declaration
01:38    when you create the dictionary,
01:40    as I did on line 14.
01:43    For my first item, I'll give it a key of Figs
01:46    and a value of 56.
01:49    Then I'll add another item,
01:51    using inventory.Add.
01:53    For this one, the key will be Apples
01:55    and the value will be 23.
01:59    Finally, I'll call the add method one more time.
02:02    This time, the key will be Oranges
02:05    and the value will be 12.
02:08    So my inventory now has three items in it.
02:13    In order to deal with each item in turn,
02:16    you have to get a list of key values.
02:19    You do this with the keys property of the dictionary object.
02:24    I'll create another variable.
02:26    I'll call this one "keys" in all lowercase,
02:29    and I'll get its value from the expression
02:31    inventory.Keys.
02:34    Again, this is the property,
02:36    so it has an uppercase initial character.
02:40    Next, I'll start with some console output.
02:42    I'll start with the string "Number of items."
02:45    Then I'll call the expression keys.Count.
02:50    If you move the cursor over the keys variable,
02:53    you'll see that its data type
02:55    is something called keyCollection.
02:57    It's similar in most ways to a list.
03:00    That's why you can get the count property.
03:03    If you take a look at the documentation
03:05    for the keyCollection class,
03:07    you'll see that it has a lot of other list-style behaviors.
03:11    Now, I'll save and run the application,
03:14    using control + F5.
03:17    I'm told that there are three items in the inventory.
03:20    And that's correct.
03:23    Next, I'll loop through the items in the inventory
03:26    using a foreach loop.
03:29    I'll type foreach and press tab twice,
03:33    and I'll change the collection I'm iterating,
03:35    or looping on, to keys.
03:39    I'll also change the name of the item
03:41    that's being created to the word "key."
03:43    That's singular.
03:45    Now each time through the list,
03:47    I'll be able to reference the key
03:49    and from there, I'll be able to get the value.
03:53    I'll start, once again, with some console output.
03:56    Then I'll output the key,
03:58    which I know is a string,
04:00    because that's how I declared the dictionary.
04:03    I'll append a colon and a space to that,
04:06    and then I'll output the associated value.
04:11    In C#, you can get the associated value
04:14    using a raze-style syntax,
04:16    by putting in a pair of brackets
04:19    and then putting the key inside that.
04:22    You'll be getting the value that's associated with that key.
04:27    Save and run.
04:29    And there's the result.
04:30    I'm outputting my inventory.
04:33    If you need to get your keys into an array,
04:35    that's a simple process
04:37    of calling a method
04:38    of the dictionary class called "toArray."
04:43    I'll declare an array of strings,
04:45    and I'll name it "keysArray,"
04:48    and I'll fill that in
04:49    with keys.ToArray.
04:53    Once I have my keys in the array,
04:55    I can sort it.
04:57    So I'll call Array.Sort.
05:00    This is a static method of the array class.
05:03    Then, I'll pass in keysArray
05:07    and that sorts that array.
05:10    Then, I can loop through the array
05:12    and deal with the items in the array one at a time.
05:16    I'll once again do a foreach loop,
05:19    and I'll name my item "key,"
05:22    and I'll reference keysArray.
05:24    Within the loop,
05:25    I'll once again output the key
05:27    and the associated value.
05:30    This statement is exactly the same
05:32    as when I was looping on the original keyCollection.
05:36    But now I'm dealing with the sorted data.
05:39    I'll run the code,
05:40    and this time,
05:41    the keys are sorted alphabetically.
05:44    There are variations you can use on the sort method,
05:47    if you want to get the keys in a different order
05:49    or use your own custom sorting algorithm.
05:52    Finally, I'll describe how to get a value
05:55    from the dictionary when you don't know for sure
05:58    that that key exists.
06:00    The architecture is very similar to parsing a string
06:04    and turning it into a number
06:06    when you're not sure whether you can do that.
06:09    You might remember that the structures
06:10    that represent numerical values
06:12    have methods called "tryParse."
06:15    Here, I'm going to use a method called "tryGetValue."
06:19    It's going to use an out parameter,
06:23    very similar to tryParse.
06:26    I'll start by declaring a variable that I'll call "value."
06:30    I know that it'll be a double
06:32    if I succeed in getting it back.
06:34    So that's the data type that I'll set it as.
06:37    Next, I'll use an if statement.
06:40    I'll call the tryGetValue method of the dictionary object.
06:45    Then I'll pass in two arguments,
06:48    the key I want to look for
06:51    and the name of the variable that I want to fill in,
06:54    preceded by the keyword "out."
06:57    Just like tryParse, tryGetValue returns a Boolean,
07:02    a true or a false.
07:03    If I get back true,
07:05    that means I succeeded in getting the value.
07:08    So I'll output that with the Console.WriteLine statement,
07:13    and I'll output Figs inventory,
07:16    and I'll append the value variable.
07:20    Then I'll add an else clause
07:22    and I'll output "Figs inventory not available."
07:28    I'll save that,
07:29    and I'll run the code.
07:30    And I successfully get back "Figs inventory is 56."
07:35    Now, if I don't spell this exactly correctly,
07:38    for example, I'll take off the s on the key I'm looking for,
07:42    then I'll get back the message
07:44    "Figs inventory not available."
07:47    So the tryGetValue method gives you a very simple way
07:50    of finding the item you're looking for
07:53    but having an alternative code path
07:55    that you can execute if that item doesn't exist.
07:59    Those are some tips getting started with dictionaries.
08:03    Again, a dictionary is like a hash map
08:05    or a hash table in other languages,
08:08    an unordered collection of data
08:10    where each item in the collection has a key and a value.
Collapse this transcript
8. Creating Custom Classes
Defining a class with static methods
00:00    - Now I'm going to move on to some
00:02    more advanced capabilities in C#.
00:05    As I described at the beginning of the course,
00:07    C# is an object oriented language.
00:10    Everything is placed in classes.
00:13    There are a couple of different ways
00:15    of using classes in your C# programming.
00:18    One very common use of a class is to contain
00:22    methods or functions that you can call
00:25    from anywhere in an application.
00:27    And one approach to this is to create
00:29    a class that only has static methods.
00:33    Methods that are called from the class definition itself,
00:36    and not from instances of the class.
00:40    It's kind of like creating a library of common functions.
00:45    One of the most common classes in
00:46    the .NET framework that follows
00:48    this model is the math class that
00:51    has static methods for all of
00:53    the common mathematical operations.
00:57    I'll demonstrate this in a version
00:59    of my simple calculator application.
01:03    In this application, everything was
01:05    placed into the program class.
01:08    The main method that launches the application,
01:11    the GetValue method that collects data from the user,
01:15    and then all of the methods that execute
01:17    the different math operations.
01:19    Adding, subtracting and so on.
01:22    Now, my goal is to make this code more reusable,
01:26    so I can call it from anywhere in an application.
01:30    As an object oriented application grows
01:33    and adds new features, you'll find that it
01:35    isn't enough to have just a starting class.
01:38    You need to break things down into smaller pieces.
01:42    Creating libraries of common functions
01:45    is an easy way to do that.
01:48    So in my solution explorer,
01:50    I'll go to my project, SimpleCalculator.
01:54    I'll right click, and I'll choose Add, New Item.
02:00    I'll choose Class from Visual C# Items.
02:04    Then, I'll name this new class CalcUtilities
02:09    and then I'll click the add button.
02:12    When you create a new class in a C# program,
02:15    the class will automatically be created
02:18    in the same namespace as where you started.
02:21    That is, it's a part of the same family
02:23    as the other classes in the application.
02:26    I'll describe later how you can reorganize your classes
02:29    to manage them a little bit better.
02:31    For now, that's good enough.
02:34    Within the namespace declaration,
02:36    you'll find a class declaration.
02:38    There's the name of your class.
02:41    Now, you'll notice that this class is placed
02:44    into a file that has the same name
02:46    as the class itself.
02:49    The file is CalcUtilities.cs and
02:51    the name of the class is CalcUtilities.
02:55    But unlike it java, this is not a requirement.
02:59    In fact, in C# you can declare classes
03:02    pretty much anywhere in any .cs file
03:05    that's a part of a project.
03:07    So I could've declared this class in the same program file,
03:11    but I like to keep my classes
03:13    well organized and easy to find.
03:16    So I followed more of a java model here,
03:18    placing this new class in its own file.
03:22    Now, I'll go back to my program class.
03:25    I'll take these four methods,
03:27    add, subtract, multiply and divide.
03:30    I'll select them, and then I'll cut them to
03:34    the clipboard, with control X.
03:38    Those are no longer a part of my program file.
03:41    Then I'll come back over to here to CalcUtilities.
03:45    I'll place the cursor inside the class declaration,
03:49    and I'll paste with control V.
03:52    Those methods are now a member of the CalcUtilities class
03:56    instead of the program class, but
03:59    right now the methods aren't available
04:01    to the rest of the application.
04:04    That's because they're marked private.
04:07    I want to make them available to everybody,
04:09    To the entire world.
04:11    I'll go through and I'll change
04:13    the access modifier private to public
04:16    on each one of these method declarations.
04:20    I'll change them one at a time,
04:22    or alternatively, I could also do a find and replace.
04:27    So now those methods are available to anybody.
04:30    I'll come back to my program file,
04:33    and I'll go back up to where I'm calling those methods.
04:37    Now I see errors telling me that these methods
04:39    don't exist in the current context.
04:43    Because I created them as static methods
04:45    of the CalcUtilities class,
04:48    I can call them from the CalcUtilities class name.
04:52    I'll add the name of the class as a prefix
04:55    and separate the class name from
04:56    the method name with the dot.
04:59    That fixes that call,
05:01    so then I'll copy that prefix and the period.
05:04    Then I'll come down to the subtract method call
05:07    and paste that in.
05:10    Then I'll do the same thing with multiply and divide.
05:13    I'll save my changes,
05:15    then I'll build the solution
05:17    and verify that I don't have any errors.
05:20    Then I'll test with control F5.
05:23    As I've done previously, I'll type in a number,
05:26    then I'll type in another number
05:29    and I'll choose an operation.
05:31    Everything works as expected.
05:33    So, creating classes that are libraries of static methods
05:38    is a great way to reorganize your code.
05:41    To take common operations and place them
05:44    in files and class definitions where you can
05:46    easily call them from anywhere in an application.
Collapse this transcript
Representing data with plain-old class objects
00:00    - I've previously described
00:01    how to create a custom class
00:03    that serves as a library of static methods,
00:07    methods that you can call from anywhere in your application.
00:11    Another common use of custom classes
00:13    is to represent data in memory.
00:16    Let's say for example,
00:18    that you were keeping track of context,
00:20    people and organizations.
00:22    You might create a class that contains data
00:26    for each contact in your list
00:28    and you would customize it to hold particular kinds of data
00:32    such as names, addresses, and so on.
00:36    I'll start here by showing how to define such a class.
00:39    Known by some developers as a POCO
00:42    or Plain Old Class Object.
00:44    This is derived from the phrase POJO,
00:47    for Plain Old Java Object in the Java world.
00:50    It's basically a class
00:52    whose primary purpose is to contain data.
00:55    POCO classes can have both properties that is data
00:59    and methods, behaviors, but the focus is on the data.
01:04    I'll start by declaring a list that I'll call produce.
01:08    I'll start with the keyword var.
01:10    I'm using implicit typing.
01:12    Then I'll generate a new list
01:14    and each item in the list will be an object of some kind.
01:19    I'm going beyond simple strings now.
01:22    These will be complex objects.
01:25    After the declaration of the data type,
01:27    a list of objects, add the parentheses
01:30    because you're calling the constructor method
01:33    of the list class.
01:35    Next, I'll define some custom classes.
01:38    In C#, every class that you define
01:42    is automatically extended from a class called object.
01:46    That's why we're saying these are objects of some kind.
01:50    You can declare your classes either in the same file,
01:53    in this case, Program.cs, or in separate C# files.
01:58    I'll keep everything local this time.
02:01    I'll declare two simple classes.
02:04    The first one will be named Fruit
02:07    and the second one will be named Vegetable.
02:10    And for the moment, I won't define
02:12    any particular data values or methods.
02:16    Now, I'll come back to my main method.
02:18    And I'll add items to my list.
02:21    I'll declare an instance of the Fruit class.
02:24    I'll star with var,
02:26    then I'll give this a name of f1,
02:29    and I'll instantiate it with new Fruit.
02:33    Now I'm calling a constructor method of the Fruit class.
02:37    You might look at this code and say,
02:38    "Well, there isn't a constructor method."
02:41    But in C#, if you don't define your own
02:44    custom constructor methods,
02:46    that is, methods that have the same name as the class itself
02:50    and that are used to create an instance of the class,
02:53    then the compiler generates
02:55    a no arguments constructor method for you.
02:58    Next, I'll add my Fruit object to my list
03:02    with produce.Add and I'll pass in f1.
03:07    Next, I'll take this code and I'll copy and paste it.
03:11    And I'll change the name of the variable from f1 to f2.
03:16    Now my list has two items in it,
03:19    both instances of the Fruit class.
03:22    Then, I'll add a vegetable to my produce list.
03:26    This time, I'll make my code a little bit more compact.
03:31    I'll start with produce.Add
03:33    and then I'll pass in new Vegetable.
03:38    Once again, I put in the parentheses, so I'm calling
03:41    the constructor method of the Vegetable class.
03:44    So those are two ways that you can work.
03:46    Either explicitly create the object
03:49    and then add it to the list
03:51    or if you don't need to hold on
03:53    to the reference to the object,
03:55    just create it and add it all in a single statement.
03:59    Next, I'll output the number of items in the list
04:02    with "There are" and then I'll append
04:05    produce.Count
04:09    and then items.
04:10    I'll run the code with Ctrl F5
04:13    and I see that there are three items in the list.
04:18    Now, I'll loop through the list
04:19    and output the data types of the items.
04:23    I'll use a foreach loop
04:26    and I'll deal with each item one at a time
04:28    in the produce list.
04:31    I'll output the item itself.
04:34    When I run this code, I see the number of items
04:38    and then I see the fully qualified data type of each item
04:42    starting with the namespace
04:44    and finishing with the class name.
04:47    Right now, my POCO or Plain Old Class Object
04:51    doesn't have the ability to hold special data
04:54    or execute special methods.
04:56    But those will be my next steps;
04:58    defining properties for the data
05:00    and methods for the behaviors.
Collapse this transcript
Declaring private fields and public properties
00:00    - The purpose for creating a special class to represent data
00:03    is to contain all of the other data
00:06    that's associated with it.
00:08    You do this with fields and properties.
00:11    A field is a variable that belongs to the class.
00:15    It's sometimes called an instance field.
00:18    There are both static fields and instance fields.
00:21    A static field belongs to the class definition
00:24    while an instance field belongs to
00:27    each instance of the class.
00:29    You declare fields as members of the classes.
00:32    I'll start in my Fruit class,
00:34    which I've already defined as a part of my program.
00:37    I'm working in a version of the solution now called
00:40    FieldsAndProperties.
00:42    Initially, I'm going to declare this in the wrong way.
00:46    It's going to functionally work,
00:47    but it's not going to follow object-oriented principles.
00:51    But my goal is to show you
00:53    how you can represent data in a class
00:55    and then expose that data to the application
00:58    in the correct way.
01:01    Each field within the class should be marked with an
01:03    access modifier and a data type.
01:06    I'll start with public then string,
01:10    and then the identifier for the field,
01:12    which I'll call name.
01:14    Now, this kind of code would work okay,
01:16    but it's not considered proper object-oriented programming.
01:21    Fields should generally be kept private to the class
01:25    and then only made available to the rest of the application
01:28    using special kinds of methods called
01:31    accessor methods and modifier methods.
01:34    The accessor method is called the getter
01:36    and the modifier method is called the setter.
01:39    Visual Studio makes it very easy to take a field
01:42    and turn it into a public property.
01:45    Which makes those methods available
01:48    using a process called encapsulation.
01:51    I'm going to right-click on the field
01:53    and then choose Refactor, Encapsulate Field.
01:58    In this dialog, I'll accept the Property name.
02:02    Notice that the Property name is the same as the Field name
02:05    but the Field name is all lowercase
02:07    and the Property name is using Pascal case
02:10    with an uppercase initial character.
02:12    I'll accept all the other options and click OK.
02:16    Then after previewing the changes, I'll click Apply.
02:20    There's the result.
02:22    The field which started as public
02:24    has been changed to private.
02:27    Then, a new property has been created.
02:31    We know it's a property because it has that
02:32    uppercase initial character.
02:35    It has two methods called the get and the set method.
02:39    The get method returns the value of the private field,
02:43    which I called name.
02:45    The set method automatically receives the value
02:48    of the correct data type which is always named value.
02:53    It takes that value and sets it to the private field.
02:56    I'll follow the process again,
02:58    but this time, with a double value.
03:01    I'll start with public, then double,
03:04    and I'll name this one weight.
03:06    Then I'll right-click on the variable name
03:08    and choose Refactor, Encapsulate Field,
03:12    and click OK and Apply.
03:16    The same process is followed.
03:18    This time, value will be a double
03:21    and the getter and the setter
03:22    will do exactly what we need them to do.
03:25    I'll close up this code so I clearly associate the field
03:29    with the property.
03:31    Now, I'll go up here to where I'm creating and adding
03:34    the instances of my Fruit class.
03:37    For each item, I'll set the name and the weight of the item.
03:42    I'll start with f1.
03:44    and I see my new properties are exposed in the list;
03:47    Name and Weight.
03:49    I'll choose Name and set it to Apple.
03:52    Then I'll use f1.Weight
03:54    and I'll set that to 8.5.
03:57    This is the number of ounces for the particular item.
04:01    Then I'll take that bit of code
04:03    then I'll paste it here where I'm creating my
04:04    second Fruit object.
04:07    I'll change the Name of this one to Banana,
04:10    and I'll change the Weight to 4.5 for the number of ounces.
04:15    Next, I'll repeat these tasks with the Vegetable class.
04:19    I'll come back here to my Fruit class
04:22    and I'll select all these code, copy,
04:25    and paste it into the Vegetable class.
04:28    And now both the Fruit and the Vegetable classes
04:31    have Name and Weight fields and properties.
04:35    I'll come back up here,
04:37    and now, I've created the new Vegetable
04:40    but I don't have a really great way
04:42    of setting the Name and the Weight from here
04:44    because I generated this object and passed it in
04:47    without giving it a name.
04:49    But I can still get a reference to it like this.
04:52    I'll use produce[2].
04:55    And then, to make sure that the compiler knows
04:57    that this is an instance of the Vegetable class,
05:01    I'll prefix it with
05:02    (Vegetable).
05:07    That means, I know that this item is a vegetable.
05:11    Then I'll move the cursor to the end of the line
05:13    and press period, then I'll wrap that
05:16    entire expression in parentheses
05:18    to make sure that it gets evaluated first.
05:22    Then I'll put in the period and there are my properties.
05:26    This entire expression is evaluated and the compiler says
05:30    "Okay, that's a vegetable,
05:32    "so I'll let you set the properties."
05:35    I'll set the Name to Carrot.
05:38    Then I'll take this line of code
05:40    and copy and paste it.
05:42    I'll set this one to Weight,
05:44    and I'll set it to a numeric value of 4.1.
05:49    And so now I'm storing this data within the objects.
05:53    I'll save and run the code
05:56    and I still successfully see that I have
05:58    Fruits and Vegetables, but right now,
06:01    I don't have a really good way to report this information.
06:05    That'll come in the next couple of videos.
06:07    But for now, what I've shown
06:09    is that for any plain old class, you can define data items
06:14    as private fields and public properties.
06:17    In the next couple of videos, I'll show you a more
06:20    concise way of defining these properties.
06:23    And then again, I'll show you ways of getting to the data
06:26    and reporting it to the application.
Collapse this transcript
Declaring properties with shorthand get and set methods
00:00    - I previously described how to declare private
00:02    fields and public properties so that you can encapsulate
00:06    data in plain old class objects, or pocos.
00:11    This is the verbose approach to declaring properties,
00:14    declaring explicit get and set methods.
00:18    The reason to do this is if you want to apply
00:20    any custom logic.
00:22    For example, let's say that you wanted to make
00:24    a rule that whenever the name of a fruit or
00:27    vegetable was accessed, it would be returned
00:30    in all upper case.
00:32    If you're using explicit get methods, you can
00:35    use codes such as this: return name dot two upper,
00:40    and then the only way to get the name of the fruit
00:42    object is to get it in upper case.
00:45    But there are lots of times when you don't need
00:48    that sort of functionality, when all you want to
00:51    do is encapsulate the data, and create a default
00:54    get and set method, and C# makes it easy to do that.
00:59    I'll go back to my fruit class, and this time I'm
01:02    working in a project named shorthand properties,
01:05    and this time I won't declare a private field at all.
01:09    I'll just declare a property.
01:11    I'll start with public, then the data type which
01:14    this time will be int for integer, and I'll set
01:17    the name of this property as quantity.
01:21    Then between a pair of braces, I'll type get,
01:25    semi-colon, set, semi-colon.
01:28    And that's it, that's all I have to do.
01:32    Now this property is properly encapsulated.
01:36    I followed good object oriented programming
01:39    methodology, I'm only offering access to the
01:43    field through a getter and a setter method.
01:47    They'd run if my requirements become more complex.
01:50    I can expand this to explicit declarations, but
01:54    the existing code that's calling the getter
01:57    and setter property won't be disturbed.
02:00    I'll copy that declarations to the clipboard, and
02:03    I'll come down here to my vegetable, and I'll
02:06    paste it in.
02:08    Then I'll go back up here to where I'm declaring
02:10    my objects, and I'll add the quantity to each object.
02:15    I'll set the quantity for my apple to three, and
02:19    I'll set the quantity for banana to seven, and
02:23    I'll come down here to carrot, and once again
02:26    I'm dealing with a complex expression, so I know
02:29    I'm dealing with an instance of the vegetable class,
02:32    and there's the quantity property, and I'll set
02:35    its value to 16.
02:38    I'll save and run the code, and everything compiles
02:42    and runs correctly.
02:44    Once again the data is being properly encapsulated,
02:48    it's stored properly in the object, which is an
02:52    instances of my poco class.
Collapse this transcript
Overriding the ToString() method
00:00    - When you declare your own custom class,
00:02    it's automatically extended from a class called object.
00:07    This relationship is sometimes called the base class
00:10    and the derived class, and sometimes
00:12    the superclass and the subclass.
00:15    They both mean the same thing.
00:17    It means that there are things that the superclass
00:20    or base class can do that the derived or subclass inherits.
00:24    Every class is extended from object in C#.
00:28    And to learn about what you're inheriting,
00:31    you can go to the documentation.
00:33    I'll go back up here to where I'm declaring
00:34    my list of objects.
00:37    I'll place the cursor in the word object, and press F1.
00:41    And that takes me to the C# reference for the object alias.
00:46    Then I'll click the link to go to the object class
00:49    in the .NET Framework.
00:51    And then I'll scroll down in the documentation
00:54    to the Method list.
00:55    And you'll see that there are a few
00:56    different methods available.
00:59    There's a method called Equals,
01:01    another one called GetHashCode,
01:03    and the one I'm concerned with right now, ToString.
01:07    Every object in C# has a ToString method,
01:10    because every class is extended from the object class.
01:14    And this method is called automatically.
01:17    Whenever you take an object and pass it somewhere
01:20    that's expecting a string.
01:22    This is already at work in my code.
01:25    I'm working in a version of my solution
01:27    called ToString right now,
01:29    and I've defined these custom classes,
01:32    and I've instantiated them and set their properties.
01:35    And then at line 34, I'm looping through the items
01:39    and outputting the items one at a time.
01:42    When I run the code, all I get is the fully qualified type
01:47    of the class.
01:48    The namespace and the class name.
01:51    But you can override that method.
01:54    You can create your own custom version
01:56    of the ToString method and it will output whatever you want.
02:00    I'll go down to my declaration of my fruit class,
02:04    and I'm going to add an override.
02:08    I'll place the cursor after my existing declarations,
02:10    but still within the class, and I'll type
02:13    the keyword override and press the spacebar.
02:17    And the list shows me the items that I can override.
02:21    The Equals method, the GetHashCode method
02:23    and the ToString method.
02:26    I'll choose ToString, and that expands to a
02:29    full code template, including the full signature
02:33    of the ToString method.
02:35    Notice the use of the override keyword.
02:39    That's a declaration to the compiler that's saying,
02:41    I'm using the same name and same return data type
02:45    as the superclass's version and I know I'm doing it.
02:49    And I want you to use this version of the method
02:51    instead of the base or superclass's version.
02:54    By default, this override version returns the value
02:58    from the base version.
03:00    But we don't want that, we want to create
03:02    our own custom output.
03:04    So I'm going to get rid of that expression
03:07    and then after the return statement,
03:09    I'll return the values from the properties,
03:12    Name, Weight and Quantity.
03:15    I'll start with Name, and then I'll add a space
03:18    and an open parentheses, and then I'll output the Weight.
03:23    And then I'll use the abbreviation for ounces, oz,
03:27    and a closing parentheses and a space and then a colon.
03:32    And then after that I'll output the Quantity.
03:36    And so that's my full expression.
03:38    I'm outputting all of the property values,
03:41    separated by literal strings as I like.
03:44    Now, I'll remind myself by looking at the vegetable class,
03:48    that if I want this to behave the same, I would need
03:51    to copy and paste the ToString method here too.
03:54    But I'm not going to do that.
03:56    I'm going to let the vegetable class
03:58    use the default ToString method, the base class's version.
04:03    I'll save and run the code, and there's the result.
04:07    I see for the fruit, that I'm getting the name of the fruit
04:10    in all uppercase, then I'm getting the number of ounces,
04:14    the weight, and then the quantity after the colon.
04:18    For the vegetable class, I'm still getting just the
04:20    fully qualified data type.
04:23    I'll close the console, and return to the code.
04:26    Then I'll take this ToString method definition,
04:30    I'll copy it, I'll go to the vegetable class
04:33    and I'll paste it, and then I'll run the code again.
04:37    And now I'm getting similar output,
04:40    but I'm not getting the vegetable in all uppercase,
04:43    because I didn't put that code into that class.
04:46    The ToString method is incredibly valuable.
04:49    You might use it, as I'm doing here,
04:51    for actual application requirements,
04:53    or you might use it just for debugging.
04:56    So you can easily display the values
04:58    that are encapsulated within a data object,
05:02    in the console as your running your code.
05:04    Either way, understanding how to override methods
05:07    is a critical part of object-oriented programming,
05:11    and it's easily supported in C#.
Collapse this transcript
Adding multiple constructor methods
00:00    - In object oriented programming,
00:02    a Constructor method is a special kind of method
00:05    that has the same name as the class
00:07    that it's defined as a part of
00:09    and that's used to create an instance of the class.
00:14    When you create your own custom classes,
00:16    you don't have to explicitly declare a constructor method,
00:20    but if you don't, a constructor method
00:22    is generated for you by the compiler.
00:25    It doesn't receive any arguments or parameters
00:28    and it's sometimes called a no arguments Constructor,
00:31    but you can create your own custom constructor methods too.
00:36    There's one very important rule.
00:38    If you create a custom constructor method,
00:40    your class must have a no arguments constructor method
00:43    that's explicitly declared.
00:45    You can have multiple constructor methods
00:48    as long as they differ in either
00:50    the number of parameters or the data types
00:53    of the parameters.
00:55    Once again, I'm working with my custom class
00:57    that I named Fruit.
00:59    And I'm working in a version of the solution now
01:01    called multiple constructors.
01:03    I'm going to start by declaring
01:05    the no arguments constructor.
01:08    All constructor methods have the same name as the class.
01:12    So, I'll start with Fruit.
01:14    Then I'll put in a pair of parenthesis with no parameters
01:17    and then a pair of braces.
01:20    I'm not going to place any code here.
01:22    And so far, I'm only doing what
01:24    the compiler would have done for me anyway,
01:27    create the no arguments constructor.
01:29    Next, I'll create the custom constructor
01:32    I'm really interested in.
01:34    Once again, I'll use the name of the class,
01:37    but this time, I'll declare three parameters or arguments.
01:42    And they'll share the same names and data types
01:45    as the fields or properties I've already declared.
01:49    I'll have a string parameter called name,
01:52    a double parameter called weight,
01:54    and an int parameter called quantity.
01:57    Now, within the constructor method
01:59    I'll take those parameter values that are passed in
02:02    and I'll save them to the properties, like this.
02:06    I'll say, "name = name,
02:09    "weight = weight, and quantity = quantity".
02:13    Notice that I'm calling the property objects
02:15    and that implicitly is calling the set methods.
02:19    When I say "quantity = quantity",
02:22    I'm calling the short hand set method
02:24    of the quantity property,
02:26    but when I say, "weight = weight",
02:28    I'm calling this explicit set method.
02:31    And whatever I pass in here,
02:33    shows up within the set method
02:35    as the value parameter.
02:37    So now, this gives me an easy way of creating
02:39    instances of the Fruit class
02:42    and declaring the values on a single statement.
02:45    I'll go back up here to where I'm creating my objects
02:49    and I'll go to my Fruit constructor method call.
02:53    And I'll pass in the same values I was using before,
02:56    Apple, 8.5, and 3.
03:00    And then I'll take these three lines of code
03:03    and delete them.
03:05    Then I'll do the same thing for the second Fruit object.
03:08    I'll pass in Banana, 4.5, and 7.
03:13    And I'll get rid of these three lines of code.
03:17    Now, I can't do this yet with the Vegetable class
03:19    because I haven't declared the custom constructor.
03:23    So, I'll come down here.
03:25    I'll select both of these constructor method declarations.
03:30    I'll copy them to the clipboard.
03:33    I'll move down to the Vegetable class
03:34    and I'll paste these in.
03:37    And then, I'll correct them
03:39    by changing the names of the constructor method
03:42    to match the class,
03:43    Vegetable in both cases.
03:46    So now, both the Fruit and the Vegetable classes
03:49    have custom constructor methods.
03:52    And I can move back up here
03:53    to where I creating my Vegetable
03:55    and I can pass the values in
03:57    just like I did before.
03:59    With Carrot, 4.1, and 16.
04:04    And these three lines of code are no longer required.
04:07    I won't delete them this time.
04:10    I'll just comment them out with ctrl + k, ctrl + c.
04:14    And I'll run the code again
04:16    and I get exactly the same results
04:17    as I did before, but with a lot fewer statements
04:21    in my program.
04:23    So, custom constructor methods
04:25    make it very easy to create custom classes
04:28    that you can instantiate with values
04:31    in single statements.
04:33    And there are other ways of using
04:34    custom constructor methods in your code
04:37    to make your application easier to write
04:40    and easier to maintain.
Collapse this transcript
Organizing classes with namespaces
00:00    - Namespaces are used in C# to organize classes.
00:04    Each class is a member of a namespace.
00:07    When you create a new project in Visual Studio,
00:10    your automatic namespace is the same as the project name.
00:14    So my project is named ConsoleApp in this solution
00:18    and my namespace has the same name.
00:21    You declare classes inside namespace declarations,
00:24    but when you want to create a complex application,
00:27    it can be useful to create separate namespaces.
00:31    One namespace for the main program,
00:33    one for data item classes, one for utilities, and so on.
00:39    You can name your namespaces however you want.
00:42    You should follow the convention of using Pascal casing
00:45    for the names, using uppercase initial characters
00:49    and then CamelCasing for the rest.
00:51    But after that, it's really up to you.
00:54    I'm going to demonstrate re-organizing an application
00:58    using this version of my project called Namespaces.
01:02    Right now my two data classes, Fruit and Vegetable,
01:06    are declared inside the Program.cs file,
01:09    and so they're a part of the same namespace as Program.
01:14    I'm going to move these now to separate files
01:17    so I can put these classes in different namespaces.
01:21    I'll start by creating a new class file.
01:24    I'll go to my project in the Solution Explorer,
01:27    and I'll right click and choose Add, New Item.
01:32    I'll choose Class as the type of item I'm creating.
01:35    I'll make sure this is in C#,
01:38    and I'll name this Fruit.
01:40    So there's my Fruit class, so far so good.
01:44    Now I'll go back to the program,
01:46    and I'll select all the code that I've already created
01:49    inside the Fruit class in this file.
01:52    I won't include the class declaration itself,
01:55    and I'll copy that code to the Clipboard,
01:58    and I'll come back here,
02:00    and I'll paste the code inside my new class declaration.
02:06    Then I'll come back here to the Program class,
02:08    and I'll select the entire class and I'll delete it.
02:14    So now my program file has both my Main program class
02:18    and it also has the Vegetable class, but the Fruit class
02:22    has been placed in its own file over here.
02:24    So I'll run my application and make sure
02:26    everything still works.
02:28    Now I'll go back to my code and I'll go to the Fruit class,
02:33    and I'll change the namespace
02:35    that the Fruit class is defined in.
02:38    I'll go to the namespace declaration,
02:40    and I'll use a namespace of ConsoleApp.Model.
02:46    The word model in object-oriented programming
02:49    refers to classes that are used to organize data.
02:53    So I'm going to be putting my Fruit and my Vegetable classes
02:56    in the same namespace.
02:58    I'll save that change and come back to my Program class,
03:02    and now, I have an error that's going to show up.
03:05    Now I'm told that the type or namespace
03:08    named Fruit can't be found.
03:10    After creating a custom namespace, which is purely
03:13    code base, you then have to go back to references
03:16    to the classes that you moved, and update that code,
03:20    so the compiler can find the classes.
03:23    Remember that when you create a new project,
03:26    you end up with all these using declarations.
03:29    These are referring to namespaces that contain
03:32    classes you might be using.
03:34    So you can do the same thing with your custom namespaces.
03:38    I'll go to the first reference to that class, Fruit,
03:41    and I'll place the cursor after the class name,
03:44    and I'll press ctrl + . and I'm told
03:48    I can either create a new class name Fruit that's in
03:51    this namespace or, as I want to do, I can add
03:55    a using declaration for this namespace.
03:59    I'll select that, and that adds the using declaration
04:03    at the top of the list.
04:05    Then I'll clean up my using declarations
04:07    and get rid of the ones I don't need.
04:10    I'll right click and choose Organize Usings
04:13    and then remove the unused ones, and I'm left with
04:16    only the ones I'm actually using in my code.
04:20    I'll save and run the code again
04:23    and everything is still working okay.
04:25    Now, I'll do something very similar
04:27    with the Vegetable class,
04:29    but instead of creating an entirely new file,
04:33    I'm just going to take the Vegetable class declaration
04:36    and I'm going to move it into the same file
04:39    that declares the Fruit class.
04:42    In C#, you don't need to have a separate file
04:45    for each public class, the way you do in Java.
04:49    So I'll come back here to my Fruit class,
04:52    and I'll move down here,
04:54    and I'll make a little bit of space and I'll paste this in,
04:58    and then I'll take a look at the class declarations.
05:02    They're both inside the new namespace, ConsoleApp.Model.
05:07    There is Fruit and there is Vegetable.
05:10    I'll save that change.
05:12    I'll come back here to the program,
05:14    I'll save the change there,
05:16    and before I run, I'll do another build,
05:20    and I'm told that I don't have any errors.
05:23    Because both the Fruit and the Vegetable classes
05:26    are in the same namespace, I only need a single
05:29    using declaration to be able to have access to them.
05:33    Then I'll come back here to Fruit.cs,
05:36    and I'll press f2 to rename the file,
05:40    and I'll call it Produce, and then I'll build again,
05:44    and it still works.
05:46    The name of the file and the name of the class
05:49    are not related to each other.
05:51    As long as the file is a part of your project,
05:54    the compiler will be able to find it,
05:56    and it will be able to find all the class declarations
05:59    that are in there.
06:01    And I'll run the code one last time,
06:03    and there's the result.
06:05    I'm finding the classes and I'm able to instantiate them
06:09    and use them in my program.
06:11    Finally, I'll show one more step.
06:14    If you like, you can take files that are in a
06:17    separate namespace and put them in their own
06:19    subfolder of the project.
06:22    Again, this isn't like Java.
06:23    In Java, you have packages and each package has its
06:27    own unique subfolder within the file system.
06:30    This is a completely optional step in C#,
06:34    but I'll follow it.
06:35    I'll go to the Solution Explorer and right click
06:37    on the project, and select Add, New Folder,
06:42    and I'll name the new folder Model.
06:47    Then I'll go to the Produce.cs file,
06:50    and I'll drag it into that folder.
06:53    Then I'll once again rebuild,
06:56    everything appears to work okay,
06:58    and I'll run the application with ctrl + f5,
07:01    and I've verified that the application works
07:03    as it did before.
07:06    So this is how you can organize an application
07:08    using namespaces and folders.
07:11    It's a completely optional step in C#,
07:14    but for larger, more complex applications that might have
07:17    dozens or even hundreds of classes, namespaces and folders
07:22    give you a very easy way to keep everything organized
07:25    and easy to find.
Collapse this transcript
9. Working with Inheritance and Polymorphism
Extending a class to create a new class
00:00    - C# implements inheritance using very simple syntax.
00:04    I'll demonstrate this using this application
00:07    named Inheritance.
00:09    In this version of my application,
00:11    I have a list containing objects,
00:14    and I'm adding fruit objects
00:15    and vegetable objects to it.
00:18    I'm going to implement inheritance
00:20    by creating a base or superclass named produce,
00:24    and then each of the two classes, fruit and vegetable,
00:27    will be extended from that class.
00:30    I'll start in my file produce.cs
00:33    that's in the model folder.
00:35    I'm going to refactor or rename this class named fruit.
00:40    I'll double click on the class name,
00:43    then I'll right click on it
00:45    and choose Refactor, Rename.
00:48    When you refactor, you're going to rename the class
00:52    and all the references to the class.
00:55    I'll name it produce, and then I'll click OK,
00:58    and that changes the name of the class
01:01    and the name of its constructor methods in this file.
01:05    But it also changes the name of the class
01:07    when it's being instantiated in the program file.
01:12    So that's refactoring.
01:13    It's a very simple operation,
01:15    but it's great for maintaining your code.
01:20    Now I have a class named produce
01:22    which has two constructor methods,
01:24    two private fields with public properties,
01:27    and one public property, quantity,
01:30    that has shorthand get and set declarations,
01:33    and the custom ToString method.
01:36    Now I still need a class named fruit
01:39    so I'm going to create that class again.
01:42    I'll place the cursor after the produce class
01:44    and before vegetable,
01:46    and I'll create a new class that I'll name fruit.
01:50    Then I'm going to indicate that this is a subclass
01:53    or a derived class of produce.
01:57    I'll put in a colon and then the name of the class
02:00    that I want to extend.
02:02    The colon acts like the extends keyword in Java.
02:06    Then I'll put in the code block for the class declaration.
02:09    I'm not quite done yet.
02:11    In order to instantiate the fruit class directly,
02:14    I need to add constructor method definitions.
02:18    So just like before,
02:20    I'll create a no arguments constructor,
02:22    and I'll create the version of the constructor
02:24    that I want to call that accepts the arguments
02:28    for the name, weight, and quantity.
02:30    I'll repeat the same signature as I used
02:32    in the original class,
02:34    but then I'm not going to define what it does.
02:38    Instead, I'm going to say,
02:40    "When this constructor method is called,
02:42    "take these values and pass them
02:45    "to the base classes version of the constructor."
02:48    I'll do that by placing a colon
02:50    after the constructor method signature.
02:53    Then I'll use the word base in lowercase.
02:56    That means call the constructor method of the base class.
03:00    After I put in the parentheses,
03:03    I see the signatures of the two constructor methods
03:05    of the base class,
03:07    and I'll pass the values in with their names;
03:11    name, weight, and quantity.
03:15    Finally, I'll put in the braces for the code block.
03:19    That's all I need to do to define the fruit class.
03:22    The fruit class is now inheriting everything
03:25    that the produce class defines,
03:27    its public properties, and the override
03:30    of the ToString method.
03:32    I'll run the code and there's the result.
03:36    It still works exactly the same as before,
03:38    but now to really test this,
03:40    I'll go back to program.cs,
03:43    and instead of instantiating the produce class,
03:47    I'll instantiate the fruit class.
03:49    I'll run the code again,
03:51    and sure enough, everything is still working fine.
03:55    Now, I'll make the same changes to the vegetable class.
03:59    I'll go back to produce.cs,
04:02    and I'm going to select and copy
04:04    these two constructor method calls.
04:08    Then I'll go down to vegetable,
04:11    and I'll add the code that extends vegetable from produce.
04:16    Then I'm going to delete all of the detailed code
04:18    within the vegetable class definition.
04:21    Then I'll come back to the code block
04:23    and paste in those constructors,
04:26    and change both of them to conform
04:28    to the name of the class
04:29    changing from fruit to vegetable.
04:34    Then, once again, I'll run the code.
04:38    Everything is still working exactly the same as before.
04:41    So I've successfully now created
04:43    an inheritance hierarchy.
04:45    I could extend the inheritance hierarchy further
04:48    creating classes that are subclasses of fruit
04:52    named banana, grape, and pear;
04:54    and subclasses of vegetable named carrot and asparagus.
04:58    It's up to you to define the inheritance hierarchy
05:01    that makes sense for your application,
05:04    but C# provides all of the syntax you need
05:06    to quickly and easily define
05:09    that inheritance relationship
05:11    and implement it in your app.
Collapse this transcript
Overriding and calling base class methods
00:00    - I've previously described
00:01    how to override base class methods.
00:05    In my Produce file, I've defined three classes named
00:08    Produce, Fruit, and Vegetable.
00:11    Right now, the Produce class
00:13    overrides its base class method called ToString.
00:17    The ToString method is implemented in the object class
00:21    and every C# class is extended from that
00:24    and so it inherits the ToString method,
00:27    but as I showed
00:28    the default ToString method only outputs
00:30    the data type of the class,
00:32    not any data that's specific to the application,
00:36    and by overriding the ToString method,
00:38    I allowed the object to report its contents.
00:42    Now, I'll describe how to do a secondary override.
00:45    How to override this same method in the derived classes,
00:49    Fruit and Vegetable,
00:51    and add to what the base class is providing.
00:54    I'll go to the Fruit class
00:56    and I'm going to add the new method.
00:58    I'll start as I did before by typing the word 'override'
01:02    and pressing the spacebar.
01:04    I'll choose the ToString method.
01:06    Now, just as before, by default,
01:08    I'm calling the base classes ToString method,
01:11    but now I'm calling the Produce version,
01:14    not the object version.
01:16    I'm only going up one level in the hierarchy.
01:19    I can either leave it like that,
01:21    or I can write my own custom code,
01:23    or, as I'm going to do here, I can combine the two.
01:27    I'll type the word 'Fruit;'
01:31    and then I'll append to that
01:33    the results of the base class output.
01:35    So, now I'm not totally replacing what the base class does,
01:39    I'm just modifying it.
01:41    Then, I'll do the same thing in the Vegetable class.
01:45    I'll add the override keyword and press space.
01:48    I'll choose ToString
01:50    and in the return statement, I'll start with 'Vegetable'
01:54    and then I'll append the return value
01:56    of the base classes version of the ToString method.
02:00    I'll run the code.
02:02    There's the result.
02:04    Each of the derived classes is benefiting
02:06    from the use of the Produce class.
02:09    If I want to change anything now
02:11    about how all these classes behave,
02:13    I can do it in the Produce class
02:15    and those changes will be inherited by the derived classes.
02:20    I'll go back to the Produce class, to the name property,
02:24    and this is where I'd earlier placed the code
02:27    that converted names to uppercase.
02:30    I'll remove that code,
02:32    so now I'm just returning the raw name.
02:35    I'll save the change and run the code again,
02:38    and I see the name now as it was placed into the object
02:42    without the uppercasing.
02:44    You can make any other changes you like
02:46    to the behavior of the base class
02:48    and those changes will be inherited by the derived classes.
02:53    So, overriding methods
02:54    is a common object oriented programming technique.
02:58    You can accept the default behavior
03:00    from the base class, or you can replace that behavior,
03:04    or as I've done here, you can combine customizations
03:07    with the original behavior
03:09    to make your derived classes do what you need.
Collapse this transcript
Creating methods that accept subclassed objects
00:00    - In object-oriented programming,
00:02    the term, polymorphism,
00:04    means the ability of an object
00:07    to be both its own native type,
00:09    and its base or supertype.
00:12    For example, a fruit can also be produce.
00:16    An apple can also be fruit.
00:18    A carrot is also a vegetable.
00:21    You can write programming code
00:23    that treats the object as one or the other,
00:26    depending on what you need.
00:28    One of the most valuable aspects of this,
00:31    in C-sharp and other such languages,
00:33    is that you can write methods that accept parameters.
00:37    You can say, "This method requires a fruit."
00:40    Then you can pass in a fruit object,
00:43    or a banana object, or an apple object.
00:46    Or, you can write code that says,
00:48    "I can accept any produce."
00:50    Then, you can accept either fruit or vegetable,
00:53    because the inheritance hierarchy says that
00:56    this object is both a fruit and an item of produce.
01:01    I'll demonstrate this in this solution,
01:03    named Polymorphism.
01:06    I'm going to start by creating a new class.
01:09    I'll place it in my Model folder,
01:11    and I'll right-click and select Add, New Item.
01:16    I'll choose Class.
01:18    I'll name this ProduceUtility.
01:21    This will be a class that has some static methods.
01:24    My goal will be to write some code
01:26    that does calculations on the data objects.
01:30    That is the fruit and vegetable objects that I'm creating.
01:34    First, I'll create a method
01:36    that accepts a single produce item,
01:38    and calculates its total weight,
01:40    by multiplying the weight times the quantity.
01:43    I'll start with public, static, double.
01:47    Public will make the method
01:49    available to the entire application.
01:51    Static will make the method callable
01:53    from this class name.
01:55    Double means that's the data type that I'll be returning.
01:59    I'll name this new method, GetItemWeight.
02:03    I'll accept in the instance of the produce class.
02:06    Now, within the method, I'll just return
02:08    the results of a calculation.
02:11    That calculation will be item.Weight * item.Quantity.
02:17    That's the entire method.
02:20    I'll save that change,
02:21    and then I'll go back to my program file.
02:24    Now, I've created three objects,
02:27    two instances of fruit, and one a vegetable.
02:30    But, the method I just created
02:32    isn't expecting instances of either of those classes.
02:35    It's expecting produce.
02:37    But, because produce is the base class
02:40    of fruit and vegetable,
02:42    I can pass in the derived object instead.
02:45    It'll be treated exactly the same,
02:48    because these objects are derived from the base class.
02:52    The compiler knows that the base class's
02:55    methods and properties are there.
02:58    They were inherited automatically.
03:00    Now, I'll go down here
03:02    to where I'm outputting the item,
03:04    using the item's two-string method.
03:07    I'll change this output as follows:
03:10    In addition to the item,
03:12    I'll append a comma and a space.
03:16    Then, on the next line,
03:18    I'll call my new method
03:19    with ProduceUtility.GetItemWeight,
03:24    and I'll pass in the item I'm currently working on.
03:27    Then, I'll also append "oz",
03:30    the abbreviation for ounces.
03:33    I'll check my code,
03:34    and I get an error that says I can't convert
03:36    from an object to the produce class.
03:40    The reason I'm running into that
03:42    is because item is coming
03:44    from the list of objects, named produce.
03:48    Earlier on, I had taken a shortcut.
03:50    I had said that this list contains objects.
03:53    I didn't say that the items in the list
03:56    would be instances of the base class produce.
03:59    Yet, that's what I'm expecting in foreach loop.
04:03    So, I'll change it here.
04:05    I'll say my list contains Produce items.
04:08    Now, I'll build the application again,
04:11    and it compiles without errors.
04:13    I'll run it.
04:15    There's the result.
04:17    I see the total weight after the listing
04:19    of the name, the weight, and the quantity.
04:23    I'll add just a little bit more text
04:25    to make this more readable.
04:27    I'll go to the literal string that currently has
04:29    just the comma and space,
04:31    and I'll add, total weight:.
04:34    I'll run it again.
04:36    Now, the output makes more sense.
04:39    Polymorphism works on individual objects,
04:42    but it also works on lists.
04:45    Let says, for example, that you wanted
04:46    to write a method that accepted
04:48    a list of produce items,
04:50    and calculated the total weight.
04:53    I'll go back to my ProduceUtility file,
04:56    and I'll define a new static method
04:58    that returns double, just like before,
05:01    and I'll name this one GetTotalWeight.
05:04    This method will receive, as an argument,
05:07    the list of produce objects.
05:10    Now, because we're looking for produce objects,
05:13    we know that the weight
05:14    and quantity properties will be there.
05:17    I'll use a foreach loop.
05:19    I'll loop through the produce collection.
05:23    Before I do the looping,
05:24    I'll declare a variable, named result.
05:28    I'll initialize it to 0.
05:30    Then, within the loop, I'll add to the result,
05:33    the calculation of the current item's weight and quantity,
05:36    just like I did before.
05:38    Finally, after the loop, I'll return the result.
05:42    I'll save those changes.
05:44    I'll come back to my program file.
05:46    I don't need to make any changes here.
05:49    The object produce is already declared,
05:52    using exactly the same data type
05:54    as what the method expects,
05:56    a list of produce items.
05:59    It's perfectly fine that, when I created these objects,
06:02    I said that they were fruits or vegetables,
06:05    because fruits and vegetables are produce.
06:08    I'll run the code,
06:09    just to make sure everything still works so far.
06:13    Then, I'll come down here,
06:14    under the foreach loop in the program file.
06:17    I'll output to the Console,
06:19    starting with Total weight.
06:22    Then, I'll append to that,
06:23    ProduceUtility.GetTotalWeight,
06:27    and I'll pass in the produce list.
06:30    Then, at the end, I'll append "oz,"
06:33    the abbreviation, once again, for ounces.
06:36    I'll save and run the code.
06:38    Now, when I run it,
06:39    it all works perfectly,
06:41    calculating the total weight for each individual item,
06:44    but then calculating the total weight for the entire order.
06:48    That's how polymorphism works.
06:51    You can define methods that treat objects
06:53    either as their native type,
06:55    or as their base type.
06:57    This lets you write code that's enormously flexible,
07:00    and very easy to maintain in the long run.
Collapse this transcript
10. Visual Programming and Event Handling
Setting visual component property values
00:00    - I've spent a good part of this course
00:02    working with C# in a console application.
00:06    But the reality is that most C# developers
00:09    are building Visual applications
00:11    for desktop, web, or mobile.
00:14    And so I'm going to wrap up the course
00:16    going back to a Visual environment:
00:18    Windows Presentation Foundation,
00:20    and I'm going to talk about how
00:22    what we've learned about object-oriented proramming
00:25    applies to Visual programming.
00:28    In Windows Presentation Foundation,
00:30    everything is an object.
00:32    That includes the main window
00:34    that's a part of every dialog box,
00:36    the grid that's used to lay out objects,
00:39    and objects that you place
00:40    in the Design area of your application.
00:43    I've opened a project named VisualProperties,
00:46    which is a beginning Visual application built with WPF.
00:50    And I'll go to the Toolbox
00:51    and drag in a couple of objects.
00:54    First I'll place a Button,
00:57    and then I'll place a TextBlock.
00:59    Then I'm going to set the font size
01:01    for both objects using the Properties Panel.
01:05    I'll select the Button,
01:07    then I'll go down here to the Properties Panel,
01:10    I'll choose the Text category,
01:13    and I'll change the size of the font to 24 pixels.
01:17    Then I'll do the same thing for the TextBlock.
01:20    I'll select it, and change it to 24 pixels.
01:24    And that makes both objects more readable on the screen.
01:27    Next I'll place the objects flush left in the application.
01:32    Now, I'm affecting properties of objects,
01:35    and these objects are instances of C# classes.
01:40    TextBlock is a class, Button is a class, and so on.
01:44    And you can affect these properties in C# code
01:46    in the same way that I was affecting them before
01:49    when I was working in a non-Visual console application.
01:54    In order to affect these properties though,
01:56    each object must have an identifier,
01:59    known in WPF as the object's name,
02:02    and in ASP.NET as the ID.
02:05    I'll select my TextBlock and go
02:08    to the Properties Panel and set the name to txtOutput.
02:12    In WPF, that's applied using an attribute called x:name,
02:18    which you see in the XML code down below.
02:21    Now I'll go the C# file.
02:24    This is, as I described earlier in the course,
02:27    the code-behind file for the XML file.
02:31    Notice the declaration of this class
02:33    says public partial class,
02:36    and that it's derived from, or extends, the Window class.
02:40    So we're following standard object-oriented techniques here.
02:44    Each class is a subclass of another class, and so on.
02:48    Also, applying other things I've shown in this course,
02:51    this is the constructor method for the MainWindow class.
02:55    It has the same name as the class itself,
02:58    and so it's called automatically
03:00    as the Window is instantiated.
03:03    Now in a Visual application,
03:04    the framework instantiates this class for you.
03:08    You don't do it yourself as the programmer.
03:11    But it's quite easy to deal with Visual objects
03:13    in this code because this method
03:15    will be called automatically as the Window opens up.
03:20    So here, I'm going to change the display of the screen
03:23    using the command txtOutput.Text,
03:27    and then I'll set a value.
03:30    And then I'll run the application.
03:33    As the application opens,
03:34    the constructor method is automatically called,
03:38    and I'm using the name of the object in WPF
03:41    to address its public property: Text.
03:44    And so this is exactly the same
03:46    as the techniques that I was showing
03:48    earlier in console applications.
03:51    A lot of what you do in this sort of Visual programming
03:54    is changing the display so the user knows
03:57    what's going on in the background.
03:59    The actual work of the application
04:01    might be hidden in business logic classes,
04:06    classes that have static methods,
04:08    or data objects, but this is what the user sees,
04:12    and using the C# programming language,
04:15    you have complete control over
04:16    the appearance of your application.
Collapse this transcript
Handling visual component events
00:00    - Visual development environments
00:02    are typically event-based.
00:04    In the Microsoft world,
00:06    this includes environments
00:07    such as Windows Presentation Foundation,
00:10    Windows Forms, ASP.net for the Web,
00:13    Windows Phone for mobile,
00:15    and Windows Store applications for Windows 8.
00:19    In all of these environments,
00:21    you can listen for events
00:23    and react to them by executing C# code.
00:26    The process is pretty much the same
00:28    from one environment to the next.
00:30    You can register to listen for and react to an event
00:33    either in your XAML markup code,
00:36    or in C#.
00:39    I'll demonstrate listening for an event
00:41    in this version of a project named Handle Events.
00:45    I already have a button and a text block control.
00:49    I'll click on the button,
00:50    and in the Properties panel,
00:52    I'll assign a name of btnClickMe.
00:57    Now, it's not absolutely necessary
00:59    to assign a name to a control
01:01    if all you want to do is listen for the event.
01:04    But it's useful in your code
01:06    to be able to identify the control.
01:09    After naming the button,
01:11    I'll then click on the icon with the lightning bolt.
01:14    This shows me a list of the event handlers for this control.
01:19    The first one on the list is named Click.
01:22    This is the most commonly-used event
01:24    of the button control.
01:26    When the user clicks the button,
01:28    you get a button event
01:30    and you can listen for the event
01:32    and you can react.
01:35    I need to generate a method that will be called.
01:38    It's known as an "event listener."
01:40    Visual Studio makes this very easy.
01:43    I'll just double-click in the text box
01:45    next to the word "Click,"
01:47    and in the XAML file,
01:49    that resulted in generating a name of a method,
01:53    and in the code-behind file,
01:55    the method "skeleton" was created.
01:57    When an event listener is executed,
01:59    it receives a couple of parameters.
02:02    The one I'm going to deal with is the first one.
02:05    It's called the "sender."
02:07    It's data-typed as a simple object.
02:10    But it's native type is
02:12    whatever control this variable represents.
02:16    In my case, it's a button.
02:19    The button control has a number of very useful properties.
02:23    But to address those properties,
02:25    I have to cast the sender variable and say,
02:28    "I know this is a button object."
02:31    Here's how you do it.
02:33    I'll declare a variable with a data type of button.
02:37    I'll name the variable "myButton,"
02:39    and I'll assign its reference from the sender parameter.
02:43    That's not going to work on its own, though.
02:46    The compiler is saying, "Wait.
02:48    "This parameter is an object, not a button.
02:51    "Are you sure?"
02:53    And in order for me to tell the compiler,
02:55    "I know for sure that this is a button object,"
02:58    I'll use casting syntax.
03:01    I place the data type in parentheses
03:04    and place it right before the variable.
03:06    That means I am now allowed
03:08    to address this object as a button.
03:11    Next, I'll go to the documentation
03:13    for the button class.
03:15    I'll place the cursor on the word "button"
03:16    and press F1.
03:18    That takes me to the Help viewer.
03:20    The button class has a large number
03:22    of properties and methods that you can use
03:25    to find out what happened,
03:27    including what object was actually clicked.
03:30    For example, it has a name property,
03:33    which is way down here,
03:35    and it has other properties that I'll demonstrate.
03:39    To learn more about visual programming,
03:41    I recommend starting with this control
03:43    because it has so many of the properties
03:45    that are shared with other controls
03:47    and it's used so frequently in applications.
03:52    I'll start by getting the name of the object.
03:55    I'll declare a variable called "name,"
03:57    data typed as string,
03:59    and I'll get that from myButton.Name.
04:02    Next, I'll get the date type of the object.
04:05    I'll create a variable called "type"
04:08    and assign it with the following expression:
04:11    myButton.GetType.
04:15    That's a method, so I'll add the parentheses
04:18    and then the Name property.
04:20    Now I have the name of the object,
04:23    that's the identifier that I assigned,
04:25    and the type as a string.
04:28    Finally, I'll get the label from the button.
04:31    The variable will be named "label,"
04:34    and the expression will look like this:
04:37    myButton.Content.ToString.
04:41    The content property of the button
04:43    represents the string that's displayed on its face.
04:47    I refer to it as a label
04:49    because that's the property name
04:50    I've used in some other languages.
04:53    But you can name it "content," if you like.
04:55    Now, I'll show the user what they did.
04:58    I'll use my text block
05:00    that already has a name of txtOutput.
05:03    I'll set its text property like this.
05:06    I'll start with a literal string
05:08    of "You clicked a,"
05:10    and then I'll append the type.
05:12    Then I'll add another string
05:14    and then the name.
05:17    Let's test that.
05:19    I'll save and run the code.
05:21    I'll click the button.
05:23    And I see, "You clicked a Button named
05:25    "btnClickMe."
05:27    So far so good.
05:29    Now let's add a bit of code
05:31    and I'll display the label from the button.
05:34    I'll append to the existing text object.
05:37    I'll start with txtOutput.text.
05:40    Then, I'll use the concatenation operator.
05:43    += means "keep the content you already have,
05:47    "but add this to it."
05:50    Next, I'll add a new line.
05:52    In WPF, you do this with the expression
05:55    "Environment.newLine."
05:58    Then, finally, I'll say "The button says,"
06:02    and then I'll append the label variable.
06:06    I'll run the code again.
06:09    This time, I get the entire output.
06:12    Now I can change the label on the button.
06:16    I'll go back to my XAML file,
06:18    and with the button still selected,
06:20    I'll go to the properties
06:22    and I'll change the content for the button
06:24    from "Button" to "Click Me."
06:28    I'll make the button a little bit wider,
06:29    to make sure all that text is displayed.
06:33    Then I'll run the application again.
06:35    I'll click the button.
06:37    Now it says, "The button says Click Me."
06:40    Learning how to get information from visual controls
06:43    when you listen for events
06:45    is a critical skill
06:47    when you're using C# to build visual applications.
06:50    Again, the programming model is pretty much the same,
06:53    regardless of whether you're programming
06:55    for desktop, web, mobile,
06:58    or Windows Store apps.
07:00    In all of these Microsoft development environments,
07:03    the model is the same:
07:05    listen for the event,
07:07    and write some C# code that you want to execute
07:10    when the event occurs.
Collapse this transcript
Challenge: Creating a visual calculator in Windows Presentation Foundation (WPF)
00:00    "(cymbal swell)"
00:03    - In the first challenge in this course,
00:05    we built a calculator application for the Console
00:08    that was purely text based.
00:11    The user types values in, and then selected an operation
00:14    by pressing a key, and then the calculator did its work.
00:19    In this challenge,
00:21    I'll ask you to try building a visual calculator
00:24    that's designed for the desktop.
00:27    It'll use Windows Presentation Foundation or WPF.
00:31    The modern framework for Windows based desktop applications.
00:36    Just like the Console application,
00:38    it'll support the four standard mathematical operations,
00:42    but instead of typing in inputs and pressing a key
00:45    on the keyboard to select an operation,
00:47    the user will interact with this application
00:50    using their mouse.
00:53    The goal is to test your knowledge of C#
00:56    using as many aspects of the language that we've learned
00:59    as possible.
01:01    Some of the tools you'll need to use include:
01:04    conditional codes using both if-else and switch statements,
01:08    and of course you'll need to use the mathematical operators.
01:12    You'll need to structure your code
01:14    choosing whether to create classes with static methods,
01:18    or put all of your coding in one class,
01:20    or build it however you like.
01:22    I do recommend storing data in fields
01:25    and properties of the class
01:27    to maintain the state of the application.
01:31    In this kind of visual application,
01:33    you'll need to remember
01:34    what the user has previously selected,
01:37    so that when they press each button,
01:39    you'll be able to take the right steps.
01:41    The logic might differ from one mathematical operation
01:45    to the next.
01:47    Let's take a look at the finished version
01:49    of the application.
01:51    The exercise files for this final chapter include
01:54    two versions of the visual calculator application.
01:58    I'll go to the finished version first.
02:00    Now, I'm not going to show you any of the code,
02:03    that would ruin the joy of the challenge,
02:05    but instead I'm just going to run the application
02:08    by pressing 'F5', and then I'll demonstrate
02:11    what this application is able to do.
02:14    It can multiply,
02:16    so I'll click a number, and then the asterisk button
02:19    and then I'll click another number, and click equals.
02:23    Then, I'll clear the results.
02:25    Then, I'll do a division operation, six divided by three.
02:30    And, that's correct.
02:32    And, then I'll do a subtraction.
02:34    56 minus four,
02:36    and again, that's correct.
02:38    And then, I'll do addition.
02:40    So, that's how the application behaves.
02:43    You can do the four mathematical operations
02:46    and you can clear the results by clicking the 'C' button.
02:50    Now, let's take a look at the beginning state
02:53    of the application.
02:54    I'll close Visual Studio, and go back to the chapter folder,
02:59    and then I'll open the starting project.
03:02    The user interface is already built for you.
03:05    There are a bunch of buttons.
03:06    10 for the numeric values, one for the decimal point,
03:10    one for each of the four mathematical operations,
03:13    a clear button, and an equals button.
03:16    All of the buttons are rigged up to call certain methods.
03:20    For example, there are methods for the add, subtract,
03:23    multiply, and divide buttons.
03:25    And, there's one for the clear button,
03:28    and one for the equals button.
03:30    All of the numeric buttons, zero through nine,
03:33    and the decimal point button, all call the same method,
03:37    'BtnEntry_click'.
03:39    It's up to you to determine which button was clicked,
03:42    by examining the 'Sender' object.
03:44    The technique for that is something I showed
03:47    earlier in this chapter.
03:49    Once you get that value,
03:51    you'll need to store it.
03:52    Again, I recommend using a private field
03:55    that's a member of the current class
03:57    to store that information
03:59    and when the user selects one of the operations,
04:02    you'll need to add code to handle that.
04:05    Up at the top, I've declared two fields to get you started.
04:10    A double field named 'current value' initialized as zero.
04:13    And, an enumeration named 'operation'.
04:17    There are six possibilities.
04:19    The four mathematical operations,
04:22    the equals operation,
04:24    and the starting operation.
04:26    So, that's the beginning skeleton of the application.
04:30    If you're an experienced programmer,
04:32    you might find that this logic is pretty straight forward,
04:36    but if you're brand new to programming,
04:38    take your time.
04:39    Work through each bit of logic
04:41    and decide what aspects of the C# language would you need.
04:45    If at any point you want to see
04:47    how my version of the application works,
04:49    you can go to the finished version and take a look.
04:52    And, in the next movie,
04:53    I'll give you a complete code review of my solution,
04:56    so you can see how I solved this challenge.
Collapse this transcript
Solution: Creating a visual calculator in Windows Presentation Foundation (WPF)
00:02    - Now I'll describe my solution to the second challenge,
00:06    creating a visual application for the Windows desktop
00:09    using Windows Presentation Foundation.
00:13    It's in the VisualCalculatorFinish folder
00:15    under the exercise files.
00:18    I'll start in the code-behind file, MainWindow.xaml.cs.
00:23    As I showed previously, the starting file had
00:26    rigged up all the methods that I'm going to use.
00:29    It was my job to add all of the logic.
00:32    I started by adding code to accept data entry from the user.
00:38    I declared a boolean field called isNewEntry
00:41    and set its value to true.
00:44    Then I created the method BtnEntry_Click.
00:48    Each of the 10 numeric buttons and the decimal point button
00:53    all use this method as their Click event listener.
00:57    When the user clicks one of the buttons
00:59    this method we see is the object, named sender.
01:04    And as I've shown in one of the
01:05    movies in the current chapter,
01:07    I can find out what they selected
01:09    by examining the button's content property.
01:13    First I declared a variable named result.
01:16    I'll use that later on to test whether
01:18    they entered something I can work with.
01:20    Then I take that sender object and cast it as a button.
01:25    And then I find out the value they selected
01:28    by looking at the Content property of the Button object.
01:32    Now I know which button they selected.
01:34    Next I have a bit of special handling
01:36    for the decimal point button.
01:38    If the isNewEntry boolean value is true
01:41    then I return from this method.
01:44    That means they didn't type any numeric values already.
01:47    But if this isn't a new entry,
01:49    that is if they've already entered some numeric values,
01:53    then I take the value from the button
01:55    and I append it to the Text property
01:58    of the TextBlock on the screen.
02:00    And then I say isNewEntry = false.
02:03    And again, this functionality is only for the decimal point.
02:08    The next bit of code is for the numeric buttons.
02:12    I try to parse the value,
02:14    and make sure that I can turn it into an integer.
02:18    If I can't, then I ignore the input,
02:21    but if I can, I then do another test.
02:24    First I ask is this new entry,
02:27    or does the text field currently equal "0"?
02:30    And if so, I clear the Text value.
02:33    Then I append that value from the button
02:36    to the current text, and set isNewEntry = false.
02:40    Each time the user clicks one of the numeric buttons
02:43    or the decimal point, I'm executing this method.
02:46    I'm only going to do something with the value once they
02:49    click one of the operation buttons or the equals button.
02:54    Now let's take a look at the methods
02:56    for the different operation buttons.
02:58    They start at line 121.
03:01    And they all call the same method, named Calculate,
03:04    and pass in the selected operation.
03:08    That's an item from the Operation enumerator.
03:11    So let's jump to the Calculate method and see
03:14    where the really interesting work is happening.
03:19    The Calculate method receives that Operation as a parameter.
03:23    Next it parses the text property of the TextBlock
03:27    and turns it into a double value.
03:30    Then it checks to make sure we're
03:32    not asking for the last operation.
03:35    There's a field called currentOperation up here
03:37    and each time an operation is selected
03:40    it's being stored in this field.
03:42    I'll go back to the Calculate method.
03:45    And here's how I'm handling each of the operations.
03:49    The Add operation is the simplest.
03:51    I'm just saying this is the result,
03:53    the currentValue plus the newValue.
03:56    currentValue is either the first entry
03:59    or the cumulative result of multiple operations.
04:03    Subtract and Multiply are handled in the same way.
04:07    First I check the current value, and if it's zero,
04:09    I set the result to the new value,
04:12    the value they just entered.
04:14    But if there's another value already being stored
04:17    then I do the Subtraction operation.
04:19    And I follow the same sort of logic
04:22    with the multiply operation.
04:24    Divide always takes a little bit more work
04:26    because you have to prevent a divide by zero error.
04:29    So I check for zero values and take appropriate steps.
04:35    I only do a straight division operation if
04:37    neither of the values is set to zero.
04:40    Finally here are the other event handlers.
04:43    The Clear button just sets the
04:45    TextBlock's Text property to "0"
04:48    and sets the currentValue to zero,
04:50    and sets isNewEntry to true.
04:53    We're essentially just clearing the state and starting over.
04:56    And the Click handler for the Equals button
04:59    calls that calculate method again,
05:01    but this time says,
05:03    "Execute whatever the last operation was."
05:06    And that's how we're handling
05:07    division, multiplication and subtraction.
05:11    So that's all the code that I used
05:13    to create my version of the calculator.
05:15    Now there's no such thing as an
05:17    absolutely correct answer in this kind of challenge.
05:20    There are many ways to put this code together.
05:23    But if you finish the challenge and your results
05:26    behave the same way as mine, then it was correct.
05:30    If you see some patterns that I used
05:32    in my solution that you like
05:35    try them out in your application.
05:37    And it might be that you found
05:39    more elegant solutions than mine.
05:41    Either way, building this simple application
05:44    can help you test your knowledge of C#.
Collapse this transcript
Conclusion
Next steps
00:00    - Thank you for joining me for this course,
00:02    C Sharp Essential Training.
00:04    I hope it's helped you get started with C Sharp.
00:07    The most popular of Microsoft's Programming Languages
00:10    for their many development frameworks.
00:14    Learning the language is just the first step
00:16    to building complete applications.
00:19    To learn more, check out one of the many courses
00:22    in the lynda.com library for Microsoft Developers.
00:26    If you're interested in creating
00:28    dynamic web based applications,
00:30    you can look at these courses for ASP.NET,
00:34    ASP.NET Essential Training,
00:36    and ASP.NET MVC4 Essential Training.
00:41    To get started building mobile apps,
00:43    you can watch Windows Phone SDK Essential Training.
00:47    And to build apps for Windows 8,
00:49    take a look at Building Windows Store Apps
00:52    Essential Training or learn how to integrate these apps
00:55    with Cloud Services
00:56    in Using Windows Azure with Windows Store Apps.
01:02    Thanks again, and happy programming.
Collapse this transcript



Site map | Partner program | Privacy policy | Terms of Service | Website use policy
© 1995–2015 lynda.com, Inc.

    Follow
    About us
    Press
    Careers
    Products
    Support
    Site feedback

No comments:

Post a Comment