Blog for Junior Developers C#/.NET

Monday, October 21, 2024

Since C# 3.0, C#/.NET developers have access to the so-called implicit type var. You can learn exactly what var is, when and how to use it in C# in this article.

what-is-var-implicit-type-in-csharp.png

What is the purpose of using the var keyword?


I have prepared some declarations and initialization of variables in the Main method.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            int number1 = 11;
            double number2 = 11.0;
            string name1 = "ModestProgrammer";
            bool isDeleted1 = false;
            DateTime dateTime1 = new DateTime(2021, 1, 1);
            AnExampleOfAVeryLongClassName anExampleOfAVeryLongClassName1 = 
                 new AnExampleOfAVeryLongClassName();
        }
    }
}


As you can see, each of these variables has an explicitly defined type (int, double, string, bool, DateTime, and AnExampleOfAVeryLongClassName). Thanks to the var keyword, i.e. the implicit type, we can replace the specified type with the word var in each of these cases.

using System;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            int number1 = 11;
            double number2 = 11.0;
            string name1 = "ModestProgrammer";
            bool isDeleted1 = false;
            DateTime dateTime1 = new DateTime(2021, 1, 1);
            AnExampleOfAVeryLongClassName anExampleOfAVeryLongClassName1 = 
                 new AnExampleOfAVeryLongClassName();

            var number3 = 11;
            var number4 = 11.0;
            var name2 = "ModestProgrammer";
            var isDeleted2 = false;
            var dateTime2 = new DateTime(2021, 1, 1);
            var anExampleOfAVeryLongClassName2 = 
                 new AnExampleOfAVeryLongClassName();
        }
    }
}


As you can see, we don't have any errors at this point, and the entire code works the same as before. We declared our variables as the implicit type var and the compiler now implicitly knows, thanks to initialization, what type we mean. So this notation is acceptable and if you now hover over the word var, you will see the type that will actually be created in that place.

typ-domniemany-var-w-csharpie-podglad-typu.jpg

So in our case we have assigned 11 to the variable number3 and it is explicitly the int type. For number4 it is double. For name2 string. For isDeleted2 bool. For dateTime2 DateTime, and for anExampleOfAVeryLongClassName2 it is of course AnExampleOfAVeryLongClassName. Also the types where we used var are identical to those in the previous example, where we declared these types explicitly.

For me the second notation, i.e. using var is much more readable, but here I agree that it may be a controversial issue. Of course, some people may prefer the first form.

Also the first issue is readability, but the second one, more crucial in my opinion, is the issue of the length of the types. If we have some longer names, then writing the var keyword may be much faster. You can see this already in our example of creating an instance of the AnExampleOfAVeryLongClassName class. What's more, if we want to use LINQ and e.g. retrieve a collection of elements, this record will be even longer.

See this example:

using System.Collections.Generic;

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            List<AnExampleOfAVeryLongClassName> classess = 
                 new List<AnExampleOfAVeryLongClassName>();
        }
    }
}


Here we have a list of elements of our class with a long name: AnExampleOfAVeryLongClassName. And now, if I wanted to get some elements from this list using e.g. LINQ, then again this example would look something like this:

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

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            List<AnExampleOfAVeryLongClassName> classess = 
                 new List<AnExampleOfAVeryLongClassName>();

            IEnumerable<AnExampleOfAVeryLongClassName> myClassess =
                classess
                .Where(x => x.Id == 1)
                .OrderBy(x => x.Id);
        }
    }
}


So I use IEnumerable here, then again as a generic type I pass this long class name, variable name and only then I can create a LINQ query.


And it is in such cases that using the implicit type var will be a much better solution:

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

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var classess = 
                 new List<AnExampleOfAVeryLongClassName>();

            var myClassess = classess
                            .Where(x => x.Id == 1)
                            .OrderBy(x => x.Id);
        }
    }
}


See how the length and thus the readability of our code changed in this case. Thanks to the use of var, our example is much more readable.


When can't you use the word var?


Finally, I would just like to point out that we can only use the word var in the case of declarations with initialization. Without initialization, the compiler will not guess what type we mean, so we can't use var then.

For such a notation:

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
            var age; //compilation error
        }
    }
}


A compilation error will be reported, because here we have only a declaration, without initialization, and the compiler does not know what type we wanted to implicitly declare here.


The word var can only be used inside methods or constructors. For example, we cannot create a field or property of type var.

namespace App
{
    class Program
    {
        private var number = 1; //compilation error
        public var MyProperty { get; set; } = 2; //compilation error

        static void Main(string[] args)
        {
        }
    }
}


In both cases, a compilation error will be reported.

The same applies to method signatures, where the word var is not allowed.

namespace App
{
    class Program
    {
        static void Main(string[] args)
        {
        }

        public static var MyMethod() //compilation error
        {
            return "1";
        }

        public static string MyMethod(var a = 1) //compilation error
        {
            return "1";
        }
    }
}


Both of the above methods will also throw a compilation error.


SUMMARY


To sum up, I think it's worth using the implicit type var wherever possible, but especially when connecting to LINQ, where our variable names can be quite long. I use the word var wherever possible in my applications and I think it significantly increases the readability of my code.

If you liked this article, be sure to join my community. Sign up for the free newsletter, where every week I share valuable materials, especially regarding C# and the .NET platform (free subscription - newsletter).

Author of the article:
Kazimierz Szpin

KAZIMIERZ SZPIN
Software Developer C#/.NET, Freelancer. Specializes in ASP.NET Core, ASP.NET MVC, ASP.NET Web API, Blazor, WPF and Windows Forms.
Author of the blog CodeWithKazik.com

Previous article - Value Type and Reference Type in C#
Dodaj komentarz
© Copyright 2024 CodeWithKazik.com. All rights reserved. Privacy policy.
Design by Code With Kazik and Modest Programmer.