We all are aware that visual studio solution explorer views the project files in a tree like structure. If we add a directory to the root of our project and place some files there, that files will be nested on that directory. Also, we know that this nesting capability is not only for directories. In web applications, .cs and .designer.cs file will be nested under .aspx file. If you worked with entity data model, you might have observed that model's designer.cs file is nested under the .edmx file.
Now, what if we would be able to nest our own files under our own created files. Isn't it crazy? well, not much here is how we can do it. Lets take a simple example project.
In the below screen-shot, you can observe the existing non-nested files.
Here IShape is an interface and Rectangle, Triangle, and Square are the classes derived from it. It would be helpful if we were able to see this relation in the solution explorer itself, isn't it? or it will be helpful, if we were able to browse the related files immediately. Well, we can do it by nesting the implementation files under the interface file.
- Go to the folder on windows explorer and open your project file(.csproj) with notepad or any other text or xml editor.
- You can see the ItemGroup under PropertyGroup. Here is mine:
<ItemGroup> <Compile Include="IShape.cs" /> <Compile Include="Program.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Rectangle.cs" /> <Compile Include="Square.cs" /> <Compile Include="Triangle.cs" /> </ItemGroup>
- Modify it like this:
<ItemGroup> <Compile Include="IShape.cs" /> <Compile Include="Program.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Rectangle.cs" > <DependentUpon>IShape.cs</DependentUpon> </Compile> <Compile Include="Square.cs" > <DependentUpon>IShape.cs</DependentUpon> </Compile> <Compile Include="Triangle.cs" > <DependentUpon>IShape.cs</DependentUpon> </Compile> </ItemGroup>
- Remove the / from compile tag of the file which you would like to nest.
- Wrap the parent file name with the tags <DependentUpon>, i.e <DependentUpon>ParentFileName.cs</DependentUpon> and place it under the file name which you would like to nest.
- Close the compile tag(</compile>) of the nested file and we are done!
- This is the final screenshot of our solution explorer:
Note: This is not only limited for inheritance. You can do it for any files. Be careful while editing the project file. Improper edit of this file will corrupt your project from being open in visual studio.
Thanks Naveen - just what I was looking for. VS2012 was refusing to nest the files generated by my T4 template. This sorted it out.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteReally helpful. Thank you.
ReplyDeleteAll the contents you mentioned in post is too good and can be very useful. I will keep it in mind, thanks for sharing the information keep updating, looking forward for more posts.Thanks seo expert
ReplyDelete