✅ 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
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 handyOperator 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
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);
}
Yep
Angius
REPL Result: Success
Result: MyUlong
Compile: 389.060ms | Execution: 104.519ms | React with ❌ to remove this embed.
Yeah you can’t, value types are sealed.
python doesn't have value types though
@it’s raining outside for extra methods on
ulong
, look into extension methods.
this works? how?
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.
It's basically syntactic sugar over just calling it as a regular static method
79.Stuff()
instead of Extensions.Stuff(79)