Author avatar

Dániel Szabó

Type Inference in C#

Dániel Szabó

  • Feb 15, 2020
  • 5 Min read
  • 999 Views
  • Feb 15, 2020
  • 5 Min read
  • 999 Views
Languages Frameworks and Tools
C#

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.

1
2
string guides = "Pluralsight Rocks!";
int number = 33;
csharp

After this declaration, we cannot do something like this.

1
2
guides = 33;
number = "Thirty three!"
csharp

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.

1
2
var guides;
var number;
csharp

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

1
2
guides = 22;
number = "C# is cool!"
csharp

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:

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

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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();
        }
        
        
    }
}
csharp

The output produced is the following.

1
2
3
4
Name=Small, OS=Windows 10
Name=Small-Medium, OS=Windows 10
Name=Medium, OS=Windows 2016
Name=Medium-Big, OS=Windows 2016
bash

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.

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

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.

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

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.

7