C# Articles
C# (pronounced "see sharp") is like C's cooler cousin. Simplified and streamlined, this programming language is still crazy-powerful.
Articles From C#
Filter Results
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 SheetCheat Sheet / Updated 12-08-2021
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 SheetArticle / 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 ArticleArticle / 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 ArticleArticle / 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 ArticleArticle / 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 ArticleArticle / 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) { <strong> // Create delegate instance.</strong> <strong> UpdateProgressCallback anon = delegate() </strong> <strong> {</strong> <strong> progressBar1.PerformStep(); // Method ‘pointed’ to</strong> <strong> };</strong> <strong> </strong> if(<strong>anon != null</strong>) <strong>anon()</strong>; // 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 ArticleArticle / 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 ArticleArticle / 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 ArticleArticle / 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