✅ how do i override built-in methods?

i come from python where you can override methods in a class to work a certain way. for example, for use in the == operator, you can override a class to modify the behaviour of the __eq__ method which checks if two objects are equal. if i wanted to do an XOR on a class that holds an internal value, how can i override it so it works on the internal value instead of the class itself?
12 Replies
it’s raining outside
i want to make a superset of a ulong by adding extra methods, but i dont know if you can subclass that or not and how it would affect behaviour in code no you cannot in python you can subclass datatypes which i find pretty handy
Angius
Angius3mo ago
Operator overloading is a thing in C#, yes Far as subclassing an ulong goes... I don't think that's possible You would have to use composition over inheritance here Or make use of extension methods
shadi
shadi3mo ago
i think this would work on my phone so can't test public static MyClass operator ^ (MyClass a, MyClass b) { return new MyClass( a.Value ^ b.Value); }
Angius
Angius3mo ago
Yep
MODiX
MODiX3mo ago
Angius
REPL Result: Success
public record struct MyUlong(ulong Value)
{
public static MyUlong operator ^(MyUlong a, MyUlong b)
=> new(a.Value ^ b.Value);
}

var x = new MyUlong(718);
var y = new MyUlong(421);

x^y
public record struct MyUlong(ulong Value)
{
public static MyUlong operator ^(MyUlong a, MyUlong b)
=> new(a.Value ^ b.Value);
}

var x = new MyUlong(718);
var y = new MyUlong(421);

x^y
Result: MyUlong
{
"value": 875
}
{
"value": 875
}
Compile: 389.060ms | Execution: 104.519ms | React with ❌ to remove this embed.
jcotton42
jcotton423mo ago
Yeah you can’t, value types are sealed.
Anton
Anton3mo ago
python doesn't have value types though
jcotton42
jcotton423mo ago
@it’s raining outside for extra methods on ulong, look into extension methods.
public static class MyExtensions
{
public ulong Triple(this ulong u) => u * 3;
}

ulong ul = 2;
ul.Triple();
public static class MyExtensions
{
public ulong Triple(this ulong u) => u * 3;
}

ulong ul = 2;
ul.Triple();
it’s raining outside
this works? how?
canton7
canton73mo ago
Extension Methods - C#
Extension methods in C# enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Angius
Angius3mo ago
It's basically syntactic sugar over just calling it as a regular static method 79.Stuff() instead of Extensions.Stuff(79)
Want results from more Discord servers?
Add your server