C
C#8mo 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
Thinker8mo 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
Pobiega8mo 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
Thinker8mo ago
yeah well, overload resolution will do its best to figure it out
Pobiega
Pobiega8mo ago
Yeah, that's what I suspected. I'd recommend not having an implicit then
Dultus
Dultus8mo ago
That's a good point.
Pobiega
Pobiega8mo ago
Creating IDs from literals should be rare enough that a constructor or explicit isnt too much of a hurdle
Thinker
Thinker8mo ago
Also, are all integers valid IDs?
Dultus
Dultus8mo 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
Thinker8mo ago
value could just be a property
Dultus
Dultus8mo ago
True, at this point..
Accord
Accord8mo 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
More Posts