Proposal: Scoped Type Declaration Syntax for class, record, struct, and interface #9960
-
Scoped Type Declaration SyntaxSummaryAllow type declarations (class, record, struct, interface) to use file-scoped syntax similar to namespaces, reducing nesting and improving readability. Only one scoped type per file, no nesting allowed. MotivationFollowing the success of file-scoped namespaces, developers frequently work with simple types that don't require extensive nesting. A scoped type syntax would:
Proposed SyntaxClassesnamespace MyNamespace;
public class PersonDto;
public string Name { get; set; }
public int Age { get; set; }
public DateTime BirthDate { get; set; }Recordsnamespace MyNamespace;
public record PersonRecord;
public string Name { get; init; }
public int Age { get; init; }Structsnamespace MyNamespace;
public struct Point;
public double X { get; set; }
public double Y { get; set; }Interfacesnamespace MyNamespace;
public interface IPersonRepository;
Task<Person> GetByIdAsync(int id);
Task SaveAsync(Person entity);
Task DeleteAsync(int id);ExamplesBefore: namespace MyNamespace
{
public class PersonDto
{
public string Name { get; set; }
public int Age { get; set; }
}
}After (PersonDto.cs): namespace MyNamespace;
public class PersonDto;
public string Name { get; set; }
public int Age { get; set; }Before: namespace MyNamespace
{
public interface IPersonService
{
Task<PersonDto> GetPersonAsync(int id);
Task SavePersonAsync(PersonDto person);
}
}After (IPersonService.cs): namespace MyNamespace;
public interface IPersonService;
Task<PersonDto> GetPersonAsync(int id);
Task SavePersonAsync(PersonDto person);Rules and Constraints
Benefits
Migration ExampleLegacy Style (multiple types per file): namespace MyNamespace
{
public class PersonDto
{
public string Name { get; set; }
}
public class AddressDto
{
public string Street { get; set; }
}
}Modern Style (separate files with scoped syntax): PersonDto.cs: namespace MyNamespace;
public class PersonDto;
public string Name { get; set; }AddressDto.cs: namespace MyNamespace;
public class AddressDto;
public string Street { get; set; }Alternatives Considered
|
Beta Was this translation helpful? Give feedback.
Answered by
HaloFour
Jan 27, 2026
Replies: 1 comment 1 reply
-
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
333fred
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See: #5785 and #928