Category Archives: Code Sample

C# Explicit and Implicit Variable Typing

There are typically multiple ways to do something in a programming language. And with C# there are two ways to set the type of a variable or object — explicitly and implicitly. Here is some code to demonstrate the two ways. I’ll explain a bit more after the code.

using System;

namespace ExplicitImplicitTyping
{
    class Program
    {
        static void Main(string[] args)
        {
            // Examples of EXPLICITLY setting the type of variables and objects
            string myString = "This is a string of characters";
            int myInteger = 12345;
            double myDouble = 123.45;
            Car myCar = new Car();

            // Examples of IMPLICITLY setting the type of variables and objects
            var mySecondString = "This is a string of characters";
            var mySecondInteger = 12345;
            var mySecondDouble = 123.45;
            var mySecondCar = new Car();
        }
    }

    class Car
    {
        public string Make { get; set; }
    }
}

 

Notice that the only difference between the two sets of declarations is that with the explicit declarations you use the type keywords (string, int, double, etc.), but when implicitly declaring the variables you use the var keyword.

So what’s going on here? When you explicitly declare a variable’s type you are telling the compiler which type to use for that variable so it can set aside a space in memory that is large enough to hold that variable. When you use the var keyword you are making the compiler figure out the type for you. If the compiler were human, and spoke English, it would say something like, “Ok, I see you’ve created a variable with the name of myString. And I see that you’ve set its value to a bunch of characters between two double quotes. Based on what I’ve been programmed to do, that fits the definition of a string. So I’m going to declare your myString variable as type string.”

My understanding is that the var keyword was implemented in C# for no other reason than to speed up code generation. “Hey, you’re using Visual Studio, so you must know how to program and set your variables, so we’re going to let the compiler do this little step for you by using the var keyword so you can get on to other things.”

One last thing. According to the MSDN documentation, an implicitly typed variable using the var keyword “…is strongly typed just as if you had declared the type yourself…”. That means that once the compiler determines and sets the variable type, the type will not change unless you cast it to another type. The is different than some other programming languages.

Happy coding!