Tuesday, 21 August 2018

C#: Partial Classes

By using partial classes feature, we can split the definition of a class, interface (or) struct over more than one file. For example you can define a partial class 'Employee' in multiple files, each file contains a section of the type or method definition, and all parts are combined when the application is compiled.

How to define a partial class?
You can define a partial class by using 'partial' keyword.

EmployeeModel.cs
using System;

namespace HelloWorld
{

    public partial class Employee
    {
        private int id;
        private String firstName;
        private String lastName;

        public int getId()
        {
            return id;
        }

        public void setId(int id)
        {
            this.id = id;
        }

        public String getFirstName()
        {
            return firstName;
        }

        public void setFirstName(String firstName)
        {
            this.firstName = firstName;
        }

        public String getLastName()
        {
            return lastName;
        }

        public void setLastName(String lastName)
        {
            this.lastName = lastName;
        }

    }

}

EmployeeUtil.cs
using System;

namespace HelloWorld
{
    public partial class Employee
    {

        public String getFullName()
        {
            return firstName + " " + lastName;
        }

        public void setFirstAndLastNames(String firstName, String lastName)
        {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public override string ToString()
        {
            return "id : " + id + ", firstName : " + firstName + ", lastName : " + lastName;
        }

    }
}

Program.cs
using System;
using HelloWorld;

class Program
{
    static void Main()
    {
        Employee emp = new Employee();

        emp.setId(123);
        emp.setFirstAndLastNames("Hari Krishna", "Gurram");

        String firstName = emp.getFirstName();
        String lastName = emp.getLastName();
        int id = emp.getId();

        Console.WriteLine("firstName : {0} lastName : {1} id : {2}", firstName, lastName, id);
    }

}


Output
firstName : Hari Krishna lastName : Gurram id : 123

Points to Remember
a.   If any part is declared abstract, then the whole type is considered abstract.
b.   If any part is declared sealed, then the whole type is considered sealed.
c.   If any part declares a base type, then the whole type inherits that class.






Previous                                                 Next                                                 Home

No comments:

Post a Comment