✅ Public class in C#
Hello guys, sorry to disturb you all; can someone explain when do we use a "public class" and non-public class in C# pls. For example, consider the following code:
I didn't use TLS. I use write "class"; does it have a default value? like private class / public class? if so, what do these values represent pls. When should we use private/ public or just write class and why?
Say when we create new classes, like a class for person etc, it matters if we put private/public or anything? Also, if a class is public, it can only have one public class within the same file ?
Now, consider the code above, can I create multiple classes within that same file? Like when after the class Program ending curly braces, I juste write a class, named "class Person" ? Is that good practice/recommended?
Sorry that's a lot of questions
17 Replies
C# always defaults to the lowest access
In context of a project, the classes being public/internal/private don't really matter all that much
Those access modifiers are there should you want to access those classes from another project
yeah I see, here in the code, it defaults to which level of access ?
private?
Yep
Access Modifiers - C#
All types and type members in C# have an accessibility level that controls whether they can be used from other code. Review this list of access modifiers.
yeah I see, it's there just if we want to reuse classes in another project
Now, can I create multiple classes within that same file? Like when after the class Program ending curly braces, I juste write a class, named "class Person" ? Is that good practice/recommended?
You can have multiple classes per file, sure
Though the convention is one class per file
yep I see, if we have multiple class per file, we can't use the TLS anymore ?
You can
oh ok, just for the new class I want to create, a just need to specify sommething like class Person { . . .}
Something like that?
$tias
But yes
ok ok
thanks !
by the way, why not declare all classes/method/everything as public? Because only the developer will have access to source code, no ? (well I know it's not done but why can't we ?)
You can
yeah, but is it bad practice or it depends on the use case?
Eh, depends how strict you want to be
It's considered a good practice to make classes internal by default
Personally, outside of libraries, I don't care much
yeah I see
noted, thanks !!