skip to content

Classes and Hierarchies

Classes, constructors, inheritance, interfaces, access modifiers and extension members: how C# models a domain. Interviewers ask about virtual dispatch and interface design.

on this pageshow

explore

questions

page 1 of 2

In C#, what access level does a type, a class member, an interface member and a nested type get when no access modifier is written?

level: juniorimportance: must knowfreq 72%

answer

  1. the default depends on where it is declared
  2. namespace level vs inside a type
  3. assembly for types, containing type for members
  4. interfaces flip the member default

basics

~10 s

A top-level class, struct, interface, enum or delegate defaults to internal. A member of a class or struct, including a nested type, defaults to private. Interface members and enum members default to public.

solid answer

~30 s

C# picks the default from the declaration's position. A type declared directly in a namespace may only be `public` or `internal`, and with no modifier it is `internal`: visible to the whole assembly, invisible outside it. Writing `private` or `protected` there is error CS1527. Inside a class, struct or record, a member declared with no modifier is `private`, and that includes nested types. Interface members are `public` unless you write otherwise, and enum members are always `public`. A member is never more visible than its containing type, so a `public` method on an `internal` class is still unreachable from another assembly.

code

csharp · 24 lines
csharp
using System.Reflection;

const BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
Type calc = typeof(InvoiceCalculator);

Console.WriteLine($"InvoiceCalculator public:  {calc.IsPublic}");
Console.WriteLine($"rate private:              {calc.GetField("rate", All)!.IsPrivate}");
Console.WriteLine($"Cache nested private:      {calc.GetNestedType("Cache", All)!.IsNestedPrivate}");
Console.WriteLine($"IInvoiceStore.Save public: {typeof(IInvoiceStore).GetMethod("Save")!.IsPublic}");
Console.WriteLine($"Total: {new InvoiceCalculator().Total(100)}");

class InvoiceCalculator                 // top-level, no modifier: internal
{
    int rate = 20;                      // class member, no modifier: private

    class Cache                         // nested type, no modifier: private
    {
        public int Read(InvoiceCalculator c) => c.rate;   // nested code reads the outer private field
    }

    public int Total(int net) => net + net * new Cache().Read(this) / 100;
}

interface IInvoiceStore { void Save(); }  // interface member, no modifier: public

go deeper

for a junior

Recall the two positions: internal for a type in a namespace, private for a member of a class or struct. Then add the exceptions: interface and enum members are public.

for a middle

Explain the accessibility domain: a member is capped by its containing type, so public inside an internal class still stops at the assembly boundary. Mention CS1527 for private top-level types.

for a senior

Show you write modifiers explicitly on API surfaces and enforce it with IDE0040, and that you keep types internal until another assembly truly needs them.

for a principal

Frame the defaults as a team decision: an internal-by-default codebase keeps refactoring cheap, and the cost is deciding how tests and sibling assemblies reach those internals.

## Two questions decide the default C# has six **declared accessibility** levels (`public`, `internal`, `protected`, `protected internal`, `private protected`, `private`) and, from C# 11, the `file` modifier for top-level types. When a declaration carries no modifier, the compiler does not pick the most open or the most closed level everywhere. It asks **where the declaration sits**: 1. Is it a type declared directly in a namespace (a **top-level type**), or a member of another type? 2. If it is a member, what kind of type contains it: a class, struct, record, interface or enum? ## The defaults, position by position | Declared in | Default with no modifier | What you may write instead | |---|---|---| | A namespace (top-level type) | `internal` | `public` only (or `file`) | | A class or record class | `private` | all six levels | | A struct or record struct | `private` | `public`, `internal`, `private` | | An interface | `public` | all six; a `private` member needs a body | | An enum | `public` | nothing: enum members take no modifier | Some consequences worth saying out loud in an interview: - **`class InvoiceCalculator { }` in a namespace is `internal`.** Another project that references the assembly cannot name it. Only `public` widens it. - **A top-level type cannot be `private` or `protected`.** The compiler rejects it with CS1527: "Elements defined in a namespace cannot be explicitly declared as private, protected, protected internal, or private protected." - **A field written as `int rate;` inside a class is `private`.** The same is true for methods, properties, events, constructors and nested types. - **A nested type defaults to `private` inside a class or struct.** Only the containing type (and anything nested in it) can name it. - **Interface members default to `public`.** Since C# 8 you may write other access modifiers on interface members, but leaving them out still means `public`; a nested type declared inside an interface is `public` too. - **Structs cannot use the `protected` family.** A struct cannot be inherited, so a `protected` field in a struct is error CS0666. ## Nested types and the containing type A nested type is a member of its containing type, so it can use **everything the containing type can use**, including that type's `private` fields. The reverse is not true: the containing class has no special access to the nested class's `private` members, and touching one is CS0122 ("is inaccessible due to its protection level"). ## The member is capped by its type The **accessibility domain** of a member is the region of program text where it can be referenced. For a member of a nested or top-level type, the domain is the intersection of the member's declared level and the domain of its containing type. So: - a `public` method on an `internal` class can be called anywhere in the assembly and nowhere else; - a `public` class nested inside an `internal` class is effectively `internal`; - marking everything `public` inside an `internal` class is harmless to outsiders, but it is noise in review. ## Seeing it for yourself The snippet in the examples uses reflection to print what the compiler emitted for declarations with no modifiers. The class reports `IsPublic` as `False` because it is `internal`, the field reports `IsPrivate`, the nested class reports `IsNestedPrivate`, and the interface method reports `IsPublic`. The nested `Cache` class reads the outer class's private `rate` field, which is legal precisely because nested code shares the containing type's access. ## A three-project walkthrough Picture a solution with a `Billing.Core` class library, a `Billing.App` executable that references it, and a `Billing.Core.Tests` project. In `Billing.Core`, `class InvoiceCalculator` with no modifier is internal: - every file in `Billing.Core` can create it and call its `public` methods; - `Billing.App` cannot name it at all; referencing it there is CS0122; - `Billing.Core.Tests` cannot name it either, unless the library grants it friend access with `InternalsVisibleTo`; - `InvoiceCalculator`'s private `rate` field is reachable only from inside `InvoiceCalculator`, including its nested `Cache` class, and from nowhere else, friend or not. Changing the first line to `public class InvoiceCalculator` opens the type and its `public` members to `Billing.App`, while the field stays private. ## Habits that follow from the defaults - Write the modifier anyway on anything that is part of an API surface; the style rule IDE0040 can require explicit accessibility modifiers so nobody relies on memory. - Leave top-level types `internal` until another assembly genuinely needs them; widening later is easy, narrowing a published `public` type breaks callers. - Remember that `static` and `sealed` are not access modifiers: they change instantiation and inheritance, not who can see the type.

  • Does marking a C# class static or sealed change who can see it?
    No. `static` and `sealed` control instantiation and inheritance, not visibility; the access level still comes from the modifier or the default. A `static` class is implicitly sealed: `new Clock()` is CS0712, declaring a variable of its type is CS0723 and deriving from it is CS0709. Declaring a `protected` member in a `sealed` class only draws warning CS0628, because no derived class can ever use it.
  • Can the containing class read a private field of its nested class?
    No. Access flows inward only: nested code can use everything the containing type can, including its `private` members, but the containing type has no special rights over the nested type's members. Reading a nested type's `private` field from the outer class is CS0122. Make the member `internal` or `public` on the nested type, which is still hidden if the nested type itself is `private`.

  • Says a class with no modifier is public to any referencing project.
  • Says class members default to internal, like top-level types.
  • Thinks interface members default to private without a modifier.
  • Believes a top-level class can be declared private to hide it in a file.
  • Thinks a public method on an internal class is callable from other assemblies.
open as a page

In C#, how do the : this(...) and : base(...) constructor initializers chain constructors, and which mistakes does the compiler reject?

level: juniorimportance: must knowfreq 66%

basics

~20 s

: this(...) forwards to another constructor of the same class; : base(...) picks a base-class constructor. Without either, C# inserts base(), so a base with no parameterless constructor gives CS7036. Field initializers run once, in the constructor that calls base.

open as a page

In C#, how do you declare an extension method like WordCount on string, and what does the compiler turn text.WordCount() into?

level: juniorimportance: must knowfreq 72%

basics

~20 s

Declare a static method in a top-level, non-generic static class and put this before its first parameter. The compiler rewrites text.WordCount() into the static call StringExtensions.WordCount(text), and finds it only when that class's namespace is in scope.

open as a page

In C#, what is the difference between override and new on a derived Send method, and which Send runs through a base-typed variable?

level: juniorimportance: must knowfreq 80%

basics

~20 s

override replaces the implementation of the base virtual Send, so a Notification-typed variable still runs the derived code. new only hides the name: through a Notification variable the base Send runs, through an EmailNotification variable the hiding one.

open as a page

In C#, what is the difference between implementing an interface member implicitly and explicitly, and how can callers reach each one?

level: juniorimportance: must knowfreq 68%

basics

~20 s

An implicit implementation is a public member matching the interface member, callable through the class or the interface. An explicit one, named like IPaymentGateway.Close with no access modifier, is callable only through an interface-typed reference.

open as a page

In C#, why should a class expose GuestName as a property rather than a public field, even when the property only stores a value?

level: juniorimportance: must knowfreq 75%

basics

~20 s

A property is a pair of accessor methods over a backing field, so validation, computed values or different storage can come later without touching callers; turning a public field into a property later breaks already-compiled callers.

open as a page

In C#, when new creates a derived class, in what order do the derived and base field initializers and the two constructor bodies run?

level: middleimportance: must knowfreq 72%

basics

~20 s

Derived field initializers run first, then the base(...) arguments are evaluated, then the base class's field initializers, the base constructor body and finally the derived constructor body. An object initializer, if present, runs after all of them.

open as a page

In C#, when a type has an instance method and an imported extension method shares its name, which one does a call bind to, and why?

level: middleimportance: must knowfreq 58%

basics

~20 s

An applicable instance method always wins, even when the extension's parameters match better: the compiler searches extensions only when instance lookup finds nothing applicable. The choice is fixed when the caller compiles, so an extension never overrides.

open as a page

Now that C# interfaces can carry default method bodies, what can a C# abstract class still do that an interface cannot?

level: middleimportance: must knowfreq 78%

basics

~20 s

An abstract class can hold instance fields, run a constructor for every subclass, and pass on members that subclasses call by name. Interfaces cannot, but a type may implement many interfaces and derive from only one class.

open as a page

In C#, when does an object initializer such as new FulfilmentOrder("ORD-7") { Quantity = 3 } assign its members, relative to the constructor?

level: juniorimportance: should knowfreq 58%

basics

~20 s

After the constructor returns. The compiler builds the object into a hidden temporary, assigns the members in textual order, and stores the reference in your variable only after every assignment succeeds, so the constructor sees default values.

open as a page

In C#, how do you declare an indexer so booking[night] reads and writes a nightly rate, and how does it differ from a property?

level: juniorimportance: should knowfreq 40%

basics

~10 s

Declare it with this and a parameter list: public decimal this[DateOnly night] { get ...; set ...; }. It is a property whose accessors take parameters: instance-only, overloadable by parameter types and never auto-implemented.

open as a page

Why does a public C# method that returns an internal type fail with CS0050, and what are the ways to fix it?

level: middleimportance: should knowfreq 40%

basics

~20 s

C# requires every type in a member's signature to be at least as accessible as the member itself. A public method returning an internal type would hand outsiders a type they cannot name, so the compiler rejects it with CS0050.

open as a page

In C#, how do protected internal and private protected differ, and which code in another assembly can reach each member?

level: middleimportance: should knowfreq 52%

basics

~20 s

protected internal means any code in the same assembly or a derived class anywhere. private protected (C# 7.2) means only derived classes in the same assembly, so another assembly's code never reaches it unless that assembly is a friend.

open as a page

In C#, when does a class's static constructor run, how many times, and what happens to the type when it throws?

level: middleimportance: should knowfreq 52%

basics

~20 s

The runtime runs a static constructor at most once, just before the first instance is created or a static member is referenced. If it throws, the type stays uninitialized and every later use throws TypeInitializationException wrapping the original exception.

open as a page

In C#, why does calling a string extension method such as IsNullOrBlank on a null reference not throw NullReferenceException at the call?

level: middleimportance: should knowfreq 45%

basics

~20 s

An extension call compiles to a static call that passes the receiver as an ordinary argument, so a null receiver simply arrives as null. Nothing throws at the call; the method body decides whether to accept null or throw.

open as a page

In C#, what do abstract and sealed enforce on a class and on an override, and when can base.Method() be called?

level: middleimportance: should knowfreq 62%

basics

~20 s

An abstract class cannot be instantiated and its abstract members must be overridden by concrete subclasses. A sealed class cannot be derived from, and sealed override stops further overriding. base.Method() calls the base implementation, unless that member is abstract.

open as a page

In C#, a class implements IPaymentGateway and IAuditLog, both declaring void Close(); what does one public Close do, and how do you split them?

level: middleimportance: should knowfreq 45%

basics

~20 s

One public void Close() implements both interface members, so either interface reference runs the same body. To give IAuditLog its own behaviour, implement void IAuditLog.Close() explicitly; the public Close then serves IPaymentGateway and class-typed callers.

open as a page

In C# 14, how does the field keyword let a Nights property validate its setter without a declared backing field, and what skips that validation?

level: middleimportance: should knowfreq 25%

basics

~20 s

In C# 14, field names the compiler-synthesized backing field inside a property accessor, so get; stays automatic while set validates and assigns field. A property initializer skips the setter and writes the backing field directly.

open as a page

In C#, when can a HotelBooking's GuestName be assigned if it has an init accessor, a private set accessor, or is a readonly field?

level: middleimportance: should knowfreq 60%

basics

~20 s

An init accessor is assignable only during creation: an object initializer, a constructor or another init accessor. A private setter works any time, but only inside the class. A readonly field takes its initializer, a constructor or an init accessor.

open as a page

A C# test project must call internal helpers in a strong-named class library; how do you grant access with InternalsVisibleTo, and what can still fail?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Add [assembly: InternalsVisibleTo("Billing.Core.Tests")] to the library, or an InternalsVisibleTo item in its project. A strong-named library must name the test assembly with its full public key (CS1726), and the test assembly must be signed with that key (CS0281).

open as a page

A C# order-fulfilment service rewritten with a C# 12 primary constructor warns CS9124 on its feeCents parameter; what did the compiler generate, and what breaks?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Because feeCents is read in methods, the compiler captures it in a hidden, mutable field, while the FeeCents property initializer copies it into a second field. CS9124 warns about the two copies, which diverge once a method assigns the parameter.

open as a page

After a C# file imports a second namespace that also defines ToSlug(this string), the build fails with CS0121; how does extension lookup by namespace scope explain it, and how do you fix it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Extension lookup searches namespace scopes innermost first and stops at the first with applicable candidates, so two equally good ToSlug methods imported at one level give CS0121. Fix it with a static call, an inner-scope using, or one fewer using.

open as a page

A C# Notification base constructor calls a virtual BuildHeader that SmsNotification overrides; why does the override see a null phone number, and how do you fix it?

level: seniorimportance: should knowfreq 48%

basics

~20 s

Virtual dispatch already reaches SmsNotification's override while Notification's constructor runs, but SmsNotification's constructor body has not run yet, so fields it assigns are still null. Pass the data to the base constructor or build the header after construction.

open as a page

In C#, GatewaySession implements IGatewaySession.Close with a non-virtual public method; why does a subclass's new Close not run through an IGatewaySession reference?

level: seniorimportance: should knowfreq 30%

basics

~20 s

GatewaySession's interface mapping sends Close to GatewaySession.Close, and subclasses inherit that mapping. A new method hides only for class-typed callers; re-listing the interface on the subclass, or a virtual base method, changes what interface callers run.

open as a page

In C#, IPaymentGateway gains a Refund method with a default body; why does adapter.Refund(...) on a LegacyCardAdapter variable fail to compile, and what runs through the interface?

level: seniorimportance: should knowfreq 40%

basics

~20 s

A class does not inherit an interface's default method, so the class-typed call is CS1061. Through IPaymentGateway the runtime runs the most specific implementation: the class's own Refund, else a derived interface's override, else the default body.

open as a page

In C#, why does new HotelBooking("Ana Ruiz") still fail with CS9035 when that constructor assigns the required GuestName, and what does [SetsRequiredMembers] change?

level: seniorimportance: should knowfreq 40%

basics

~20 s

The required check runs at each creation site and never looks inside constructor bodies, so callers must still set every required member. [SetsRequiredMembers] declares that the constructor sets them all and switches the check off, without verifying it.

open as a page

As the lead setting a C# solution's coding standard, would you make types internal by default and let tests reach them through InternalsVisibleTo?

level: principalimportance: should knowfreq 30%

basics

~20 s

Usually yes for types: internal by default keeps a library's public surface small and refactoring cheap. Granting InternalsVisibleTo to test assemblies only is a reasonable trade, but it couples tests to internals and silences some unused-type analyzers.

open as a page

Should a C# team adopt primary constructors for its service classes' dependencies, and what house rule and enforcement would you put around captured parameters?

level: principalimportance: should knowfreq 32%

basics

~20 s

Adopt them where they remove boilerplate, but pick one storage rule: either allow captured parameters and forbid assigning them, or require each parameter to initialize a private readonly field. Enforce it with CS9124 and CS9107 as errors and IDE0290's settings.

open as a page

Should a C# team seal classes by default or leave them open for inheritance, and how would you enforce the choice?

level: principalimportance: should knowfreq 35%

basics

~20 s

Seal application and internal classes by default, because unsealing later is not a breaking change while sealing a published class later breaks every subclass. For public library types decide per type, and enforce internal sealing with CA1852.

open as a page

Your shared C# package publishes IPaymentGateway, implemented by three teams; how do you add a Refund operation: a default interface method, a new interface, or an abstract base class?

level: principalimportance: should knowfreq 35%

basics

~20 s

Adding an abstract member breaks implementers: CS0535 on recompile, TypeLoadException for old builds. A default method fits when a real default exists, a derived IRefundableGateway fits an optional capability, and an abstract base class costs each team its base-class slot.

open as a page

showing 1–30 of 33