Home > Articles > Programming > Visual Studio

The .NET Languages

In this chapter from Microsoft Visual Studio 2015 Unleashed, 3rd Edition, Lars Powers and Mike Snell focus on the foundations of .NET programming in C# and Visual Basic. They start by highlighting new features of the languages for those who are already familiar with C# and VB. They then include a language primer as a review of some basic .NET programming tasks. They then cover some more in-depth programming features, enhancements to C# 6.0 and VB 14, and language-related IDE enhancements. The chapter concludes with an overview and map of the .NET Framework class library.
This chapter is from the book

Unlocking the productivity promises of the Visual Studio IDE is at the heart of this book. The IDE, of course, also ships from Microsoft in concert with new versions of the .NET languages and Framework. You need to have a solid grasp of programming the Visual Basic or C# language using the .NET Framework to take advantage of everything Visual Studio has to offer. Of course, you may also need to know many other things such as XAML, Hypertext Markup Language (HTML), Cascading Style Sheets (CSS), TypeScript, JavaScript (and related frameworks), C++, F#, and LightSwitch. Today’s developer likely does not code in a single language syntax. However, VB and C# are still at the core of most Visual Studio development.

In this chapter, we set aside the IDE (for the most part) and focus on the foundations of .NET programming in C# and Visual Basic. We start by highlighting new features of the languages for those who are already familiar with C# and VB. We then include a language primer as a review of some basic .NET programming tasks. We then cover some more in-depth programming features, enhancements to C# 6.0 and VB 14, and language-related IDE enhancements. The chapter concludes with an overview and map of the .NET Framework class library.

What’s New in C# 6.0 and VB 14

This section is for developers looking for highlights on what’s new about the C# and Visual Basic languages. For those who need the basics (or a refresher), we suggest you start by reading the “Language Primer” section a little later in this chapter. You can then return here to see what additions exist to the primer.

In general, the language changes are small additions that help you write cleaner code. They simplify coding by eliminating unnecessary, repetitive code. The changes also make the code easier to read and understand.

Null-Conditional Operators

One of the most repetitive tasks you do as a programmer is to check a value for null before you work with it. The code to do this checking is typically all over your application. For example, the following verifies whether properties on an object are null before working with them. (For a more complete discussion of all operators, see the section “Understanding Operators” later in this chapter.)


public bool IsValid()
    if (this.Name != null &&
        this.Name.Length > 0 &&
        this.EmpId != null &&
        this.EmpId.Length > 0)
        return true;
        return false;


Public Function IsValid() As Boolean
    If Me.Name IsNot Nothing AndAlso
        Me.Name.Length > 0 AndAlso
        Me.EmpId IsNot Nothing AndAlso
        Me.EmpId.Length > 0 Then

        Return True

        Return False
    End If
End Function

Both C# 6.0 and VB 14 now allow automatic null checking using the question mark dot operator (?.). This operator tells the compiler to check the information that precedes the operator for null. If a null is found in an If statement for example, the entire check is considered false (without additional items being checked). If no null is found, then do the work of the dot (.) to check the value. The code from earlier can now be written as follows:


public bool IsValid()
    if (this.Name?.Length > 0 &&
        this.EmpId?.Length > 0)
        return true;
        return false;


Public Function IsValid2() As Boolean
    If Me.Name?.Length > 0 AndAlso
        Me.EmpId?.Length > 0 Then

        Return True

        Return False
    End If
End Function

The null-conditional operator cleans up code in other ways. For instance, when you trigger events, you are forced to copy the variable and check for null. This can now be written as a single line. The following code shows both the old way and the new way of writing code to trigger events in C#.


//trigger event, old model
  var onSave = OnSave;
  if (onSave != null)
    onSave(this, args);

//trigger event using null-conditional operator
  OnSave?.Invoke(this, args);

ReadOnly Auto Properties

Auto properties have been a great addition to .NET development. They simplify the old method of coding properties using a local variable and a full implementation of get and set. See “Creating an Automatically Implemented Property” in the later section “Language Features.”

However, up until 2015, auto properties required both a getter and a setter; this makes it hard to use them with immutable data types. The latest release now allows you to create auto properties as read only (with just the get). A read-only backing field is created behind the scenes on your behalf. The following shows an example of a full property, a standard auto property, and the new read-only auto property.


Public class Employee
    //full property
    private string name;
    public string Name
        get { return name; }
        set { name = value; }

    //standard auto property
    public string Address { get; set; }

    //read-only auto property
    public string EmpId { get; }


Public Class Employee

    'full property
    Private _name As String
    Public Property Name() As String
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
        End Set
    End Property

    'standard auto property
    Public Property Address As String

    'read-only auto property
    Public ReadOnly Property EmpId As String

End Class

Read-only auto properties can be assigned from the constructor. Again, they have a hidden backing field. The compiler knows this field exists and thus allows this assignment. The following shows a constructor inside the Employee class shown above assigning the read-only EmpId property. Notice that, in Visual Basic, the Sub New constructor must be used to assign a read-only property.


public Employee(string id)
    EmpId = id;


Public Sub New(ByVal id As String)
    EmpId = id
End Sub

You can also initiate read-only auto properties at the time of their creation (just like the field that backs them), as shown next. Note that if you were to combine this assignment with the previous constructor code (that initialized the read only property), the object creation would happen first. Thus, the constructor init would take precedence.


public string EmpId { get; } = "NOT ASSIGNED";


Public ReadOnly Property EmpId As String = "NOT ASSIGNED"

NameOf Expression

You now have access to the names of your code elements, such as variables and parameters. The .NET languages use the NameOf expression to enable this feature.

Prior to 2015, you often had to indicate the name of a program element by enclosing it in a string. However, if the name of that code element changed, you had an error lurking in your code (unless you managed to remember to change the string value). For example, consider the following code that throws an instance of ArgumentNullException. This class takes a string as the name of the argument. It then uses the string value to find your program element; it’s not strongly typed programming at all.


public void SaveFeedback(string feedback)

    if (feedback == null)
        //without nameOf
        throw new ArgumentNullException("feedback");


Public Sub SaveFeedback(ByVal feedback As String)
    If feedback Is Nothing Then
        'without nameOf
        Throw New ArgumentNullException("feedback")
    End If
End Sub

The NameOf expression eliminates this issue. You can use the expression along with your actual, scoped code element to pass the name of your code element as a string. However, NameOf uses the actual type to reference the name. Therefore, you get compile-time checking and rename support. The following shows an example of throwing the same exception as used earlier but using NameOf.


throw new ArgumentNullException(nameof(feedback));


Throw New ArgumentNullException(NameOf(feedback))

Using (Imports) Statics

The using statement (Imports in VB) allows developers to declare namespaces that are in scope; thus, classes in the namespace do not need to be fully qualified inside your code. (See “Organizing Your Code with Namespaces” later in this chapter.) You can now use the same statement with static classes. To do so, in C# you must include the static keyword as in “using static.” In Visual Basic, you simply use Imports and then specific the static library.

The ability to indicate using (Imports in VB) with a static class tells the compiler that the class and its members are now in scope. This allows you to call a method of the static class without referencing the namespace or even the class name inside your code.

As an example, consider the static class System.Math. You could add a using statement to the top of your code file. In that case, calls to the static methods would no longer need to be qualified by namespace and class. Instead, you could call the method directly. The following shows the difference between the two approaches.


using static System.Math;

//use the static method, round without using
return System.Math.Round(bonus, 0);

//use the static method
return Round(bonus, 0);


Imports System.Math

'use the static method, round without imports
Return System.Math.Round(bonus, 0)

'use the static method
Return Round(bonus, 0)

String Interpolation

The .NET languages allow you to replace portions of a string with values. To do so, you use String.Format or StringBuilder.AppendFormat. These methods allow you to use placeholders as numbers inside curly braces. These numbers are replaced in series by the values that follow. This is cumbersome to write and can lead to confusion.

In 2015, the code editor allows you to put the variable right in the middle of the string. You do so using the format that starts the string with a dollar sign ($) as an escape character. You can then add curly braces within the string to reference variables, as in {value}. The editor gives you IntelliSense for your values, too. The call to String.Format then happens for you behind the scenes. The example that follows shows how the previous use of String.Format is now simplified with enhanced string literals.


//old style of String.Format
return String.Format("Name: {0}, Id: {1}", this.Name, this.EmpId);

//string interpolation style
return ($"Name: {this.Name}, Id: {this.EmpId}");


'old style of String.Format
Return String.Format("Name: {0}, Id: {1}", Me.Name, Me.EmpId)

'string interpolation style
Return $"Name: {Name}, Id: {EmpId}"

Lambda Expressions as Methods (C# Only)

Methods, properties, and other bits of code can now be assigned using lambda expression syntax (in C# only). (See “Write Simple Unnamed Functions Within Your Code (Lambda Expressions)” later in this chapter.) This makes writing and reading code much easier. The following shows a full method implementation as a lambda and a single expression. Notice that we use the string interpolation discussed in the prior section.


public override string ToString() => $"Name: {this.Name}, Id: {this.EmpId}";

Index Initializers (C# Only)

Prior language editions brought developers the concept of creating an object and initializing its values at the same time. (See “Object Initializers” later in this chapter.) However, you could not initialize objects that used indexes. Instead, you had to add one value after another, making your code repetitive and hard to read. C# 6.0 supports index initializers. The following shows an example of creating a Dictionary<string, DateTime> object of key/value pairs and initializing values at the same time.


var holidays = new Dictionary<string, DateTime>
    { "New Years", new DateTime(2015, 1, 1) },
    { "Independence Day", new DateTime(2015, 7, 4) }

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020