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

Did you find this page helpful?