Reputation: 190799
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#?
Upvotes: 4
Views: 787
Reputation: 1
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
Upvotes: 0
Reputation: 96477
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);
}
}
}
Upvotes: 9
Reputation: 29051
You could 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 on.
/// 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; }
}
Upvotes: 1
Reputation: 532455
Encapsulate it in it's own class (or a struct, if more appropriate).
public class UID
{
public int Value { get; set; }
}
Write your methods in terms of your UID class, limiting the exposure to the actual value type to the smallest subset of code necessary.
publc class Entity
{
public UID ID { get; set; }
public void Foo( UID otherID )
{
if (otherID.Value == this.ID.Value)
{
...
}
}
}
}
Upvotes: 2
Reputation: 20044
Define a struct with just one field
public struct ID_Type
{
public long Id;
};
and use it whereever you need it.
If you have just one class where the ID type is needed, you can also try to make this class a generic class with the UID type being a type parameter.
Upvotes: 1
Reputation: 8564
Wouldn't the result be the same if you used int and then changed it later on?
Upvotes: 0
Reputation: 44066
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!
Upvotes: 8
Reputation: 124696
Is there a way to mimic typedef in C#
No
to solve my problem
What problem?
Upvotes: -2