creating a new type

how do Integers for example do it, that they are a struct under the hood but instead of calling a constructor like
int i = new int(0);
int i = new int(0);
they can be assigned like
int i = 0;
int i = 0;
8 Replies
IKryxxᵈᵉᵛ
IKryxxᵈᵉᵛOP12mo ago
and can the user replicate this?
exokem
exokem12mo ago
Primitive types like int are special cases that I assume are handled by the C# compiler It isn't really possible to do much custom syntax unless you want to write a preprocessor or something
IKryxxᵈᵉᵛ
IKryxxᵈᵉᵛOP12mo ago
shite thanks
exokem
exokem12mo ago
You can create custom types, but the syntax will use the new keyword like you have in the first line
cap5lut
cap5lut12mo ago
there is also implicit/explicit conversion:
MODiX
MODiX12mo ago
cap5lut
sharplab.io (click here)
Example e = 5;
Console.WriteLine(e);
public readonly struct Example {
private readonly int value;
public Example(int value) {
this.value = value;
}
public override string ToString() => $"Exaample({value...
public static implicit operator Example(int value) => ...
}
Example e = 5;
Console.WriteLine(e);
public readonly struct Example {
private readonly int value;
public Example(int value) {
this.value = value;
}
public override string ToString() => $"Exaample({value...
public static implicit operator Example(int value) => ...
}
React with ❌ to remove this embed.
cap5lut
cap5lut12mo ago
⤴️ will print Exaample(5) thats basically like casting, if that was explicit instead of implicit u would have to write Example e = (Example)5; its basically a casting operator override
Thinker
Thinker12mo ago
Also about ints, I the int constructor is never called when you do int i = 0;. Again ints are special.
Want results from more Discord servers?
Add your server