Partial class in C# (partial modifier)

This post was originally posted at https://agrawalsuneet.github.io/blogs/partial-class-in-csharp-partial-modifier/ and reposted on Medium on 30th Mar 2020.

What is a Partial class?

//Someclass1.cs
public partial class SomeClass
{
// code
private void function1(){ }}//Someclass2.cs
public partial class SomeClass
{
// code
private void function2(){ }}//final compiled code
public class SomeClass
{
private void function1(){ }
private void function2(){ }}

Requirements of Partial modifier

  • A partial modifier can be added to a class or an interface or a struct.
  • Every part of the partial class definition should be in the same assembly and namespace, but we can use different source file name.
  • All the parts must have the same accessibility for example public or private, etc.
  • If any part is declared abstract, sealed or base type then the whole class is declared of the same type.
  • The partial modifier can only appear immediately before the keywords class, struct, or interface.
  • Nested partial types are allowed.
  • Different parts can have different base types like implementing different interfaces and the final class will inherit all the base types.

Advantages of Partial class

  • With the concept of partial classes, we can better the code structure like by separating business logic and UI implementation within the same class.
  • Can avoid conflicts if multiple developers working on the same class or interface or struct.
  • When we working with automatically generated source, code can be added to the class without having to recreate the source file. For example, Visual Studio separates HTML code for the UI and server-side code into two separate files: .aspx and .cs files.

--

--

--

https://agrawalsuneet.github.io/

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Notes from 25/3–31/3

Using environment variables to control a dynamic Airflow DAG

Google Play app description

Why we do the Cloud Budgeting

Using MongoDB with Jaguar.dart

What I Learned at Work this Week: More Difficult SQL Parsing

Day -1 DevOps

What are we up to now? Here are our current projects

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Suneet Agrawal

Suneet Agrawal

https://agrawalsuneet.github.io/

More from Medium

Better unit tests in C# with xUnit

C# Nullable Reference Types

Csharp: Everything You Need To Know About IT