English
Summary
Conclusions
Encapsulation hides an object’s state and exposes only a public contract, which lets a class guarantee its invariants. Access modifiers define visibility scopes: private is the class, internal is the assembly, public is any code, and the options involving protected relate to inheritance. A multi-project solution with a class library uses internal for hidden helper types. State is protected by properties with restricted setters, command methods, and defensive copies. Static members belong to the class: static fields are shared by all objects, a static constructor runs once, static classes group helper functions, and factory methods with private constructors provide clear ways to create objects.
Self-check questions
- What is encapsulation? What is a class invariant?
- Why are public fields considered bad practice?
- What access modifiers exist in C#? What is the access scope of each?
- What is the default access for class members and top-level types?
- What is an assembly? How is the
internalmodifier related to assemblies? - How do you create a solution with a class library and a console application?
- What is a defensive copy? When is it needed?
- How do
const,readonly, andstatic readonlydiffer? - What is a static field? Give examples of its use.
- Why can’t a static method access instance fields?
- When does a static constructor run?
- What is a static class? What is the
using staticdirective for? - What are factory methods and private constructors used for?
- How are namespaces and project files organized?
- Why is global mutable state dangerous?
Useful links
- Access modifiers: https://learn.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers
- Static classes and members: https://learn.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members
- Static constructors: https://learn.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
- The
readonlykeyword: https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/readonly - Class library in Visual Studio: https://learn.microsoft.com/dotnet/core/tutorials/library-with-visual-studio