Hour 21. C# and the .NET Framework

One of the most important technologies for developing applications and web services is Microsoft’s .NET framework. Now close to 15 years old, .NET continues to evolve, incorporating new standards that allow developers to create full-featured windows applications. .NET is not new technology, but a way to approach new technology. .NET consists of today’s software and hardware tools as well as tomorrow’s more advanced ones. Microsoft’s .NET development environment, Visual Studio, was introduced in the last hour. With it, you can create programs in a variety of languages, including C#, which will be touched upon in this hour.

The concepts behind the .NET Framework are complicated, so don’t be discouraged if the material in this hour doesn’t make immediate sense. But if you wish to take your rudimentary knowledge gained throughout this book to the next level, .NET is an excellent place to go.

The highlights of this hour include

Image Understanding why developers use the .NET Framework

Image Breaking down the elements of the .NET Framework

Image Defining the C# language

Image Writing your first C# program

Image Creating a C# windows application

Understanding the Purpose of .NET

Throughout the earlier hours, you have seen ways to tackle online programming, including JavaScript, Java, HTML, CSS, and PHP. Microsoft’s .NET is a centralized approach to online and networked technology. For the past decade and a half, Microsoft has developed an approach to online programming and encapsulated that approach into an umbrella of multiple technologies called .NET.

Microsoft’s goal is for .NET to address the needs of users who will live in an always on and connected online world. Developers that use .NET are looking to build next-generation, platform-independent products. With the significant changes to the computing space, being platform-independent has become more crucial than ever—since the introduction of .NET, programmers now need to worry about multiple operating systems, a host of mobile environments and devices, and cloud-based services as well. Code written for the .NET Framework is called managed code (which can easily be shared thanks to the Common Intermediate Language (CIL), covered later in this hour). Code written in languages such as C and C++, is compiled into machine code tied specifically to the computer on which it was compiled, and is known as unmanaged code.


Tip

If you are looking to create managed code in C or C++, that option is available when you use Visual C++ in Visual Studio.


The .NET Framework creates simplified software deployment agnostic of platform thanks to the common language runtime (CLR), the framework class library (FCL), parallel computer platform, and the dynamic language runtime (DLR).

The Common Language Runtime

The heart of the .NET Framework is the common language runtime (CLR). The CLR allows multiple languages to share objects and methods and cuts down on memory leak problems thanks to garbage collection.

CLR might sound difficult to understand at first, but it’s simple. A .NET-compatible language such as Visual Basic, Visual C++, or C# will not compile to a specific machine, as is historically the case for computer languages, but rather will compile to a common machine language. Every .NET-based operating system will emulate this common language. So, in theory, a single program written in C++ could run, unaltered, on a PC, a Windows phone, and as a web service.


Tip

If a programmer learns a language that compiles to a CLR, that program runs on any device that supports .NET. A different compiler and a different language no longer have to be developed for each kind of computing device.


The key components of the CLR include

Image The Common Type System—As you have probably noticed during your survey of languages throughout this book, while most programming concepts and syntaxes are fairly universal, there are subtle differences (like dialects within a shared language) that can cause problems if you attempt to integrate multiple languages. The common type system (CTS) allows all languages within the .NET framework to share type definitions, preventing problems that could arise if an incompatible piece of data is assigned to a type. The CTS also sets rules that allow types written in different programming languages to interact with each other. These rules are enforced by the CLR.

Image The Common Intermediate Language—As discussed in earlier lessons, other languages covered in this book like C and C++ compile their code into machine language that is unreadable and also specific to the platform and machine on which it was compiled. Not a great start to creating platform-independent applications and services. The CIL creates a middle step of low-level instructions called an assembly, which when combined with the metadata that describes the types, members, and references in the code, allows your code to run on a variety of platforms—it just needs to be put through a just-in-time compiler (JIT) to run on your specific hardware platform.

Image Garbage Collection—Although it was not covered in great detail in the hour on C and C++, effective programming practice is to declare only the memory you need for your programs, and then release the memory back to the system when you are done with it. Inefficient memory use can slow both your program and your entire system. The .NET Framework introduced garbage collection, an automatic memory management feature which makes you not have to worry about these issues. This isn’t to say you are completely free from any involvement in memory management—in fact, if you pursue development in .NET, you should learn how garbage collection works.


Tip

If you want to know more about .NET, its strengths, and the C# language, I’d recommend picking up Sams Teach Yourself C# 5.0 in 24 Hours. It covers in excellent detail the subjects touched upon in this hour.


The Framework Class Library

There is little sense in reinventing the wheel. While writing your own code from scratch is always a bit gratifying, taking existing code and using it as a foundation helps you to build more robust code. The .NET Framework’s FCL includes a number of reusable classes, interfaces, and types. There are thousands of classes in the FCL and you can find detailed information on some of the most commonly used classes at msdn.microsoft.com/en-us/library/gg145045.aspx.

Some of the lowest-level FCL offerings are the base class libraries (BCL), which you use for string manipulation, working with streams, file input and output, and more.

With these thousands of classes, .NET uses namespaces to avoid ambiguity between type names and to clarify hierarchal groupings. The website listed earlier in this section has a robust table that lists several dozen of the most common namespaces, many of which fall in the system grouping. Specific namespaces use the dot operator to clarify each level of the hierarchy, that is, system.collections. If you click on the system.collections element in the table on Microsoft’s website, you will get a listing of the base namespaces and four others within the collections hierarchy. Clicking on any of them gives you their classes, interfaces, structures, and more. Effective use of the elements in the FCL will save you considerable development time and add impressive power to your programming abilities.

Parallel Computing Platform

Developers looking to speed up the execution of their programs have turned to multithreaded and asynchronous applications. While these methodologies can greatly increase the speed of programs, they also can lead to problematic, error-filled programs. The .NET Framework simplifies creating these apps with the parallel computing platform, which allows developers to write code that can take advantage of multiple processors. This is a topic far beyond your knowledge and experience at this point, but it is a key feature of the .NET Framework that you should know about in case you want to head in that direction.

Dynamic Language Runtime

JavaScript, covered in the first half of the book, is considered a dynamic language, as are many other scripting languages you may have heard of, like Python and Ruby. These languages have subtle differences from languages like C and Visual Basic. One example you may remember is that you don’t have to specify a type for your variables. You can declare a variable culture and have it first hold a floating-point number like 14.5 and then assign it a string like “breakfast cereal”. Other languages don’t allow this in order to make sure variables aren’t used improperly. This is known as type safety. Obviously, you don’t want any interactivity problems to arise when a statically typed language like Visual Basic or C# interact with dynamic languages, and the DLR covers these potential problems, allowing you as the developer to choose whatever language you feel suits your development purposes best.

The C# Language

C# was developed specifically for .NET, to act as a scripting language for applications and web pages. C#, like Java, is based on the C and C++ programming languages. C# is an object-oriented language (also like Java and C++) and supports classes, inheritance, polymorphism, encapsulation, and abstraction.

If you installed Visual Studio in order to follow along with the Visual Basic examples in the previous lesson, you already have your C# Integrated Development Environment (IDE) ready to go. To build a C# (also called Visual C#) program, you would select New Project, just like you did in the last hour. This time though, you would click on one of the Visual C# choices on the list on the left side (they are a subhead under Other Languages), so if nothing is below Other Languages, click the arrow to its left and choices for Visual C#, Visual C++, and Visual F# should appear, as in Figure 21.1.

Image

FIGURE 21.1 Much like with Visual Basic, the project choices for Visual C++ are quite diverse.


Note

As mentioned in the last hour (but worth repeating), your dialog boxes and choices may look a bit different than what you see here depending on what version of Visual Studio you have installed.


This should be a fairly easy program to follow by this time in the book. Generally, first programs are “Hello World” examples, but giving you a little credit, working on a program with not just output but input and variables can be a bit more instructive.

The most confusing part of the program is probably the first few lines. As mentioned earlier, these using lines instruct the compiler to let you use the classes and objects associated with the namespaces that follow. Frankly, you don’t really need any of them except System and if you comment out the next four (adding the double slashes // at the beginning of the lines) and rebuild the project, it will work just fine. Remember that these were generated automatically when you selected your project.

The previous paragraph should point out a similarity that C# has with C, C++, and JavaScript. You use // to create comments, telling the compiler to ignore anything that comes to the right of the slashes. As emphasized throughout the book, it is good programming practice to use comments frequently. Some would argue this listing has too many comments, and that’s a fair point—you don’t want to overdo things and state the obvious. But undercommenting is far worse, particularly if you have to return to a piece of code you wrote months, or even years, earlier and have to waste time piecing together what the code is accomplishing.

Input and output are the staples to any programming language and for C#, Console.Readline and Console.Writeline are great starting points. A secondary input function, Console.Readkey, is also being used, although its value is not being assigned to a variable. This is just a way to keep the output window from disappearing once it calculates the area and presents the result onscreen. Without that line waiting for you to input any single character (hence, press any key), the program will output the value of the area, and then end the program, making the window go away before you have time to read it properly. To see what I mean, comment out those last two lines and rebuild and rerun the program.

Taking Advantage of the Visual Nature of Visual C#

That example is easy to follow and demonstrates the use of C# code in an old-school way, but one of the advantages of Visual Studio is creating Windows applications. So let’s see how easy it is to make a windows form that does this same calculation. So save your previous project and select a new C# project, this time a Windows Form Application. Once it sets things up for you, you will get the work area you see in Figure 21.4.

Image

FIGURE 21.4 Visual C# Windows-based applications will be easy to understand if you’ve read through the introduction to Visual Basic in the previous lesson.

This should look familiar to you, as it is virtually identical to the Windows Form Application you saw for Visual Basic. The controls in the toolbox will also be similar—the underlying code you write for the application will be where Visual Basic and Visual C# truly diverge.

Open your toolbox and place two labels and two text boxes on your form. It’s easy to align them, as once you start dragging a text box under the other, a blue guideline will appear to ensure you place one under the other. These guidelines appear both vertically and horizontally, as shown in Figure 21.5.

Image

FIGURE 21.5 Guidelines will help you with alignment.

Highlight the two labels and rename their text property in the properties box to Radius (the top label) and Area (the bottom label). While you’re at it, click the form and give it the name “Radius to Area Calculator”.

Now you need to reopen the toolbox and add a button to your form. Align it to the two text boxes and then change the button’s text property to calculate. Your form should look like the one pictured in Figure 21.6.

Image

FIGURE 21.6 Your area calculator should be coming along nicely.

Next you need to highlight the text box to the right of Radius and name the textbox for when we do our calculation. For this example, it is named enteredRadius.


Tip

When you have a variable name made up of multiple words, capitalizing the first letter of the second word (and all following words) is common practice and is known as camel notation—because it is like you are creating little camel humps within your word.


You then need to do the same for the area text box. It is named enteredArea. (I understand that the area is being calculated, not entered, but consistency of names can be a good thing.)

Now all that is left is to put some code behind the calculate button. If you double-click on the button, you will bring up the code section. Between the two braces following private void calculate_Click, enter the following code:

double radius, area;

radius = double.Parse(enteredRadius.Text);
area = 3.14 * radius * radius;

enteredArea.Text = area.ToString();

It should look like Figure 21.7.

Image

FIGURE 21.7 Just like with Visual Basic, once you set your controls, you then enter code to get the controls to do what you want.

The first three lines of code are similar to your console version. You declare two variables named radius and area. The information entered by the user into the enteredRadius text box is considered a string, so you need to parse it into a number before you do math with it. Then you use the radius of the circle to calculate the area. But before you can display the calculated area in its text box, you must turn the number back into a string, which is easy enough with the ToString method. Now your control is ready to go. Build it and run it. If you enter the same radius as you did in the console example, you should get the same area, as displayed in Figure 21.8.

Image

FIGURE 21.8 Now you can calculate circle areas whenever you want!

Not the sexiest example, but it is nice to see the text-based and windows-based versions of the same program. This obviously is just scratching the surface of what you can do with C#—like the other languages you’ve learned, you can do loops, conditional statements, object-oriented programming (OOP), and so much more. There’s almost no limits to the power of C#, particularly when you learn to use it in conjunction with the other tools of Visual Studio.

Summary

The 30,000 foot view of Microsoft’s .NET Framework terrain should give you some idea of where you can take your programming knowledge next. The world of application and web service development continues to splinter into different devices and platforms, so the ability to create solutions that work regardless of platform is crucial. In addition, it makes little to no sense to learn multiple development environments as well as languages, so the commonality of tools and editor in Visual Studio can save you time and effort and allow you to focus on solving the business issues at hand.

This completes the survey of other languages and environments. The next part (Part V) begins a three-hour look at the business of programming, giving you some understanding of where the skills you are acquiring can be used in the corporate world.

Q&A

Q. Is .NET the only way to develop platform-independent applications and services?

A. Not at all. Some people initially thought that .NET and C# were going to replace Java, but as you’ve seen in Part III of this book, Java is still going strong. In addition, new cloud-based programming methods like Infrastructure as a Service (IaaS) and Software as a Service (SaaS) can also deliver applications largely platform-independent. Microsoft’s size and marketing muscle will always keep .NET in the game, but there are other options as well.

Q. Is it best to use a particular programming language with .NET?

A. While Visual Studio offers a suite of programming languages and tools, there are certain advantages to using C#. It was developed specifically for the .NET Framework. Its similarities to C, C++, and Java make it easy to pick up for anyone that has any experience with those other languages, and it incorporates both the strength of an object-oriented language and a component-oriented language. However, if you prefer VB or C/C++, you have those options in Visual Studio as well.

Workshop

The quiz questions are provided for your further understanding.

Quiz

1. What is the IDE developers use to create .NET applications?

2. What are the components of the .NET framework?

3. What does CIL stand for?

4. True or false: The power of the FCL is that it has just a few dozen classes, so they are easy to memorize.

5. What is garbage collection in .NET?

6. What language is an example of a dynamic language?

7. C# is similar to what other languages?

8. Why is it not wise to immediately do math with numbers entered by users in C#?

9. How do you add comments to your code in C#?

10. What is the purpose for the CLR?

Answers

1. Visual Studio.

2. The components of the .NET Framework are the CLR, the FCL, the parallel computing platform, and the DLR.

3. CIL stands for the common intermediate language.

4. False. The power of the FCL is that it has hundreds of classes that cover a number of programming needs.

5. Garbage collection is automatic memory management.

6. JavaScript is an example of a dynamic language.

7. C# is similar to C and C++ (as well as Java).

8. You should parse entered values into numbers before doing math or C# may assume the value is a string, and you won’t get the value you expect.

9. You can either create single-line comments with the double slash (//) or multi-line comments enclosed in (/* and */) just as you do in JavaScript, C, and C++.

10. The CLR allows all computers with a CLR compiler to be .NET compatible.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.137.12