C# code organization and attributes
This page covers the features that decide how C# source is laid out and how code carries metadata. The first four sections are about structure: where the program starts, how much nesting a file needs, where using directives live, and how a single .cs file can run with no project at all. The last two are about attributes, the declarative metadata that frameworks, analyzers, serializers and source generators read, including the C# 11 generic form.
The samples share one invented app, OrdersPortal. The first three features are shown together in a small console project; the rest are complete file-based apps you run with dotnet run sample.cs. All outputs were produced with .NET SDK 10.0.115 (C# 14).
Features on this page
Section titled “Features on this page”| Feature | Version | Use it when |
|---|---|---|
| Top-level statements | C# 9 | Writing a program’s entry point without a Program class and Main. |
| File-scoped namespaces | C# 10 | A file declares one namespace (almost always). |
| Global usings | C# 10 | A namespace or alias is needed in most files of a project. |
| File-based app directives | C# 14 with .NET 10 SDK | A script, tool or demo fits in one .cs file. |
| Attributes | C# 1 | Tools or frameworks need declarative metadata on code. |
| Generic attributes | C# 11 | An attribute takes a type argument that should be checked at compile time. |
Top-level statements
Section titled “Top-level statements”Introduced in C# 9 (.NET 5). One file in a project may contain statements directly at the top level, before any type declarations. The compiler wraps them in a generated Program class and entry point. You still get args, you can await (the generated Main becomes async), and you can return an integer exit code. Functions declared there are local functions. Since .NET 6, the dotnet new console template uses this style, and minimal ASP.NET Core hosts use it for Program.cs. The project below also demonstrates the next two sections.
// Top-level statements: this file is the entry point.if (args.Length == 0){ Console.Error.WriteLine("usage: OrdersPortal.Cli <total>"); return 2; // becomes the process exit code}
var total = Money.Parse(args[0], CultureInfo.InvariantCulture);var order = new Order("ORD-1201", total);await Task.Delay(10); // await makes the generated Main asyncConsole.WriteLine($"{order.Id}: {order.Total} (rounded {order.RoundedTotal})");Console.WriteLine(Describe(order));return 0;
static string Describe(Order o) => o.Total > 100 ? "priority" : "standard"; // local functionRun it with dotnet run -- 149.5, then with no argument:
ORD-1201: 149.5 (rounded 150)priority(exit code 0)
usage: OrdersPortal.Cli <total>(exit code 2)Pitfalls:
- Only one file per project can have top-level statements, and type declarations in that file must come after the statements.
- Top-level locals are not fields. Other classes cannot see them, and helpers in that file capture them unless marked
static. - Tests that need the entry point type can reference
Program, but it is generated asinternalunless you addpublic partial class Program;.
File-scoped namespaces
Section titled “File-scoped namespaces”Introduced in C# 10 (.NET 6). namespace OrdersPortal.Models; followed by a semicolon applies that namespace to everything in the file, so the types are not wrapped in braces and every line loses one level of indentation. The compiled result is identical to a block-scoped namespace. Because nearly every file declares exactly one namespace, this has become the default style in new templates; the csharp_style_namespace_declarations = file_scoped editorconfig setting and IDE0161 enforce it.
namespace OrdersPortal.Models;
public sealed record Order(string Id, Money Total){ public Money RoundedTotal => Round(Total, 0, MidpointRounding.AwayFromZero);}Money and Round come from the global usings in the next section; the output is shown above.
Pitfalls:
- A file can contain only one file-scoped namespace, and it cannot be combined with block-scoped namespaces in the same file.
- The declaration must come before any type declarations;
usingdirectives can appear above it.
Global usings
Section titled “Global usings”Introduced in C# 10 (.NET 6). A global using directive applies to every file in the compilation, so common imports are written once. It supports the same forms as a normal using: namespaces, global using static System.Math; and aliases. Since C# 12 an alias can name any type, including decimal or a tuple, as Money = decimal does here. SDK-style projects with <ImplicitUsings>enable</ImplicitUsings> also generate global usings for System, System.Linq, System.Threading.Tasks and others, and <Using Include="..." /> items in the project file add more. Keep project-specific imports in one GlobalUsings.cs so they are easy to find.
global using OrdersPortal.Models;global using static System.Math;global using Money = decimal;<!-- OrdersPortal.Cli.csproj --><Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net10.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <Using Include="System.Globalization" /> </ItemGroup></Project>With these three files the program in the first section compiles without a single using line in Program.cs or Order.cs.
Pitfalls:
- Global usings bring every type in a namespace into every file, which can create ambiguous names (for example two
Ordertypes). Keep the list short. - Global usings must appear before all non-global usings and namespace declarations in their file.
File-based app directives
Section titled “File-based app directives”Introduced with C# 14 and the .NET 10 SDK (November 2025). dotnet run app.cs builds and runs a single C# file with no .csproj. The C# compiler ignores lines starting with #! and #:; the SDK reads them instead. #!/usr/bin/env dotnet on the first line lets Unix shells execute the file directly after chmod +x. #:package Name@Version adds a NuGet reference, #:project references a project, #:property Name=Value sets an MSBuild property, and #:sdk changes the SDK (for example Microsoft.NET.Sdk.Web). The .NET 11 SDK and SDK 10.0.300 add #:include for splitting an app across files. File-based apps publish with Native AOT by default, so reflection-heavy code may need #:property PublishAot=false. When the app grows, dotnet project convert app.cs turns it into a regular project.
#!/usr/bin/env dotnet#:property InvariantGlobalization=true#:property PublishAot=false
// A file-based app: no .csproj, configured by the #: directives above.var orders = new[] { ("ORD-1301", 42.00m), ("ORD-1302", 180.25m) };foreach (var (id, total) in orders) Console.WriteLine($"{id,-10}{total,10:N2}");Console.WriteLine($"Args: {(args.Length == 0 ? "(none)" : string.Join(' ', args))}");Running dotnet run order-report.cs -- --since 2026-11-01 prints:
ORD-1301 42.00ORD-1302 180.25Args: --since 2026-11-01Pitfalls:
- Directives must be at the top of the file, before any code.
- A
.csfile inside a folder that also has a.csprojgets confusing quickly; keep file-based apps in their own folder. - Use exact package versions (
@1.2.3) rather than@*for anything you share, so the script does not change behavior when a new package ships.
Attributes
Section titled “Attributes”Introduced in C# 1 (.NET Framework 1.0). An attribute is a class deriving from System.Attribute that you attach to an assembly, type, member, parameter or return value with square brackets. The metadata does nothing on its own: the compiler ([Obsolete], [CallerMemberName]), analyzers, the runtime ([Serializable], [DllImport]), frameworks through reflection ([Required], [Route]) and source generators ([JsonSerializable], [LoggerMessage]) read it and act. When you write your own attribute, [AttributeUsage] controls valid targets, whether it may repeat, and whether it is inherited. The Attribute suffix may be omitted at the use site, and arguments must be compile-time constants, typeof expressions or arrays of those.
#:property PublishAot=false// Reflection-based validation is not trim-safe; without this line the build prints IL2026 warnings.using System.ComponentModel.DataAnnotations;using System.Reflection;
var input = new CreateOrderRequest { CustomerEmail = "not-an-email", Quantity = 0 };var results = new List<ValidationResult>();bool ok = Validator.TryValidateObject(input, new ValidationContext(input), results, validateAllProperties: true);Console.WriteLine($"Valid: {ok}");foreach (var r in results) Console.WriteLine($" - {r.ErrorMessage}");
var audit = typeof(CreateOrderRequest).GetCustomAttribute<AuditedAttribute>();Console.WriteLine($"Audited as '{audit?.Category}'");
#pragma warning disable CS0618LegacyPricing.Calculate();#pragma warning restore CS0618
[Audited("orders")]public sealed class CreateOrderRequest{ [Required, EmailAddress] public string? CustomerEmail { get; set; }
[Range(1, 500, ErrorMessage = "Quantity must be between 1 and 500.")] public int Quantity { get; set; }}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]public sealed class AuditedAttribute(string category) : Attribute{ public string Category { get; } = category;}
public static class LegacyPricing{ [Obsolete("Use PricingService.Calculate instead.")] public static void Calculate() => Console.WriteLine("legacy pricing ran");}Output:
Valid: False - The CustomerEmail field is not a valid e-mail address. - Quantity must be between 1 and 500.Audited as 'orders'legacy pricing ranPitfalls:
- Reflection-based attribute reading is slow on first use and can break under trimming or Native AOT; prefer source generators where the framework offers them.
- Attribute arguments must be constants, so you cannot pass a
decimal, aDateTimeor an instance. [Obsolete]only warns by default; passtrueas the second argument to make use an error.
Generic attributes
Section titled “Generic attributes”Introduced in C# 11 (.NET 7). A class that derives from Attribute may now be generic, so [ValidatedBy<CreateOrderValidator>] replaces [ValidatedBy(typeof(CreateOrderValidator))]. The difference is that the type argument goes through normal generic constraints: with where TValidator : IValidator, new(), passing a type that is not a validator is a compile error instead of a runtime failure. Reading the attribute through reflection needs either the closed type or a non-generic base class, as in the sample. Type arguments must be representable in metadata, so dynamic, nullable reference annotations such as string? and tuple element names are rejected (CS8970).
using System.Reflection;
foreach (var type in new[] { typeof(CreateOrderRequest), typeof(CancelOrderRequest) }){ var attr = type.GetCustomAttribute<ValidatedByAttribute>(); Console.WriteLine($"{type.Name} -> {attr?.ValidatorType.Name ?? "(none)"}");}
[ValidatedBy<CreateOrderValidator>] // C# 11: type checked at compile timepublic sealed class CreateOrderRequest;
[ValidatedBy<CancelOrderValidator>]public sealed class CancelOrderRequest;
public interface IValidator;public sealed class CreateOrderValidator : IValidator;public sealed class CancelOrderValidator : IValidator;
public abstract class ValidatedByAttribute : Attribute{ public abstract Type ValidatorType { get; }}
[AttributeUsage(AttributeTargets.Class)]public sealed class ValidatedByAttribute<TValidator> : ValidatedByAttribute where TValidator : IValidator, new(){ public override Type ValidatorType => typeof(TValidator);}Output:
CreateOrderRequest -> CreateOrderValidatorCancelOrderRequest -> CancelOrderValidatorPitfalls:
GetCustomAttribute<ValidatedByAttribute<T>>()needs a concreteT. To find “any” instance, give the generic attribute a non-generic base class or inspectGetGenericTypeDefinition().- The type argument must be fully known at the use site: inside a generic class,
[ValidatedBy<T>]is error CS8968 because attribute type arguments cannot use type parameters.
Choosing between them
Section titled “Choosing between them”- New console app or service host: top-level statements, file-scoped namespaces and implicit usings are the default; keep project-specific imports in one
GlobalUsings.cs. - Throwaway script, sample or CI helper: a file-based app. Anything with several files, tests or a team: a project (convert with
dotnet project convert). - Metadata read by a framework: attributes. An attribute that only exists to carry a
Type: make it generic and constrain the type.
Interview questions
Section titled “Interview questions”What does the compiler generate for top-level statements?
A Program class with a static entry-point method. Its signature depends on the code: it returns Task or Task<int> if the statements use await, int if they return a value, and it takes string[] args. Methods declared in the file become local functions of that entry point.
Are global usings a performance or runtime feature? No. They only affect name lookup at compile time; the generated IL is the same as with per-file usings. Their cost is readability and the risk of ambiguous names.
How does a file-based app differ from a C# script (.csx)?
A file-based app is a normal C# program compiled by the SDK, with an implicit project generated from the #: directives, so it supports all language features, NuGet packages, publishing and Native AOT. It can be converted to a project at any time.
Why would you choose [ValidatedBy<T>] over [ValidatedBy(typeof(T))]?
The generic form lets constraints check the type at compile time and removes a cast or Activator call when the attribute is consumed. Both store the same kind of metadata.
Senior scenario: OrdersPortal has 400 files with using lists of 15 lines and three different Money types imported in different places. How would you clean this up safely?
Enable implicit usings, then move only the namespaces used in most files into one GlobalUsings.cs; leave rarely used or conflicting namespaces local. Resolve the three Money types first (rename or alias them) so global imports cannot create ambiguity errors. Apply file-scoped namespaces and IDE0005 (unnecessary usings) with dotnet format in a single mechanical commit, separate from behavior changes, so the review is a diff of whitespace and imports only.
Related pages
Section titled “Related pages”- Methods, lambdas and extensions: local functions used by top-level programs.
- Types, records and unions: the records used in these samples.
- Async and await: async entry points.
- C# 14 release guide, C# 12 release guide and C# version history.