Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio Find all references ignores var

I want to find all references to some class in visual studio but instances defined with var are ignored.

Is there some way to fix this?

Here i am using SHIFT+F12 to get references

SHIFT+F12

The results are:

enter image description here

But when using ReportWindow on line 1197: enter image description here

I get what i want

enter image description here

like image 619
Matija K. Avatar asked Apr 21 '17 10:04

Matija K.


1 Answers

At this point in time, VS 2015, 2017 and 2019 have this behaviour for the built-in Find All References search, as well as Resharper's Find Usages and Find Usages Advanced search options. It is also expected behaviour.

The only time a var reference will be returned in the search results is when you make an explicit call to a constructor. Also, when a method is called and returned to variable that has been explicitly declared as the given type, that line will also be returned in the search results.

Personally, I like to use var only when it is obvious what is being returned and assigned to a variable, which is usually only when a constructor is called directly. This is also handy when declaring a class with a long and inconvenient name, avoiding having to type that type twice:

Dictionary<string, Ninja> trainees = new Dictionary<string, Ninja>();

Here is an example of a small program demonstrating where Find All References will find results and where it will not.

using System;
​
namespace VarSearchTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var ninja = NinjaAcademy.Train();     // <---------- does not find (implicit)
            Ninja ninja2 = NinjaAcademy.Train();  // <---------- finds (explicit type declaration)
            var chrisFarley = new Ninja();        // <---------- finds (explicit constructor call)


            Console.WriteLine(ninja.Hide());
            Console.WriteLine(ninja2.Hide());
            Console.WriteLine(chrisFarley.Hide());
        }
    }
​
    public class Ninja  // <-------------------- Find all references/usages
    {
        public string Hide()
        {
            return "Puff of smoke...";
        }
    }
​
    public static class NinjaAcademy
    {
        public static Ninja Train()  // <---------------- finds (explicit return type)
        {
            return new Ninja();      // <------------------ finds (explicit constructor call)
        }
    }
}

You can also track this github issue in case it ever changes in the future, as it would be handy to have implicit references easy to find. In the meantime, consider using var only in the scenarios where it provides convenience in the explicit situations.

like image 180
Jason Down Avatar answered Sep 28 '22 09:09

Jason Down