C# Partial Class

C# Code Snippets Partial Classes
Share:

About

In this code snippet, we will found out what partial classes are in C#.

If a class is marked with the partial keyword a class with the same name can be declared in another file. Both of the classes will now share everything between them and act as one. The partial keyword basically allows us to split up a class into different parts that can be put into different files.

Let’s look at the code below to see how to make a partial class.

Code:

First file

using System;

namespace PartialClass
{
    class Program
    {
        static void Main(string[] args)
        {
            MyPartialClass MPC = new MyPartialClass(10);

            MPC.myMethod();

            Console.ReadLine();

            //As you can see we were able to call the method from the other file just as if it was in this file. 
        }
    }

    //The partial keyword is used so a class can be split into more physcial files.

    public partial class MyPartialClass
    {
        public MyPartialClass(int number)
        {
            MyProperty = number;
        }
        public int MyProperty { get; set; }
    } 
}

Second file

using System;

namespace PartialClass
{
    public partial class MyPartialClass
    {
        public void myMethod()
        {
            Console.WriteLine(MyProperty);
        }
    }
}

Example in Visual Studio

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger