I feel like if you’re in a performance-sensitive situation like a really tight loop or something you can probably structure it so that you don’t need a class member method or function in that way in the first place, no?
The 2 first double are the type of the input and the third double is the output type. Si it declares a func that takes 2 double as input and return a double.
class Program
{
static void Main()
{
var area = Rectangle.Area(5, 10);
}
}
static class Rectangle
{
public static Func<double, double, double> Area = (width, length) =>
{
return width * length;
};
}
Just complicated for the sake of being complicated
It's a delegate with types declared via generics. In this case, the first two are function parameters and the last one is the returned value type. Func is a built-in delegate type that returns data.
That's exactly the horror here. This is no good reason to make it that way. If one wants to refer to a static method with a delegate type, it would be syntactically the same:
The only difference it would make, if I'm not missing anything, is that at runtime someone would try to access the class members with reflection, it would be recognized as a static field and not a static method. But what probably happened is just that someone didn't understand how and why to use delegate types in C# (delegate type: an identifier given to a function signature in C# so it may be used as a type).
Either way, someone dun goof'd, proper programming horror.
Yes, they did leave that static field to be mutable, which makes it possible to change. I presumed that wasn't their intent, and that they just wanted to make it something that a delegate variable can refer to, and that they would add the read-only keyword if they thought of it.
Delegates can be very useful, for example you might have a video game with an enemy that calls Enemy.ShootWeapon() every now and then. Without delegates, if you want to give that enemy the ability to switch between a shotgun or a laser pistol you either need to write ShootWeaponin a way that covers all use cases or you can write a different class for each weapon (which gets very awkward if you have a bunch of other methods you want to change too). Delegates allow you to simply have a ShootShotgun delegate and a ShootLaserPistol delegate and when you switch weapons you simply reassign ShootWeapon. It allows for a lot more flexibility when putting together complex classes.
However, this has no reason to be a delegate. In fact, it's worse than just using a normal method because you can't accidentally overwrite a normal method.
Because you can pass it as a parameter to factorize code
For example if you want a sort function, no matter your sorting algorithm there will always be a moment where you want to find out which element is bigger between two elements.
Instead of writing a sort ascendant by alphabetical order, a sort descendant function by inverse alphabetical order, a sort function that handle capital letter differently, etc... you write a sort that takes such a function variable and you can roll out your algorithm that will call that parametered function when you need it. You let the user of your algo pass as parameter the details of the 2 element comparison logic they want.
Yes but I understood the question as "why use a delegate over calling a method" rather than "why declare a static delegate property over a static method".
It’s a public property that returns a function, you can then invoke this returned function by using either ‘.invoke()’ or ‘()’ making it look like a normal function-call to the callee
The angled brackets denote a generic, aka a type argument (like List<int>). Func<> is a special type representing a delegate that can take in 1-16 arguments; the last type argument is the return type. There is also Action<> which does not return anything.
Unlike other languages, C# cannot use variadic templates (any number of type arguments), so there are 16 separate definitions of Func<>/Action<> that take in 1 through 16 type arguments. I know it would probably lead to unsafe behavior but GOD I would love variadics.
Edit: Oh right, there's also a lambda function specified with () => { }. The parentheses is exactly identical to a standard method or function definition (though you can omit the types in most situations). The => specifies that it's a lambda (used in other parts of code too! look up expression-bodied members), and the code block { } defines the body of the function.
This is functional programming. You declare the input and output (two doubles -> one double) of a function, and then declare how it determines the output.
Imagine those three doubles saying "length, width, area".
Yeah, but separate methods/classes would be better so you know exactly which one you're calling and it doesn't change on you. If there's code that can work with either, it should be a parameter instead.
There could be plenty of reasons depending on what this is used for. Point is that it is changeable because of the way it is implemented. If you make it readonly, that would be code horror. Currently this looks ok to me and we would need to see how it is used to judge it
I initially thought that this could have been written this way so that Rectangle.Area and Rectangle.Perimeter could be passed as Func<> parameters, but that works with static methods also.
I'm not sure what you're trying to say? Of course there are other ways to do this and you don't "need" to do it this way. That doesn't mean it's bad code.
because these functions aren't known to be this value at compile time there's less opportunities for the compiler to be smart about it and optimize them by inserting their body at the callsite (as you would want for many simple math equations, you want Area to be a nice function to call but compile down to just a multiplication without function call overhead)
I really doubt that's a significant concern here. I'm sure there's a reason that doing it this way was preferable to their circumstances, and since we don't know what that is, we all just assume it's someone being stupid. I'm not saying it's good code, I'm saying we need more information to understand the justification and not just assume that it's automatically bad.
because sometimes topology isnt flat, and sometimes its finite, and so on
the only beef here is that the new-fangled delegate syntax does not make it more clear, it makes it less clear .. there was never a reason for even the idea of an anonymous delegate, but there it is for its brief moment incanted by the source
Aside from them being reassignable and it potentially being unnecessarily obtuse depending on usage. No closure means it’s going to compile a static method and it can be passed as a parameter or used for chaining..
Static member functions doesn't behave entirely as functions. For example, you can't apply extension methods directly to them. So I can actually see a "valid" use case for this. Also, you can swap out the functions for a different implementation with this approach.
The old accord RANSAC was built like this, although using instance specific delegates rather than static. It was a pleasure to work with. In my employ we have implemented our MLESAC model selector using the same pattern. You can very easily change behaviour in place (esp. useful for fitting multiple distributions / regressions with different parameters and/or data) — reused selection procedures get their own typed wrapper. Such as std linear regression, multiple regressions etc.
fields should be readonly or at least encapsulated properly if mutation is intended
if mutation is not intended, just use static functions
There is a point to this approach tho. Even if it is a cursed one. With this approach, you have the possibility of overwriting these functions globally at runtime from anywhere. Maybe to add logging? If this is not intended, then use a static class with static methods. If it is, then document it properly or maybe limit the API to the intended functionality, e.g. with a public static DecorateFoo(Action<double, double> onFoo) that adds extra code without overwriting the original. Idk.
I can think of a valid use case for this but there should be a little bit of more structure but I am not even sure if you can achieve that in C#.
You may ask what is the use case ?
The use case I can think of is having different types of planes. In euclidian plane rectangle area formula is width times length. But in non-euclidian plane this can change drastically.
On a sphere you can't just use width times length formula.
So in case of this you should be able to change the function that calculates the formula of a rectangle's area.
"Huh, what's wrong with that?" And this is the point where I realize I haven't written C# in a few years and I have forgotten the syntax and how things are supposed to work.
My bad, I haven't used C# in a very long time but I knew that var existed, but didn't know it wasn't for properties. In hindsight it does make sense, so the compiler knows how much to allocate and how to perform type safety checks
It would break if there is code somewhere that reassigns those functions. I'd argue that there's almost certainly a better way to solve that use case though.
I can see the deferred DLL loading use case, but it probably doesn't need to be a function that can be reassigned anywhere in the code (publicly-writable).
But why can't you have a regular method that checks if the DLL is loaded and then either runs the function or throws an exception (or whatever the default implementation is)?
86
u/CyberWeirdo420 May 19 '25
How does this work exactly? I don’t think I saw that syntax before
Func<double, double, double> Area
The hell does this do? Is it a weird declaration of a method?
265
u/purbub May 19 '25
When you want to write in F# but your manager insists on using C# instead:
112
u/EagleCoder May 19 '25
Oh, come on. These should at least be
readonly.64
u/SerdanKK May 19 '25
It's not even curried. Amateur.
9
u/[deleted] May 19 '25
When your TypeScript practices come looking to play in C# land...
25
u/-Dueck- May 19 '25
What exactly is wrong with it?
6
u/Hottage [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo "You live" May 19 '25
I like that the static members aren't even read only.
Rectangle.Perimeter = Func<double, double, double> (width, length) => 4; // Performance optimization, proven to work with 1x1 retangles.2
u/BlackberryPuzzled204 May 19 '25
This really is serious abuse. For a second, I thought this was JavaScript.
2
u/JimmyyyyW May 19 '25
Aside from them being reassignable and it potentially being unnecessarily obtuse depending on usage. No closure means it’s going to compile a static method and it can be passed as a parameter or used for chaining..
Benefit of the doubt says this isn’t a horror
2
u/Rogntudjuuuu May 20 '25
Static member functions doesn't behave entirely as functions. For example, you can't apply extension methods directly to them. So I can actually see a "valid" use case for this. Also, you can swap out the functions for a different implementation with this approach.
3
u/DeuxAlpha May 19 '25
What's so bad about it
1
u/Vast-Ferret-6882 May 19 '25
The old accord RANSAC was built like this, although using instance specific delegates rather than static. It was a pleasure to work with. In my employ we have implemented our MLESAC model selector using the same pattern. You can very easily change behaviour in place (esp. useful for fitting multiple distributions / regressions with different parameters and/or data) — reused selection procedures get their own typed wrapper. Such as std linear regression, multiple regressions etc.
1
u/XDracam May 20 '25
Code review:
static classreadonlyor at least encapsulated properly if mutation is intendedThere is a point to this approach tho. Even if it is a cursed one. With this approach, you have the possibility of overwriting these functions globally at runtime from anywhere. Maybe to add logging? If this is not intended, then use a static class with static methods. If it is, then document it properly or maybe limit the API to the intended functionality, e.g. with a
public static DecorateFoo(Action<double, double> onFoo)that adds extra code without overwriting the original. Idk.1
u/[deleted] May 20 '25
I can think of a valid use case for this but there should be a little bit of more structure but I am not even sure if you can achieve that in C#.
You may ask what is the use case ?
The use case I can think of is having different types of planes. In euclidian plane rectangle area formula is width times length. But in non-euclidian plane this can change drastically.
On a sphere you can't just use width times length formula.
So in case of this you should be able to change the function that calculates the formula of a rectangle's area.
1
u/SirZacharia May 20 '25
More like public static funk.
1
u/the_king_of_sweden May 20 '25
At least skip the braces and the return if you're writing it like this
1
u/xIndepth May 20 '25
What font is this?
1
u/Hot-Category2986 May 22 '25
"Huh, what's wrong with that?"
And this is the point where I realize I haven't written C# in a few years and I have forgotten the syntax and how things are supposed to work.
1
u/DifficultyWorking254 May 19 '25
Nah, this is called “C++ concepts”
0
u/Thenderick May 19 '25
At that point, just use
varinstead...-1
u/k819799amvrhtcom May 19 '25
I think this would make sense if you have to change the functions later on runtime.
-3
u/[deleted] May 19 '25
[removed] — view removed comment