---
title: "How can var know of an undefined type?"  
description: "How can var know of an undefined type?"  
author: "Royce Roy"  
published: 2014-02-03  
updated: 2014-02-03  
canonical: https://www.mindstick.com/forum/1943/how-can-var-know-of-an-undefined-type  
category: "c#"  
tags: ["c#"]  
reading_time: 2 minutes  

---

# How can var know of an undefined type?

How can the [implicit](https://www.mindstick.com/interview/827/what-are-implicit-objects-list-them) type [variable](https://www.mindstick.com/articles/1807/objective-c-data-types-variables-object-creation) [var](https://www.mindstick.com/forum/33920/what-is-different-var-and-dynamic-types-in-c-sharp) know a type that is not defined in the [scope](https://www.mindstick.com/interview/372/what-are-the-different-scopes-for-java-variables) (using using)?

## Example:

This is ok

```
public class MyClass{    public void MyMethod           {        var list = AStaticClass.GetList();    }}
```

But this is not ok

```
public class MyClass{    public void MyMethod           {        List<string> list = AStaticClass.GetList();    }}
```

In the last [code](https://yourviews.mindstick.com/view/85458/alan-turing-the-mastermind-behind-cracking-the-enigma-code-during-world-war-ii) snippet I have to [add](https://www.mindstick.com/forum/12983/add-address-in-textbox-when-page-is-load-and-if-i-search-address-in-textbox-show-in-map-by-javascript) using System.Collections.Generic; for it to work.

How does this work?

## Replies

### Reply by Pravesh Singh

Hi Royce,\

When the compiler does the type inference it replaces var with System.Collections.Generic.List<string> and your code becomes:

```
public class MyClass{    public void MyMethod           {        System.Collections.Generic.List<string> list = AStaticClass.GetList();    }}
```

But since the compiler spits IL, the following C# program (without any using statements):

```
public class Program{    static void Main()    {        var result = GetList();    }    static System.Collections.Generic.List<string> GetList()    {        return new System.Collections.Generic.List<string>();    }}
```

and the Main method looks like this:

```
.method private hidebysig static void Main() cil managed{    .entrypoint    .maxstack 8    L_0000: call class [mscorlib]System.Collections.Generic.List`1<string> Program::GetList()    L_0005: pop    L_0006: ret}
```

As you can see the compiler inferred the type from the right hand-side of the assignment operator and replaced var with the fully qualified type name.

\


---

Original Source: https://www.mindstick.com/forum/1943/how-can-var-know-of-an-undefined-type

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
