How to Import Other Namespaces into Visual C#?

MrSplosion picture MrSplosion · Feb 18, 2012 · Viewed 10.7k times · Source

Sorry if my question seems a little noobish but I can't find an answer. I would like to use DirectInput for my XNA game. I've read around and it seems this is the best way to get input from a gamepad other than a XBox 360 controller. The first step is to include the Microsoft.DirectX.DirectInput namespace however I don't quite know how. Simply putting it in at the beginning of my class doesn't work, visual C# doesn't recognize it.

This got me thinking should I download the DirectX SDK? There is alot of stuff in there and the file is big how do I just download the single namespace? Is this even possible? If I can download the single namespace where do I put the file?

Now you can see all the questions racking around in my brain. So how do I make visual C# recognize the Microsoft.DirectX.DirectInput namespace so I can use the methods, properties and all that good stuff?

Thanks!

Answer

phoog picture phoog · Feb 18, 2012

You need to set a reference to the DLL containing the code library you'd like to use. Presumably that's part of the SDK, so yes, you should download it. Then, in Visual Studio

  • open the solution explorer
  • open the project where you want to use the library
  • right-click the references node for that project
  • choose "add reference"
  • navigate to and select the dll

Once you've added the reference successfully, VS should recognize the using directive (and any types you've used from the assembly).

Note that references are made to assemblies; assemblies are not the same as namespaces. Beginners often confuse the two. Types that are defined in different assemblies can be in the same namespace; the BCL has dozens of examples of this.

Furthermore, the "using" directive doesn't cause anything to be loaded or anything like that; it just allows you to specify types without fully qualifying the names. In fact, it's possible to code in C# without ever using a using directive. For example, the following code files are equivalent:

using System.Collections.Generic;
public static class Collector
{
    public static ICollection<T> Collect(IEnumerable<T> enumerable)
    {
        return new List<T>(enumerable);
    }
}

AND

public static class Collector
{
    public static System.Collections.Generic.ICollection<T> Collect(System.Collections.Generic.IEnumerable<T> enumerable)
    {
        return new System.Collections.Generic.List<T>(enumerable);
    }
}