Typedef emulation in C #

I have a field variable called uid in the class. Type int, but I want to open the possibility that I change it long or short.

With C ++, a typedef is for this purpose, but I see that C # does not have a typedef.

Is there a way to simulate a typedef in C #?

+4
source share
10 answers

I think you are trying to use a type alias. If so, you can use it using the using alias directive. You must specify the full type (full namespace) when assigning an alias.

For instance:

 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); } } } 
+9
source

Try to make a class . It looks like typedef to steroids, and you can change the internal representation as much as you want without affecting the interface!

You can even make it a guide!

+8
source

Make it a structure:

 struct Uid { public int Value; } 
+3
source

Encapsulate it in your own class (or structure, if more appropriate).

 public class UID { public int Value { get; set; } } 

Write your methods in terms of your UID class, limiting the impact of the actual value type to the smallest subset of code needed.

 publc class Entity { public UID ID { get; set; } public void Foo( UID otherID ) { if (otherID.Value == this.ID.Value) { ... } } } } 
+2
source

Define a structure with only one field

  public struct ID_Type { public long Id; }; 

and use it wherever you need it.

If you have only one class that needs an identifier type, you can also try to make this class a universal class with a UID type, which is a type parameter.

+1
source

You can always use generics:

 public class Foo<T> { public T MyField { get; set; } } public class FooInt : Foo<int> { } public class FooShort : Foo<short> { } 

or just change it later.

 /// want an int public class Foo { public int MyField { get; set; } } /// and just change it later on: public class Foo { public short MyField { get; set; } } 
+1
source

Wouldn't the result be the same if you used int and then changed it later?

0
source

Here is a simple solution that helped.

  using typedef = System.Int32; class MyTypeDef { typedef ERROR, TRUE=1, FALSE=0; public int MyMethod() { if(this is an error condition) { ERROR = TRUE; } else { ERROR = FALSE; } return ERROR; } // end MyMethod } // end MyTypeDef 
0
source

Is there any way to simulate typedef in c #

No

to solve my problem

What is the problem?

-2
source

Source: https://habr.com/ru/post/1332268/


All Articles