C
C#14mo ago
Dultus

❔ The best way to create custom types?

Hey, what's the best way to implement a custom type? E.g. I want an Id and instead of having it like this:
int id = 12345;
int id = 12345;
I want it like that:
ID id = 12345;
ID id = 12345;
So I don't calculate with the ID for example because it's an ID, not some random number.
11 Replies
Thinker
Thinker14mo ago
Use a readonly struct or something and add an implicit conversion operator
public readonly struct Id
{
private readonly int _value;

public Id(int value) => _value = value;

public static implicit operator Id(int value) => new(value);
}
public readonly struct Id
{
private readonly int _value;

public Id(int value) => _value = value;

public static implicit operator Id(int value) => new(value);
}
something like this
Pobiega
Pobiega14mo ago
If a method expects an ID and that implicit exists, will it accept an int in its place? On phone so can't test
Thinker
Thinker14mo ago
yeah well, overload resolution will do its best to figure it out
Pobiega
Pobiega14mo ago
Yeah, that's what I suspected. I'd recommend not having an implicit then
Dultus
DultusOP14mo ago
That's a good point.
Pobiega
Pobiega14mo ago
Creating IDs from literals should be rare enough that a constructor or explicit isnt too much of a hurdle
Thinker
Thinker14mo ago
Also, are all integers valid IDs?
Dultus
DultusOP14mo ago
public struct Id
{
private readonly int value;
public static Id FromInt(int value)=> new Id(value);
public Id(int value) => this.value = value;
public int GetInt() => this.value;
}
public struct Id
{
private readonly int value;
public static Id FromInt(int value)=> new Id(value);
public Id(int value) => this.value = value;
public int GetInt() => this.value;
}
So I guess something like this would be the best way still?
Thinker
Thinker14mo ago
value could just be a property
Dultus
DultusOP14mo ago
True, at this point..
Accord
Accord14mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server