Cover

Table Of Contents

Table of Contents

The Story behind the Succinctly Series of Books

Chapter 1   Introducing C# and .NET

Chapter 2   Coding Expressions and Statements

Chapter 3   Methods and Properties

Chapter 4   Writing Object-Oriented Code

Chapter 5   Handling Delegates, Events, and Lambdas

Chapter 6   Working with Collections and Generics

Chapter 7   Querying Objects with LINQ

Chapter 8   Making Your Code Asynchronous

Chapter 9   Moving Forward and More Things to Know

Detailed Table of Contents

Chapter 1 Introducing C# and .NET

Chapter 1  Introducing C# and .NET

Welcome to C# Succinctly. True to the Succinctly series concept, this book is very focused on a single topic: the C# programming language. I might briefly mention some technologies that you can write with C# or explain how a feature fits into those technologies, but the whole of this book is about helping you become familiar with C# syntax.

In this chapter, I'll start with some introductory information and then jump straight into a simple C# program.

What can I do with C#?

What can I do with C#?

C# is a general purpose, object-oriented, component-based programming language. As a general purpose language, you have a number of ways to apply C# to accomplish many different tasks. You can build web applications with ASP.NET, desktop applications with Windows Presentation Foundation (WPF), or build mobile applications for Windows Phone. Other applications include code that runs in the cloud via Windows Azure, and iOS, Android, and Windows Phone support with the Xamarin platform. There might be times when you need a different language, like C or C++, to communicate with hardware or real-time systems. However, from a general programming perspective, you can do a lot with C#.

What is .NET?

What is .NET?

.NET is a platform that includes languages, a runtime, and framework libraries, allowing developers to create many types of applications. C# is one of the .NET languages, which also includes Visual Basic, F#, C++, and more.

The runtime is more formally named the Common Language Runtime (CLR). Programming languages that target the CLR compile to an Intermediate Language (IL). The CLR itself is a virtual machine that runs IL and provides many services such as memory management, garbage collection, exception management, security, and more.

The Framework Class Library (FCL) is a set of reusable code that provides both general services and technology-specific platforms. The general services include essential types such as collections, cryptography, networking, and more. In addition to general classes, the FCL includes technology-specific platforms like ASP.NET, WPF, web services, and more. The value the FCL offers is to have common components available for reuse, saving time and money without needing to write that code yourself.

There's a huge ecosystem of open-source and commercial software that relies on and supports .NET. If you visit CodePlex, GitHub, or any other open-source code repository site, you'll see a multitude of projects written in C#. Commercial offerings include tools and services that help you build code, manage systems, and offer applications. Syncfusion is part of this ecosystem, offering reusable components for many of the .NET technologies I have mentioned.

Writing, Running, and Deploying a C# Program

Writing, Running, and Deploying a C# Program

The previous section described plenty of great things you can do with C#, but most of them are so detailed that they require their own book. To stay focused on the C# programming language, the code in this book will be for the console application. A console application runs on the command line, which you'll learn about in this section. You can write your code with any editor, but this book uses Visual Studio.

Note: The code samples in this book can be downloaded at https://bitbucket.org/syncfusiontech/c-succinctly.

Starting a New Program

You'll need an editor or Integrated Development Environment (IDE) to write code. Microsoft offers Visual Studio (VS), which is available via Community Edition as a free download for training and individual purposes (https://www.visualstudio.com/en-us/products/vs-2015-product-editions.aspx). There are other development tools, but you can also use any editor, including Notepad. Notepad++ is another editor that does syntax highlighting, but there are many more available. Essentially, you just need the ability to type a text document. Pick your editor or IDE of choice and it will work for all programs in this book.

Note: You need to use Visual Studio 2015 to compile the samples in this book.

To get started, we need a program to run. In VS, select File > New > Project, then select Installed > Templates > Visual C# in the tree on the left, and finally select the Console Application project type. Name the solution Chapter01, name the project Greetings, set the location to your preference, and click OK. This will create a new solution for you. Delete the Program.cs file and add a Greetings.cs file. In any text editor, just create a file named Greetings.cs. The following is a C# program that prints a greeting to the command line.

using System;

 

class Greetings

{

    static void Main()

    {

        Console.WriteLine("Greetings!");

    }

}

Code Listing 1

The class is a container for code, defining a type, named Greetings. A class has members and this example shows a method member named Main. A method is similar to functions and procedures in other programming languages. For desktop application types, like console or WPF, naming a method Main tells the C# compiler where the program begins executing. Both the Greetings class and Main method have curly braces, referred to as a block, indicating beginning and ending scope.

The void keyword isn't a type; it indicates that a method does not return a value. For Main, you can replace void with int, meaning that the program has a return code. This number can be used by command-line shell tools to evaluate the conditions under which the program ended. It is unique to each program and specified by you. Later, you'll learn more about methods and return values.

The static modifier indicates that there is only ever one instance of a Greetings class that has that Main method—it is the static instance. Main must be static, but other methods can omit static, which makes them instance members. This means that you can have many copies of a class or instance with their own method.

Since a program only needs a single Main method, static makes sense. A program that manages customers might have a Customer class and you would need multiple instances to represent each Customer. You'll see examples of instantiating classes in later chapters of this book.

Inside the Main method is a statement that prints words to the command line. The words, enclosed in double quotes, are a string. That string is passed to the WriteLine method, which writes that string to the command line and causes it to move to the next line. WriteLine is a method that belongs to a class named Console. You see in this example, just like the Greetings class, the Console is a class too. This Console class belongs to the System namespace, which is why the using clause appears at the top of the file, allowing us to use that Console class.

The code begins with a using clause for the System namespace. The FCL is grouped into namespaces to keep code organized and avoid clashes between identically named types. This using clause allows us to use the code in the System namespace, which we're doing with the Console class. Without that, the compiler doesn't know what Console means or how to find it, but now C# knows that we're using the System.Console class.

Namespaces and Code Organization

Namespaces and Code Organization

There are various ways to organize code and the choice should be based on the standards of your team and the nature of the project you're building. One of the common ways to organize code is with the C# namespace feature. Here's a hierarchical description of where namespaces fit into the overall structure of a program:

    Namespace

        Type

            Type Members

Out of this hierarchy, the namespace is optional, as demonstrated in the previous program where the Greetings class was not contained in a namespace. This means Greetings is a member of the global namespace. You should avoid this practice as it opens the possibility for other developers working with your code to write their own Greetings class in the same namespace, which will cause errors because the C# compiler can't figure out which Greetings class to use. While Greetings might seem unique and unlikely, think of common names, such as File, Math, or Window, that would cause problems. The following program uses namespaces appropriately.

using static System.Math;

 

namespace Syncfusion

{

    public class Calc

    {

        public static double Pythagorean(double a, double b)

        {

            double cSquared = Pow(a, 2) + Pow(b, 2);

            return Sqrt(cSquared);

        }

    }

}

Code Listing 2

The Calc class is a member of the Syncfusion namespace. The Pythagorean method is a member of the Calc class. A method is a block of code with a name, parameters, and return value that you can call from other code. This follows the namespace, class, member organization.

System is a namespace in the FCL and Math is a class in the System namespace. The using static clause allows the code to use static members of the Math class without full qualification. Instead of writing Math.Pow(a, 2), which squares the value of a, you can use the shorthand syntax in the Pythagorean method. The Pythagorean method uses Math.Sqrt, which provides square root, similarly. The following sample shows how you can use this code.

using Syncfusion;

using System;

 

using Crypto = System.Security.Cryptography;

 

namespace NamespaceDemo

{

    class Program

    {

        static void Main()

        {

            double hypotenuse = Calc.Pythagorean(2, 3);

            Console.WriteLine("Hypotenuse: " + hypotenuse);

 

            Crypto.AesManaged aes = new Crypto.AesManaged();

 

            Console.ReadKey();

        }

    }

}

Code Listing 3

The Main method calls the Pythagorean method of the Calc class, passing arguments 2 and 3 and receiving a result in hypotenuse. Since Calc is in the Syncfusion namespace, the code adds a using clause for Syncfusion to the top of the file. Had the code not included that using clause, Main would have been required to use the fully qualified name, Syncfusion.Calc.Pythagorean.

Another feature of the previous program is the namespace alias, Crypto. This syntax allows you to use a shorthand syntax when you need to fully qualify a namespace, but want to reduce syntax in your code. If there had been another Cryptography namespace used in the same code, though not in this listing, full qualification would have been necessary. Crypto is the alias for System.Security.Cryptography and Main uses that alias in Crypto.AesManaged to make the code more readable.

Running the Program

The rest of this chapter returns to the previous Greetings program in this chapter.

Now the program is written and you want to continue by compiling the program and running it. You'll want to save this file with the name Greetings.cs. The name isn't necessarily important, but by convention should be meaningful and is often the same name as a class it contains. You're allowed to put multiple classes in the same file, but it's easier to find a class later if it is alone in its own file of the same name. C# files have a .cs extension.

In VS, click the green Start arrow on the toolbar and it will build and run the program. The program runs and stops so quickly that you won't see the command-line output, so you can press Ctrl + F5 to make the command line stay open. This book uses Visual Studio 2015, but Syncfusion has published Visual Studio 2013 Succinctly, which explains many features that are still valid in Visual Studio 2015. In the meantime, I'm going to show you how to use the C# compiler directly—the benefit being that you see what the IDE is doing for you.

Tip: Adding Console.ReadKey(); as the last line in Main makes the command line stop and wait for a key press.

Minimally, you need the .NET Framework installed on your machine, which is free for commercial as well as non-commercial use. If you installed VS, you already have the .NET Framework. Otherwise, download it from http://www.microsoft.com/en-us/download/details.aspx?id=30653 and install it. This link is for .NET Framework 4.5, but any future version should work fine.

Once .NET is installed, open Windows Explorer and do a search for the C# compiler, csc.exe. Since I'm using Visual Studio 2015 for the examples in this book, the C# 6 compiler on my machine is located at C:\Program Files (x86)\MSBuild\14.0\Bin, but yours may differ.

Next, make sure the C# compiler is in your path. Open your System Properties window. As of this writing, I'm on Windows 8.1 and found it via selecting Control Panel > System and Security > System, and then clicking Advanced System Settings. Select the Advanced tab and click the Environment Variables button. In the System variables list, select Path, and click Edit. You should see several paths separated by semicolons. At the end of that path, add your C# compiler's path that you found with the Windows Explorer search and make sure it's separated from the previous paths with a semicolon. Close out of all these windows when you're done setting the path.

Now that you have the .NET Framework installed and have the path to the C# compiler set, you can build the program that you typed in the previous example. First, open a command prompt window. On my system, I can do this by pressing the Windows logo key + R, typing cmd.exe in the Run dialog, and then clicking OK. If you've never used a command line, it's a good idea to open your favorite search engine and look for a tutorial. Alternatively, it might be good to learn PowerShell; Syncfusion has a book on it titled PowerShell Succinctly. In the meantime, navigate to the directory where you saved Greetings.cs. You can type cd\your\path\there and press Enter to get there. You can verify you're in the right location by typing dir to see what files reside in the current directory.

To compile the program, type csc Greetings.cs. If you see compiler errors, go back to Code Listing 1 and make sure you've typed the code exactly as it is there and then recompile.

Tip: Use a space separated list to compile multiple files; e.g., csc.exe file1.cs file2.cs. For C# compiler help, type csc.exe /help.

Now type dir and you'll see a new file named Greetings.exe. This is an executable assembly. In .NET, an assembly is a unit of identity, execution, and deployment, which is why it's not just called a file. For the purposes of this book, you won't be involved with all the nuances of assemblies, but it's an encompassing term that includes both executable (.exe) and library (.dll) files.

Now type Greetings.exe and press Enter. The program will print Greetings! on the command line. Then you'll see a new command-line prompt, meaning that the program ended. This came from the Console.WriteLine statement in the Main method. When the Main method finishes executing, the program finishes too.

Deploying the Program

.NET uses XCopy deployment, which means that you only need to copy the assembly to anywhere you want it to go. The one caveat is that whatever machine you run the program on must also have the .NET CLR installed. Installing VS or the .NET Framework automatically installs the CLR. Also, you can only install the .NET Framework Runtime, which doesn't include development tools, to a machine where you only want to run a C# program but not perform any development tasks. In practical terms, most Windows systems already have .NET installed from the original installation and it is kept up-to-date via Windows Update.

Whenever you run the program, Windows looks at the executable, determines that it's a .NET assembly, loads the CLR, and then gives that assembly to the CLR to run. From the users' perspective, the CLR behavior is behind the scenes; the program appears like any other program when they run the executable.

Summary

Summary

This chapter included a couple broader takeaways regarding how C# fits into the .NET Framework ecosystem and how to create a C# program. Remember that C# is a programming language, but it builds programs that use the FCL to run applications managed by the CLR. What this gives you is the ability to compile programs into assemblies that can be deployed and run on any machine that supports the CLR. The program entry point

Impressum

Verlag: BookRix GmbH & Co. KG

Tag der Veröffentlichung: 01.02.2016
ISBN: 978-3-7396-3504-0

Alle Rechte vorbehalten

Nächste Seite
Seite 1 /