4 ms·
I'm fairly new to Unity programming in C# and I was surprised a few months ago that everything in C# must be in a class. As far as I can tell there is no such t
by jay_kyburz 6y ago
I'm fairly new to Unity programming in C# and I was surprised a few months ago that everything in C# must be in a class. As far as I can tell there is no such thing as just a function.
Now I have I have a class with some static functions in it.
- wvenable 6y agoA static class in C# isn't really a class, it's just a namespace to hold functions.
- imtringued 6y agoClasses in OOP are type dependent namespaces. That's the entire reason why classes even exist. You can now reuse function and member names inside classes instead of having to globally qualify them to prevent name collisions. In C you would do something like class_name_function_name(var, par1, par2). The OOP counterpart would look like this in Java: ClassName var = new ClassName(); var.functionName(par1, par2). Now you might be asking if this is really such a big deal. I mean it is pretty obvious that this can be useful even if you limit yourself to static dispatch and completely avoid inheritance and polymorphism. The reality is that functional programming languages like Haskell don't support type dependent namespaces. When you name a field in a Haskell record then no other record is allowed to have a field with the same name.
- toolslive 6y agoClasses are used for a variety of things. Let's look at it from a language designer's perspective. If design a language and you want to offer inheritance, specialization,.... you will often end up with offering classes. Once you have that you could decide to offer namespaces. But, a class with some static methods comes quite close to what you need to offer for a namespace. Hold on: you can use classes to combine some functionality that belongs together and come close to what you need for modules. It's not a surprise the designers of java, c#, ... went that route.
- jimbob45 6y agohttps://stackoverflow.com/a/1027853 https://stackoverflow.com/a/1027853 In honesty, statics accomplish the same thing.
- goto11 6y agoC# is slowly moving away from "everything is a class". Static classes with static imports is basically a module or namespace. C# also allows stand-alone functions inside methods. But you still have to declare a static class to hold "top-level" functions, which is somewhat ugly. Given the current development of C# I expect we see stand-alone functions in the future.
- arethuza 6y ago"everything in C# must be in a class" As an aside, C# also has structure types which have value semantics - one example being DateTime: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct https://docs.microsoft.com/en-us/dotnet/csharp/language-refe...
- twodave 6y agoNot to mention tuples and (soon in C# 9!) record types.