C# 7.0 All-in-One For Dummies book cover

C# 7.0 All-in-One For Dummies

By: John Paul Mueller and Bill Sempf Published: 12-26-2017

Sharpen your knowledge of C#

C# know-how is a must if you want to be a professional Microsoft developer. It's also good to know a little C# if you're building tools for the web, mobile apps, or other development tasks. C# 7.0 All-in-One For Dummies offers a deep dive into C# for coders still learning the nuances of the valuable programming language. Pop it open to get an intro into coding with C#, how to design secure apps and databases, and even pointers on building web and mobile apps with C#.

C# remains one of the most in-demand programming language skills. The language regularly ranks in the top five among "most in-demand" languages, typically along with Java/JavaScript, C++, and Python. A December 2016 ZDNet article noted 'If your employer is a Microsoft developer, you better know C#." Lucky for you, this approachable, all-in-one guide is here to help you do just that—without ever breaking a sweat!

Includes coverage of the latest changes to C#

  • Shows you exactly what the language can (and can't) do
  • Presents familiar tasks that you can accomplish with C#
  • Provides insight into developing applications that provide protection against hackers

If you have a basic understanding of coding and need to learn C#—or need a reference on the language in order to launch or further your career—look no further.

Articles From C# 7.0 All-in-One For Dummies

page 1
page 2
page 3
28 results
28 results
C# 7.0 All-In-One For Dummies Cheat Sheet

Cheat Sheet / Updated 03-10-2022

C# provides you with access to a phenomenal array of programming options. Use this cheat sheet to help you get the job done faster and easier when using C# as your development solution of choice.

View Cheat Sheet
Making Sure Your ASP.NET Site Is Accessible

Article / Updated 02-01-2018

Everyone has special needs, and those needs change as time progresses. Microsoft is aware of this. Someone with perfect eyesight in the morning might suffer from tired eyes in the afternoon. Many web users have some sort of special need all the time. Whether the need is intermittent or constant, making your site accessible means making it easy for everyone to use. Microsoft has made a significant investment in accessible web browsing, and you’ll be pleased to find that most of the controls make good decisions about accessibility right out of the box. Understanding how to use them for this purpose takes a little effort, however. If you’re building websites for large enterprises or the government, Section 508 (an amendment to the Rehabilitation Act) makes this very important. Check out Accessibility for Everybody, by John Paul Mueller (Apress) for more information. Most ASP.NET controls, where applicable, fit a certain feature list for accessibility. The goal is to make coding for accessibility easy for the programmer and functional for the user. Any element that isn’t made of text should have an alternate text option. For instance, all image tags support an AlternateText property, which populates the HTML alt tag. web-to-text readers will “speak” the contents of this tag in place of the image. If you add an image to a web page, Visual Studio even prompts you for the alternate text. Controls don’t require the use of style sheets or color dependency. If you want, you can easily strip all style information from a page for simplicity of use by a reader or a low-sight version of the application. All input controls in Getting Input from the User support a TabIndex property, which allows users to tab from control to control. For those not using a mouse, this is optimum. Setting which part of the form has the cursor by default (called default focus) is easy in ASP.NET with the DefaultFocus property. Changing it is easy with the SetFocus method. You can give buttons keyboard equivalents by using the AccessKey property. Labels and input controls can be associated, which many web readers depend on. A feature in Visual Studio called Check Page for Accessibility checks web Content Accessibility Guidelines (WCAG) and Section 508 errors. If you use this feature, warnings will actually be posted to your build process.

View Article
Employing Dynamic C# Programming Techniques

Article / Updated 02-01-2018

When you define a new variable, you can use the dynamic keyword, and C# will let you make assumptions about the members of the variable. For example, if you want to declare a new Course object, you do it like this: Course newCourse = new Course(); newCourse.Schedule(); This is, of course, assuming that you have a Course class defined somewhere else in your program, like this: class Course { public void Schedule() { //Something fancy here } } But what if you don't know what class the new object will be? How do you handle that? You could declare it as an Object, because everything derives from Object, right? Here's the code: Object newCourse = new Object(); Not so fast, if you make your next line this: newCourse.Schedule(); Note the squiggly line appears almost immediately, and you get the famous “object does not contain a definition for Schedule…” error in the design time Error List. However, you can do this: dynamic newCourse = SomeFunction(); newCourse.Schedule(); All this code needs to have is the stub of a function that returns some value, and you are good to go. What if SomeFunction() returns a string? Well, you get a runtime error. But it will still compile! About now you may be thinking: “This is a good thing? How!?!” For the time being, you can blame COM. You see, COM was mostly constructed using C++, which has a variant type. In C++, you could declare a variable to be dynamic, like this: VARIANT newCourse; It worked just like the dynamic type, except C# wasn't invented yet. Anyway, because a lot of the objects in COM used VARIANT out parameters, it was really tough to handle Interop using .NET. Because Microsoft Office is mostly made of COM objects, and because it isn't going to change any time soon, and because Microsoft all C# programmers to be Office developers one day, bam, you have the dynamic type. Say, for instance, that your newCourse is a variant out parameter from a method in a COM class. To get the value, you have to declare it an Object, like this: CourseMarshaller cm = new CourseMarshaller(); //a COM object int courseId = 4; Object newCourse; cm.MakeCourse(courseId, newCourse); //and now we are back to square one newCourse.Schedule(); //This causes a 'member not found exception' Line 6 will not compile, even if the Schedule method exists, because you can't assume that newCourse will always come back as a Course object, because it is declared a variant. You’re stuck. With a dynamic type, though, you’re golden once again, with this code: CourseMarshaller cm = new CourseMarshaller(); //a COM object int courseId = 4; dynamic newCourse; cm.MakeCourse(courseId, newCourse); newCourse.Schedule(); //This now compiles What happens if newCourse comes back as something that doesn't have a Schedule method? You get a runtime error. But there are try/catch blocks for runtime errors. Nothing will help it compile without the dynamic keyword. Readers who are long-time Visual Basic programmers, or even newer VB.NET programmers, realize that you can handle this dynamically — and have always been able to — in Visual Basic. Some developers recommend that programmers who work with legacy systems use Visual Basic for their new code, and this is exactly why. In the interest of language parity, now C# can do it, too. In general, this is good, because many organizations are writing legacy code in VB and new code in C# — and it can get pretty messy in the trenches. This change makes the code base slimmer.

View Article
Using Structures as Records in C#

Article / Updated 01-31-2018

The main reason to work with structures in most code is to create records that contain custom data. You use these custom data records to hold complex information and pass it around as needed within your application. It’s easier and faster to pass a single record than it is to pass a collection of data values, especially when your application performs the task regularly. Keep reading to find out how to use structures as a kind of data record. Managing a single record Passing structures to methods is cleaner and easier than passing a collection of individual data values. Of course, the values in the structure must be related in order for this strategy to work well. However, consider the following method: static void DisplayMessage(Message msg) { Console.WriteLine( "In response to Msg {0}, you can get {1} of {2} for {3}.", msg.MsgID, msg.Qty, msg.ProductID, msg.Price); } In this case, the DisplayMessage() method receives a single input of type Message instead of the four variables that the method would normally require. Using the Message structure produces these positive results in the code: The receiving method can assume that all the required data values are present. The receiving method can assume that all the variables are initialized. The caller is less likely to create erroneous code. Other developers can read the code with greater ease. Code changes are easier to make. Adding structures to arrays Applications rarely use a single data record for every purpose. In most cases, applications also include database-like collections of records. For example, an application is unlikely to receive just one Message. Instead, the application will likely receive a group of Message records, each of which it must process. You can add structures to any collection. However, most collections work with objects, so adding a structure to them would incur a performance penalty because C# must box and unbox each structure individually. As the size of the collection increases, the penalty becomes quite noticeable. Consequently, it’s always a better idea to restrict collections of data records that rely on structures to arrays in your application when speed is the most important concern. Working with an array of structures is much like working with an array of anything else. You could use code like this to create an array of Message structures: // Display all the messages on screen. Message[] Msgs = { myMsg, myMsg2 }; DisplayMessages(Msgs); In this case, Msgs contains two records, myMsg and myMsg2. The code then processes the messages by passing the array to DisplayMessages(), which is shown here: static void DisplayMessages(Message[] msgs) { foreach (Message item in msgs) { Console.WriteLine( "In response to Msg {0}, you can get {1} of {2} for {3}.", item.MsgID, item.Qty, item.ProductID, item.Price); } } The DisplayMessages() method uses a foreach loop to separate the individual Message records. It then processes them using the same approach as DisplayMessage(). Overriding methods Structures provide a great deal of flexibility that many developers assign exclusively to classes. For example, you can override methods, often in ways that make the structure output infinitely better. A good example is the ToString() method, which outputs a somewhat unhelpful (or something similar): Structures.Program+Messages The output isn’t useful because it doesn’t tell you anything. To garner anything useful, you must override the ToString() method by using code like this: public override string ToString() { // Create a useful output string. return "Message ID:\t" + MsgID + "\r\nProduct ID:\t" + ProductID + "\r\nQuantity:\t" + Qty + "\r\nTotal Price:\t" + Price; } Now when you call ToString(), you obtain useful information. In this case, you see the following output when calling myMsg.ToString(): Message ID: 1 Product ID: 22 Quantity: 5 Total Price: 29.95

View Article
Dividing a Single C# Program into Multiple Assemblies

Article / Updated 01-31-2018

In Visual Studio, and in C#, Visual Basic .NET, and the other .NET languages, one project equals one compiled module — otherwise known as an assembly in .NET. The words module and assembly have somewhat different technical meanings, but only to advanced programmers. Executable or library? Executable (.EXE): A program in its own right that contains a Main() method. You can double-click a .EXE file in Windows Explorer, for example, and cause it to run. Executable assemblies often use supporting code from libraries in other assemblies. Class library (.DLLstrong>): A compiled library of functionality that can be used by other programs. Every program needs System classes. Libraries are housed in DLL assemblies. Libraries aren’t executable — you can’t make them run directly. Instead, you must call their code from an executable or another library. The Common Language Runtime (CLR), which runs C# programs, loads library assemblies into memory as needed. The important concept to know is that you can easily write your own class libraries. Assemblies Assemblies, which are the compiled versions of individual projects, contain the project’s code in a special format, along with a bunch of metadata, or detailed information about the classes in the assembly. This section introduces assemblies because they round out your understanding of the C# build process — and they come into play in the discussion of namespaces and access keywords such as protected and internal. Assemblies also play a big part in understanding class libraries. The C# compiler converts the project’s C# code to Common Intermediate Language (usually called IL) that’s stored in the appropriate type of assembly file. IL resembles assembly language (one step beyond the 1s and 0s used in machine language) that hardcore programmers have used for decades to get down “close to the metal” because their higher-level languages couldn’t do what they needed or the compilers couldn’t produce the most efficient code possible. One major consequence of compiling from .NET to IL, regardless of language, is that a program can use assemblies written in different languages. For example, a C# program can call methods in an assembly originally written in Visual Basic or C++ or the C# program can subclass a VB class. Executables You can run executable assemblies in a variety of ways: Run them in Visual Studio: Choose Debug→  Start Debugging (F5) or Debug→  Start without Debugging (Ctrl+F5). Double-click the assembly file (.EXE) in Windows Explorer. Right-click the file in Windows Explorer and choose Run or Open from the pop-up menu. Type the assembly’s name (and path) into a console window. If the program takes arguments, such as filenames, from the command line, drag the files to the executable file in Windows Explorer. A solution in Visual Studio can contain multiple projects — some .DLL and some .EXE. If a solution contains more than one .EXE project, you must tell Visual Studio which project is the start-up project; the one runs from the Debug menu. To specify a start-up project, right-click that project in Solution Explorer and choose Set As Startup Project. The start-up project’s name appears in boldface in Solution Explorer. Think of a solution containing two .EXE assemblies as two separate programs that happen to use the same library assemblies. For example, you might have in a solution a console executable and a Windows Forms executable plus some libraries. If you make the console app the start-up project and compile the code, you produce a console app. If you make the Windows Forms app the start-up — well, you get the idea. Class libraries A class library contains one or more classes, usually ones that work together in some way. Often, the classes in a library are in their own namespaces. You may build a library of math routines, a library of string-handling routines, and a library of input/output routines, for example. Sometimes, you even build a whole solution that is nothing but a class library, rather than a program that can be executed on its own. (Typically, while developing this type of library, you also build an accompanying .EXE project to test your library during development. But when you release the library for programmers to use, you release just the .DLL (not the .EXE) — and documentation for it, which you can generate by writing XML comments in the code.)

View Article
Using Anonymous Methods in C#

Article / Updated 01-31-2018

After you have the gist of using delegates, take a quick look at Microsoft’s first cut at simplifying delegates in C# 2.0 a couple of years ago. To cut out some of the delegate rigamarole, you can use an anonymous method. Anonymous methods are just written in more traditional notation. Although the syntax and a few details are different, the effect is essentially the same whether you use a raw delegate, an anonymous method, or a lambda expression. An anonymous method creates the delegate instance and the method it “points” to at the same time — right in place, on the fly, tout de suite. Here are the guts of the DoSomethingLengthy() method again, this time rewritten to use an anonymous method (boldfaced): private void DoSomethingLengthy() // No arguments needed this time. { ... for (int i = 0; i < duration; i++) { if ((i % updateInterval) == 0) { // Create delegate instance. UpdateProgressCallback anon = delegate() { progressBar1.PerformStep(); // Method ‘pointed’ to }; if(anon != null) anon(); // Invoke the delegate. } } } The code looks like standard delegate instantiations, except that after the = sign, you see the delegate keyword, any parameters to the anonymous method in parentheses (or empty parentheses if none), and the method body. The code that used to be in a separate DoUpdate() method — the method that the delegate “points” to — has moved inside the anonymous method — no more pointing. And this method is utterly nameless. You still need the UpdateProgressCallback delegate type definition, and you’re still invoking a delegate instance, named anon in this example. Needless to say, this description doesn’t cover everything there is to know about anonymous methods, but it’s a start. Look up the term anonymous method in C# Language Help to see more anonymous method examples in the DelegateExamples program on the website. The best advice is to keep your anonymous methods short.

View Article
How to Seal a C# Class

Article / Updated 01-31-2018

You may decide that you don’t want future generations of programmers to be able to extend a particular class. You can lock the class by using the keyword sealed. A sealed class cannot be used as the base class for any other class. Consider this code snippet: using System; public class BankAccount { // Withdrawal -- You can withdraw any amount up to the // balance; return the amount withdrawn virtual public void Withdraw(decimal withdrawal) { Console.WriteLine("invokes BankAccount.Withdraw()"); } } public sealed class SavingsAccount : BankAccount { override public void Withdraw(decimal withdrawal) { Console.WriteLine("invokes SavingsAccount.Withdraw()"); } } public class SpecialSaleAccount : SavingsAccount // Oops! { override public void Withdraw(decimal withdrawal) { Console.WriteLine("invokes SpecialSaleAccount.Withdraw()"); } } This snippet generates the following compiler error: 'SpecialSaleAccount' : cannot inherit from sealed class 'SavingsAccount' You use the sealed keyword to protect your class from the prying methods of a subclass. For example, allowing a programmer to extend a class that implements system security enables someone to create a security back door. Sealing a class prevents another program, possibly somewhere on the Internet, from using a modified version of your class. The remote program can use the class as is, or not, but it can’t inherit bits and pieces of your class while overriding the rest.

View Article
Using Expression-Bodied Members in C#

Article / Updated 01-31-2018

Expression-bodied members first appeared in C# 6.0 as a means to make methods and properties easier to define. In C# 7.0, expression-bodied members also work with constructors, destructors, property accessors, and event accessors. Creating expression-bodied methods The following example shows how you might have created a method before C# 6.0: public int RectArea(Rectangle rect) { return rect.Height * rect.Width; } When working with an expression-bodied member, you can reduce the number of lines of code to just one line, like this: public int RectArea(Rectangle rect) => rect.Height * rect.Width; Even though both versions perform precisely the same task, the second version is much shorter and easier to write. The trade-off is that the second version is also terse and can be harder to understand. Defining expression-bodied properties Expression-bodied properties work similarly to methods: You declare the property using a single line of code, like this: public int RectArea => _rect.Height * _rect.Width; The example assumes that you have a private member named _rect defined and that you want to get the value that matches the rectangle’s area. Defining expression-bodied constructors and destructors In C# 7.0, you can use this same technique when working with a constructor. In earlier versions of C#, you might create a constructor like this one: public EmpData() { _name = "Harvey"; } In this case, the EmpData class constructor sets a private variable, _name, equal to "Harvey". The C# 7.0 version uses just one line but accomplishes the same task: public EmpData() => _name = "Harvey"; Destructors work much the same as constructors. Instead of using multiple lines, you use just one line to define them. Defining expression-bodied property accessors Property accessors can also benefit from the use of expression-bodied members. Here is a typical C# 6.0 property accessor with both get and set methods: private int _myVar; public MyVar { get { return _myVar; } set { SetProperty(ref _myVar, value); } } When working in C# 7.0, you can shorten the code using an expression-bodied member, like this: private int _myVar; public MyVar { get => _myVar; set => SetProperty(ref _myVar, value); } Defining expression-bodied event accessors As with property accessors, you can create an event accessor form using the expression-bodied member. Here’s what you might have used for C# 6.0: private EventHandler _myEvent; public event EventHandler MyEvent { add { _myEvent += value; } remove { _myEvent -= value; } } The expression-bodied member form of the same event accessor in C# 7.0 looks like this: private EventHandler _myEvent; public event EventHandler MyEvent { add => _myEvent += value; remove => _myEvent -= value; }

View Article
The C#-Provided Constructor

Article / Updated 01-31-2018

C# keeps track of whether a variable has been initialized and doesn’t allow you to use an uninitialized variable. For example, the following code chunk generates a compile-time error: public static void Main(string[] args) { int n; double d; double calculatedValue = n + d; } C# tracks the fact that the local variables n and d haven’t been assigned a value and doesn’t allow them to be used in the expression. Compiling this tiny program generates these compiler errors: Use of unassigned local variable 'n' Use of unassigned local variable 'd' By comparison, C# provides a default constructor that initializes the data members of an object to 0 for numbers false for Booleans null for object references Consider the following simple program example: using System; namespace Test { public class Program { public static void Main(string[] args) { // First create an object. MyObject localObject = new MyObject(); Console.WriteLine("localObject.n is {0}", localObject.n); if (localObject.nextObject == null) { Console.WriteLine("localObject.nextObject is null"); } // Wait for user to acknowledge the results. Console.WriteLine("Press Enter to terminate..."); Console.Read(); } } public class MyObject { internal int n; internal MyObject nextObject; } } This program defines a class MyObject, which contains both a simple data member n of type int and a reference to an object, nextObject (both declared internal). The Main() method creates a MyObject and then displays the initial contents of n and nextObject. The output from executing the program appears this way: localObject.n is 0 localObject.nextObject is null Press Enter to terminate... When the object is created, C# executes a small piece of code that the compiler provides to initialize the object and its members. Left to their own devices, the data members localObject.n and nextObject would contain random, garbage values. The code that initializes values when they’re created is the default constructor. It constructs the class, in the sense of initializing its members. Thus C# ensures that an object starts life in a known state: all zeros, nulls, or false values, depending on type. This concept affects only data members of the class, not local variables in a method.

View Article
Returning Multiple Values Using Tuples in C#

Article / Updated 01-30-2018

In versions of C# prior to C# 7.0, every return value was a single object. It could be a really complex object, but it was still a single object. In C# 7.0, you can actually return multiple values using tuples. A tuple is a kind of dynamic array nominally containing two items that you can interpret as a key and value pair (but it isn’t strictly required). In C#, you can also create tuples containing more than two items. Many languages, such as Python, use tuples to simplify coding and to make interacting with values considerably easier. C# 4.x actually introduced the concept of a Tuple as part of dynamic programming techniques. However, C# 7.0 advances the use of tuples to allow returning multiple values rather than just one object. This book doesn’t provide extensive coverage of tuples, but they work so well in returning complex data that you definitely need to know something about this use of tuples. Using a single-entry tuple A tuple relies on the Tuple data type, which can accept either one or two inputs, with two being the most common (otherwise, you can simply return a single object). The best way to work with tuples is to provide the data types of the variables you plan to provide as part of the declaration. Here’s an example of a method that returns a tuple: static Tuple getTuple() { // Return a single value using the tuple. return new Tuple("Hello", 123); } The code begins by specifying that getTuple() returns a Tuple consisting of two items, a string and an int. You use the new keyword to create an instance of Tuple, specify the data types in angle brackets, , and then provide the data values. The getTuple() method effectively returns two values that you can manipulate individually, as shown here: // This is where your program starts. static void Main(string[] args) { // Obtain a single entry tuple. Console.WriteLine( getTuple().Item1 + " " + getTuple().Item2); // Wait for user to acknowledge the results. Console.WriteLine("Press Enter to terminate..."); Console.Read(); } To access a single-entry tuple like this one, you call getTuple(), add a period, and then specify which item to use, Item1 or Item2. This example just demonstrates how tuples work, so it’s simple. The output looks like this: Hello 123 Press Enter to terminate... Using a tuple lets you return two values without resorting to complex data types or other odd structures. It makes your code simpler when the output requirements fit within the confines of a tuple. For example, when performing certain math operations, you need to return a result and a remainder or the real part and the imaginary part of a complex number. Relying on the Create() method An alternative way to create a tuple is to rely on the Create() method. The result is the same as when working with the method above. Here’s an example of using the Create() method: // Use the Create() method. var myTuple = Tuple.Create("Hello", 123); Console.WriteLine(myTuple.Item1 + "\t" + myTuple.Item2); This approach isn’t quite as safe as using the method above because myTuple could end up with anything inside. You could further eliminate the portion of the constructor to force the compiler to ascertain what myTuple should receive as input. Using a multi-entry tuple The true value of a tuple is in creating datasets using extremely easy coding methods. This is where you might choose to view Item1 as a key and Item2 as a value. Many dataset types today rely on the key and value paradigm and viewing a tuple in this way does make it incredibly useful. The following example shows the creation and return of a tuple dataset. static Tuple[] getTuple() { // Create a new tuple. Tuple[] aTuple = { new Tuple("One", 1), new Tuple("Two", 2), new Tuple("Three", 3) }; // Return a list of values using the tuple. return aTuple; } You specify the return types of the Tuple data type. However, this example adds a pair of square brackets ([]) similar to those used for an array. The square brackets tell C# that this version of getTuple() returns multiple tuples, not just one. To create a tuple dataset, you begin with the variable declaration as shown for aTuple. Each new entry into the tuple requires a new Tuple declaration with the requisite inputs as shown. The entire thing is placed within curly brackets and you end it with a semicolon. To return the tuple, you simply use the return statement as normal. Accessing the tuple requires use of an enumerator, and you can do anything you would normally do with an enumerator, such as interact with the individual values using foreach. The following code shows how you might perform this task just for experimentation purposes: static void Main(string[] args) { // Obtain a multiple entry tuple. Tuple[] myTuple = getTuple(); // Output the values. foreach (var Item in myTuple) { Console.WriteLine(Item.Item1 + "\t" + Item.Item2); } // Wait for user to acknowledge the results. Console.WriteLine("Press Enter to terminate..."); Console.Read(); } The foreach statement places individual items from myTuple into Item. You then access the data elements individually by using Item1 and Item2 as before. Here’s the output from this example: One 1 Two 2 Three 3 Press Enter to terminate... Creating tuples with more than two items Tuples can have one to eight items. If you want more than eight items, the eighth item must contain another tuple. Nesting tuples enables you to return an almost infinite number of items, but at some point you really do need to look at the complexity of your code and see whether you can keep the number of return items down. Otherwise, you find that your application executes slowly and uses a lot of resources. Here is an example that uses three items: static Tuple[] getTuple() { // Create a new tuple. Tuple[] aTuple = { new Tuple("One", 1, true), new Tuple("Two", 2, false), new Tuple("Three", 3, true) }; // Return a list of values using the tuple. return aTuple; } The technique follows the same pattern as before. The only difference is that you provide more values for each tuple. It also doesn’t matter whether you create a single tuple or a tuple array used as a dataset. Either choice allows you to use up to eight items per tuple.

View Article
page 1
page 2
page 3