❔ C# methods
Why do I need to have a class or struct, so that I can have functions?
In other words, why do I need to put functions inside classes or structures?
26 Replies
Is it just the way the language was build?
Functions must always be associated to some object?
yes
there are no first-class functions in c#
If that is the case, are lambdas the way to go in c# so small functions that dont have to be directly related to any object?
sure
lambdas are great
there are also static classes that can have static methods for reuse
without instantiation
Yeah, I was thinking about that, would be annoying if the language forced me to instantiate an object every time I want to call a function :)
In C you do not need to associate a class/struct with a function
I come from C++
In F# you work with functions, even though it does support classes
So what you are asking is just how C#, as an OOP language, is built
Yes
Pretty much
I was curious to see the compiler didnt allowed me to declare functions outside classes
I typically make a static class for helpers related by concern
no syntax sugar to avoid having to write static all over?
A great example of a static class is
Console
not that i'm aware of
and when using you need
using static
You do
Console.WriteLine("hello")
without creating an instance of ConsoleCould be a Singleton
it's not though
No there is not. However you can omit the static keyword on a class and only have the methods static
I see
I will experiment with that a bit
Happy coding
Thank you both :)
"first-class member" is a term that means "can be treated as an expression", which basically means "can be assigned to a variable and passed around" which C# supports in the form of delegates. Functions without a class are usually just called functions, while functions inside a class are usually called methods.
Technically speaking, C# doesn't have functions. Even local functions are converted to regular methods by the compiler (I think)
it depends on context, lambdas are common in many places
There's one scenario where you don't need to put method inside of a class explicitly, and that's when using top-level statements. You're limited to just a single file then, though.
Yes, the first time I created a project I didn't notice I had top level statements checked and it felt like a scripting language ahahah
I see what you mean tho, that is interesting
Yep, that's the goal of TLS
Making quick little projects without the whole ceremony
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.