Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the C# compiler differentiates between these 2 cases?

When you have some property that's like:

using Algebra;

public Algebra.Vector3 Direction
{
    get { return this.direction; }
}

then compile and later change it to:

using Algebra;

public Vector3 Direction
{
    get { return this.direction; }
}

it seems like the compiled code is different between the two assemblies, which I could see using the Reflector.

Why does the compiler differentiates between the two code? Isn't it only necessary to see if there is any ambiguous type at compile time and if there isn't, have the compiled code be the same for both? I would assume the compiled code to use fully qualified names for every member at all times.

like image 661
Joan Venge Avatar asked Jan 27 '11 22:01

Joan Venge


2 Answers

I can't reproduce this. Sample code:

namespace Algebra
{
    public class Vector3 {}
}

namespace Test
{
    using Algebra;

    public class Program
    {
        private Vector3 direction = null;

        public Vector3 Direction1
        {
            get { return direction; }
        }

        public Algebra.Vector3 Direction2
        {
            get { return direction; }
        }
    }
}

The generated IL for the two properties is exactly the same, and they look the same in reflector.

My guess is that you've actually got another class called Vector3 in the "global" namespace (or some other namespace that you have a using directive for).

Try hovering over both type names in Visual Studio and see what they show.

like image 103
Jon Skeet Avatar answered Sep 25 '22 02:09

Jon Skeet


Here is an example that would generate the results you are observing. Hopefully this clears up what you’re asking. Assuming you have

  • a separate library containing the type Vector3 in a namespace Algebra;

  • the following files in your project:

File ①

namespace NotAlgebra
{
    public class Vector3
    {
        // ...
    }
}

File ②

using Algebra;

namespace NotAlgebra
{
    public class XYZ
    {
        // Refers to NotAlgebra.Vector3 (defined in File 1 above)
        Vector3 MyProperty1 { get; }

        // Refers to Algebra.Vector3 (defined in the external library)
        Algebra.Vector3 MyProperty2 { get; }
    }
}
like image 22
Timwi Avatar answered Sep 26 '22 02:09

Timwi