Friday 6 September 2019

Partial class in c sharp.



Coding for a single class can be split and stored more than one source file.
Then the class is called as partial class .
This is useful  when you create a asp.net project and coding will of a single class can be split and written different parts of class in .aspx file and .cs file.
The different parts  of a class in separate file must have same name. the keyword class be preceded by keyword partial. But the source file name may be different.
When the program is compiled, different parts of a class available in difffrent files get combined and become a single class.

Class A1.cs

namespace ConsoleApp2
{
      partial   class A
    {
      public   static void A1()
        {
            Console.WriteLine("A1 method");
        }
    }
}
Class A2.cs
namespace ConsoleApp2
{
   partial class A
    {
       public  static void A2()
        {
            Console.WriteLine("A2 method");
        }
    }
}

Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            // The code provided will print ‘Hello World’ to the console.
            // Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
            A.A1();
            A.A2();
            Console.ReadKey();

            // Go to http://aka.ms/dotnet-get-started-console to continue learning how to build a console app!
        }
    }
}

Output:
A1 method
A2 method
Restrictions of partial class:
All the partial class parts should be in same namespace and assembly.
All the parts must have the same accessibility.
If any part of a class is sealed then the whole class becomes sealed.
If any part of a class abstract then the whole class becomes abstract.

One of the main advantage of partial class is when diffferent programmer work on different parts of a same class and it enables them to split the code and write in separate files .
Muthu karthikeyan,Madurai.


To learn Dotnet in Madurai:
contact:91 9629329142

No comments:

Post a Comment