Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Beginning C# 7 Hands-On ??? Advanced Language Features

You're reading from   Beginning C# 7 Hands-On ??? Advanced Language Features Learn the advanced-level features of C# 7 using Visual Studio 2017

Arrow left icon
Product type Paperback
Published in Oct 2017
Publisher Packt
ISBN-13 9781788294263
Length 310 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Tom Owsiak Tom Owsiak
Author Profile Icon Tom Owsiak
Tom Owsiak
Arrow right icon
View More author details
Toc

Table of Contents (30) Chapters Close

Preface 1. Creating a Simple Generics Class 2. Creating a Generic Method FREE CHAPTER 3. Implementing a Generic Interface to Accomplish Sorting 4. Making Delegates More Flexible with Generics 5. Creating and Using Generic Dictionaries 6. Connection Between Delegates and Lambda Expressions 7. Expression-Bodied Lambdas and Expression-Bodied Members 8. Anonymous Methods and Objects That Run Their Own Delegates 9. C# with LINQ and Built-In Types 10. C# with LINQ and Custom Data Types 11. Using Query Syntax to Construct Queries 12. Queries That Perform Aggregation Functions 13. Using LINQ to Summarize Tuples 14. Summarizing Results with Grouping 15. Joining Datasets with Inner Joins 16. Downloading, Installing, and Running SQL Server 2017 17. Writing Code to Manually Connect to a Table and Retrieve Records 18. Inserting Records into Tables Using Stored Procedures 19. Using the Nullable Feature to Make Apps More Stable 20. Connecting a Chart Control to SQL Server 21. Using LINQ to Operate on Tables from SQL Server 22. Creating a Page That Saves Text to Disk 23. Creating a Page That Uses the File Upload Control 24. Serializing and Deserializing Objects 25. Having a Little Fun with Images with Pixel Manipulations 26. Saving an Image to SQL Server 27. Creating and Using an XML File 28. Creating XML Files with C# 29. Querying XML Documents with LINQ

Initializing a collection of integers to their array and displaying the results

Now, double-click on the Display Values button and go into Default.aspx.cs. Delete the Page_Load block. Next, between the set of curly braces beneath the line beginning with protected void Button1_Click..., enter the following:

GenericsClass<int> ints = new GenericsClass<int>(new int[] { 1, 2, 3, 4, 5 });

You can see in this line that we are basically initializing a collection of integers to their array.

Now, you can display this. So, for example, you can enter the following below this line:

sampLabel.Text += ints.DisplayValues();

Notice that the GenericsClass which we have constructed is operating in integers, but it can operate equally well on any other data type.

Changing the data types in our generics class

Now, to make the code efficiency more obvious, take both of the preceding lines, copy them (Ctrl + C) and paste them (Ctrl + V) beneath these and just change it to double, as follows:

GenericsClass<double> dubs = new GenericsClass<double>(new double[] {1, 2, 3, 4, 5});
sampLabel.Text = ints.DisplayValues();

We'll call this one dubs and change the name here to double: it's the same code, the same class, and the same generic class that you can operate on the doubles. Again, to emphasize this one more time, and to see that flexibility and code reuse is really the purpose here; that is, the ability to reuse code, we'll now take both of these new lines, copy and paste them below once more, and just change double to decimal, as follows:

GenericsClass<decimal> decs = new GenericsClass<decimal>(new decimal[] { 1, 2, 3, 4, 5 });
sampLabel.Text = ints.DisplayValues();

Let's call this one decs. Now, of course, if you want to make things a little more interesting, you can throw in some decimals:

GenericsClass<double> dubs = new GenericsClass<double>(new double[] { 1.0, -2.3, 3, 4, 5 });
sampLabel.Text = ints.DisplayValues();
GenericsClass<decimal> decs = new GenericsClass<decimal>(new decimal[] { 1, 2.0M, 3, 4, 5.79M });
sampLabel.Text = ints.DisplayValues();
With decimals, just make sure that you put the M suffix in there, because you need the M suffix at the end to indicate that it's a decimal.

Running the program

Now, let's take a look. When you run this code and click on the Display Values button, your screen will look like the one shown in Figure 1.1.4:

Figure 1.1.4: The initial run of our code

Accumulating the input

Now, we will accumulate the input. So, in the following sampLabel.Text lines, we change the = sign to +=, as shown here:

GenericsClass<double> dubs = new GenericsClass<double>(new double[] { 1.0, -2.3, 3, 4, 5 });
sampLabel.Text += ints.DisplayValues();
GenericsClass<decimal> decs = new GenericsClass<decimal>(new decimal[] { 1, 2.0M, 3, 4, 5.79M });
sampLabel.Text += ints.DisplayValues();

Let's run it one more time. Click on the Display Values button and your screen will now look like the one shown in Figure 1.1.5:

Figure 1.1.5: The input is now being accumulated, and the values are showing as expected

The program is now working as expected.

So, the big idea of generics at this point is that you can define a generic class. This class can operate equally well on many different data types. For example, you can make a generic class that operates on integers as well as on doubles and decimals.

This step isn't strictly required, but here's a little bit of additional insight. If you want to, you can set a breakpoint as follows. Select the line with the open curly brace under the line beginning with protected void Button1_Click.... Now, go to Debug | Step Into (F11) and click on Display Values.

Now, we will go through it. So, to first step into it, hover your mouse over the T object in the following line in Generics Class.cs:

public GenericsClass(T[] input)

Here, T is essentially like a parameter, so it does have a certain value, which is expressed in the vals = input; line. The first time, T is used for integers. This is how you can step through this code. At the bottom of the screen, the values inside the array are displayed, as shown in Figure 1.1.6:

Figure 1.1.6: The values inside the array

The t variable, as you can see in Figure 1.1.7, is an integer, and this is how it operates:


Figure 1.1.7: The t is an integer

Notice also in the screenshot that it's a generics class with an <int> datatype.

The T object in the foreach(T t in vals) line right now represents an integer, and so on for the other data types. So, flexibility of code and reuse of code means that you will write less code. If not for generics, you would have to create individual classes to handle each different data type.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image