Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef emulation in C#

Tags:

c#

I have a field variable named uid in a class. The type is int, but I want to open the possibility that I change it long or short.

With C++, typedef is the one for this purpose, but I see C# doesn't have typedef.

Is there a way to mimic typedef in C#?

like image 759
prosseek Avatar asked Nov 29 '22 05:11

prosseek


2 Answers

I think you're trying to alias the type. If so, you can alias it via the using alias directive. You must specify the fully qualified type (the entire namespace) when assigning an alias.

For example:

using System;
using MyAlias = System.Int32;

namespace UsingAlias
{
    class Program
    {
        static void Main(string[] args)
        {
            MyAlias temp = Math.Min(10, 5);
            Console.WriteLine(temp);

            MyAlias result = MyAlias.Parse("42");
            Console.WriteLine(result);
        }
    }
}
like image 62
Ahmad Mageed Avatar answered Dec 18 '22 17:12

Ahmad Mageed


Try making a class. It's like a typedef on steroids, and you can change the internal representation as much as you want without affecting the interface!

You could even make it a guid!

like image 39
Greg D Avatar answered Dec 18 '22 17:12

Greg D