Home > database >  How to access dotnet's System.Int32 type from within my own System namespace (containing my cus
How to access dotnet's System.Int32 type from within my own System namespace (containing my cus

Time:11-06

From within my custom top level System namespace (where I have also defined struct Int32) I am unable to access the dotnet's standard System.Int32 type. My own Systme.Int32 is hiding the dotnet's System.Int32. I have tried using global:: to fully qualify the System.Int32 name to get to dotnet's standard type , but it still keeps referencing my own type. I cannot find a way around it. Reading Eric Lippert's 11 year old answer to a related question here https://stackoverflow.com/a/3830520/423632 suggests I need to write my own compiler for this. But it should not be impossible to do.

The following code does not compile , giving the error refering to the first statement in the Main method:
" error CS0029: Cannot implicitly convert type 'int' to 'System.Int32' "

// DOES NOT COMPILE ! 

using System; 

namespace System
{


    struct Int32
    {

        public override string ToString()
        {

            return "My own Int32 lol";


        }
    }

    class Program
    {
        static int Main(string[] args)
        {
            global::System.Int32 x = 5; // error CS0029 
            Console.WriteLine(x);
            return 0;
        }

    }

}

CodePudding user response:

One way I found is to use an extern alias:

extern alias MSCorLib;
namespace System
{
    struct Int32
    {
        public override string ToString()
        {
            return "My own Int32 lol";
        }
    }
    class Program
    {
        static int Main(string[] args)
        {
            MSCorLib::System.Int32 x = 5;
            Console.WriteLine(x);
            return 0;
        }

    }
}

If you compile this with the -reference option:

csc Program.cs -reference:MSCorLib=mscorlib.dll

Then it will print 5 as expected.

For Int32 specifically, you can also just use int:

int x = 5;

Of course, this also applies to double, float, short, etc.

  • Related