Partial Class in C#

In this article we will discuss about how to define and use the Partial Class in C#.
  • 2872

Partial keyword is used when we want to make the Class definition into different file within same namespace. The partial keyword makes it easy to make readability of the class code easier. We can read it into different file. It means we can physically separate a class in multiple files. These kinds of Classes are spread out among several files under same namespace.

It is useful if the length of the program is going to be increase then we can divide the Class in different files to minimize the length of the program and to make understandable and we have to use the Partial keyword to make a Class Partial while declaring the Class.

The following program to make a Class Partial in C# is as follows:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace parclass

{

    class Program

    {

        static void Main(string[] args)

        {

            student obj = new student();

            obj.show();

            obj.display();

            Console.ReadLine();

        }

    }

    public partial class student

    {

        public void show()

        {

            Console.WriteLine("Welcome");

        }

    }

}

Now add a Class file to do this follow the following Steps to make the Class definition in separate files under same namespace:

  1. Go to solution Explorer.

  2. Right Click on it and select add option.

  3. Then select New Item and select Class template.

  4. Then change the name of the class i.e. in place of Class1 just give student name to the class.

  5. Then Click on Add button.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace parclass

{

    public partial class student

    {

        public void display()

        {

            Console.WriteLine("hi");

        }

    }

}

Output:

Image8.jpg

In the above program we can see that under same namespace .i.e. parclass we have make two separate files of a Class .i.e. student and can access functionality of both files combinedly.

Further Readings
 
You may also want to read these related articles.

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2019 DotNetHeaven. All rights reserved.