Skip to Content
Course content

8: Type Inference with var

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Wait, is var basically like JavaScript where the type can change?

This is the biggest misconception I see when people coming from TypeScript or JS hit C#. The short answer is: absolutely not. C# is still a strongly typed language. When you use var, you aren't telling the compiler to "figure it out at runtime"; you're telling it to "figure it out right now during compilation and then lock it in."

Once the compiler sees var score = 100;, it knows score is an int. If you try to assign a string to it on the next line, the code won't even compile. It's essentially a shortcut for your fingers, not a change in how the language works.

// The compiler does the work for you here
var productPrice = 19.99m; // Compiler sees 'm' and decides this is a decimal

// This will cause a compile-time error, just like if you'd written 'decimal productPrice'
productPrice = "Too expensive!"; 

When am I actually supposed to use this instead of the explicit type?

I'll be honest: you can use var almost everywhere inside a method, but you shouldn't. I use it when the type is "obvious from the right side of the assignment." If I have to jump to another file to figure out what a method returns, var is a hindrance, not a help.

Where it really shines is with those long, clunky generic types. Look at this comparison:

// This is tedious and redundant. I'm writing the type twice.
Dictionary<string, List<Order>> customerOrders = new Dictionary<string, List<Order>>();

// This is clean, and I still know exactly what it is because of the 'new' keyword.
var customerOrders = new Dictionary<string, List<Order>>();

If you're using LINQ or complex API calls, var is a lifesaver. Writing out IEnumerable<UserViewModel> three times in one method just creates visual noise that hides the actual logic of your code.

Can I just use var for everything now?

Not quite. There are a few hard boundaries. First, you can't use var for fields (variables declared directly in a class but outside a method). Fields require an explicit type because the compiler needs to know the object's layout before any methods are even executed.

Second, you can't declare a var without initializing it. Since the compiler determines the type based on the value you provide, you can't just say var x; and assign it later. It would have no idea what x is supposed to be.

public class OrderManager
{
    // ERROR: This won't compile. Fields must have explicit types.
    var _retryCount = 3; 

    public void Process()
    {
        // ERROR: This won't compile. No value to infer the type from.
        var timeout; 
        timeout = 30;
    }
}



📋 Practical Task

Refactoring the Inventory Tracker

You've inherited a piece of code for an inventory system that is incredibly verbose. Your goal is to clean up the UpdateStock method using var where it improves readability, but you also need to fix a compilation error in the class structure.

Requirements:

  • Replace the explicit type declarations inside the UpdateStock method with var for the currentStock and newBatch variables.
  • Fix the class-level field var _warehouseLocation by giving it an explicit type (it should be a string).
  • Ensure the code still compiles and maintains its strong typing.
public class InventoryTracker
{
    // FIX THIS: This field is causing a compiler error
    var _warehouseLocation = "North-Sector-7";

    public void UpdateStock(string sku, int addedAmount)
    {
        // REFACTOR THESE: Use type inference here
        Dictionary<string, int> currentStock = GetStockLevels();
        List<int> newBatch = GetIncomingShipment(sku);

        int total = currentStock[sku] + newBatch.Sum();
        Console.WriteLine($"New total for {sku} at {_warehouseLocation}: {total}");
    }

    private Dictionary<string, int> GetStockLevels() => new Dictionary<string, int> { { "SKU123", 10 } };
    private List<int> GetIncomingShipment(string sku) => new List<int> { 5, 5, 2 };
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.