Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Type Inference in C#

Feb 15, 2020 • 5 Minute Read

Introduction

C# is a strongly typed language, and its default type declaration is explicit. This means we have to specify a type for a new variable or the compiler will throw an error. With version 3 of C#, a new keyword, var, was introduced that allows developers to store any type of value in an implicit way. This means that the compiler decides during compile time, when the first assignment happens, what the type will be for that variable. This can be easily integrated with LINQ.

var

Before the introduction of type inference, we had to explicitly define what would be a string. integer, or any other type before compile time.

      string guides = "Pluralsight Rocks!";
int number = 33;
    

After this declaration, we cannot do something like this.

      guides = 33;
number = "Thirty three!"
    

The compiler will let us know that it cannot convert between these types.

If we do not want to decide beforehand what the type should be, we can use the following expressions.

      var guides;
var number;
    

Then later in the app, we can assign the desired values.

      guides = 22;
number = "C# is cool!"
    

But we will still get an error if we want to assign a different type of variable than the type assigned at the first occurrence. For example:

      guides = 22;
guides = "This is not going to work."
    

This will fail, as the compiler cannot convert implicitly between these types.

LINQ

LINQ stands for Language-Integrated Query, a set of technologies based on the integration of query capabilities directly into the C# language. They are very similar to SQL queries, and the goal is to filter out data based on specific criteria. LINQ supports most datatypes, including XML, SQL etc. For full details, visit the official documentation.

In the below example we will create a Servers class with a set of attributes including Name, OS, CPU, RAM and Price. Using LINQ, we will be able to filter servers based on these properties.

      using System;
using System.Collections.Generic;
using System.Linq;

namespace Pluralsight
{
    public class Servers
    {
            public string Name { get; set; }
            public string OS { get; set; }
            public Int16 CPU { get; set; }
            public Int16 RAM { get; set; }
            public double Price { get; set; }
        
        public static void Main()
        {

            List<Servers> serversList = new List<Servers>{
            new Servers(){ Name="Small", OS="Windows 10", CPU=2, RAM=2, Price=10 },
            new Servers(){ Name="Small-Medium", OS="Windows 10", CPU=2, RAM=3, Price=12 },
            new Servers(){ Name="Medium", OS="Windows 2016", CPU=8, RAM=16, Price=15 },
            new Servers(){ Name="Medium-Big", OS="Windows 2016", CPU=8, RAM=20, Price=18 },
            new Servers(){ Name="Big", OS="Windows 2019", CPU=16, RAM=32, Price=25 }
            };
            var serverQuery = from server in serversList
                              where server.Price <= 18
                              select new { server.Name, server.OS, server.CPU, server.RAM, server.Price };
            foreach (var server in serverQuery)
            {
                Console.WriteLine("Name={0}, OS={1}", server.Name, server.OS);
            }
            Console.ReadKey();
        }
        
        
    }
}
    

The output produced is the following.

      Name=Small, OS=Windows 10
Name=Small-Medium, OS=Windows 10
Name=Medium, OS=Windows 2016
Name=Medium-Big, OS=Windows 2016
    

Let's dissect the example in order to understand how type inference and LINQ fit together.

We are using two additional namespaces. One is called System.Collections.Generic, and the other is System.Linq. The first provides us with the implementation of the List data structure where we store our servers. The second adds the LINQ capabilities to our application. After the initialization of the list with the servers, the magic happens.

      var serverQuery = from server in serversList
    where server.Price <= 18
    select new { server.Name, server.OS, server.CPU, server.RAM, server.Price };
    

First we define our variable, which holds the query results, then the query looks for servers cheaper than 19. The var keyword allows us to decide the type of variable during runtime, basically detaching the type of items look for and the actual content that we store in serversList.

Processing results also happens with the help of the var keyword.

      foreach (var server in serverQuery)
    {
        Console.WriteLine("Name={0}, OS={1}", server.Name, server.OS);
    }
    

Conclusion

In this guide, we learned to utilize two useful features of C#. The var keyword helps us write cleaner, easier-to-maintain code, and LINQ helps us filter data in a more elegant way. I hope this guide has been informative to you and I would like to thank you for reading it.

Dániel Szabó

Dániel Szabó

Written content author.

More about this author