Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an unused constructor cause an assembly dependency in this case?

Tags:

c#

.net

There's a subtle point about assembly dependencies I would like to understand. I have a project which uses SharpDX through a custom wrapper like so:

SharpDX.dll <- Wrapper.dll <- Project.dll

In Wrapper.dll is a type such as:

public class D3DWrapperTypeA {
    //public D3DWrapperTypeA(SharpDX.Device device) {
    //    
    //}

    public D3DWrapperTypeA(IntPtr devicePointer) {
         SharpDX.Device device = new SharpDX.Device(devicePointer);
         // etc
    }
}

In this class, if I uncomment the commented constructor, then Project.dll must reference SharpDX.dll, even if it doesn't use the constructor.

However, I also have another wrapper type like so:

public class WrapperTypeB {
    public SharpDX.Device GetDevice(int adapter) {
        // etc
    }

    public IntPtr GetDevicePointer(int adapter) {
        return GetDevice(adapter).NativePointer;
    }
}

And here, as long as I don't actually use the GetDevice method that returns a SharpDX object, Project.dll doesn't need to reference SharpDX.dll.

Why is it that even an unused constructor that takes a parameter of a SharpDX type causes a dependency on SharpDX, whereas an unused method that returns a parameter of a SharpDX type doesn't?

like image 279
Asik Avatar asked Aug 28 '13 15:08

Asik


1 Answers

It is pretty unclear how you know you have a dependency. You will however have a compile-time dependency. A runtime dependency would be much harder to explain.

The compile-time dependency exists because the C# compiler insists that it needs to know all of the overloads of the constructor so that it can call the correct one. It won't be able to do so if it doesn't know anything about SharpDX.Device if it can't load the metadata for SharpDX.dll.

That's not the case of a method that returns a SharpDX.Device, the return type is never used to determine which overload is the correct one.

like image 60
Hans Passant Avatar answered Oct 26 '22 23:10

Hans Passant