Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

var: practical reference

var: practical reference: var asks the compiler to infer a local variable's static type from its initializer.

Version: C# language; verified against C# 14 reference

Syntax

var /* grammar-specific form */

var asks the compiler to infer a local variable's static type from its initializer.

Use it when the type is obvious or the variable name communicates the role better.

It does not mean dynamic and the inferred type cannot change after assignment.

It requires an initializer and cannot infer from null alone or an untyped method group.

The complete program actually uses var; its exact expected stdout is Int32.

Examples

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

var value = 7; Console.WriteLine(value.GetType().Name);

Result

Int32

The complete program actually uses `var`; its exact expected stdout is `Int32`.

Sources