C# offers a functionality that allows developers to write source code in distinct files and then compile them together as a unified whole. This capability, known as partial types, was introduced in C# 2.0. The keyword 'partial' is employed to define partial types.
It enables the creation of partial class, interface, struct, and method across multiple source files, which are merged during the compilation process.
Here, we are defining a partial class in the Customer.cs file that contains the depositeAmount method and a withdraw method in the Customer2.cs file. These methods are stored in distinct files and merged during the compilation process.
C# Partial Class Example
// Customer.cs
using System;
namespace CSharpFeatures
{
partial class Customer
{
// Deposit function
public void depositAmount(int d_amount)
{
amount += d_amount;
Console.WriteLine(d_amount+" amount is deposited");
Console.WriteLine("Available balance is: "+amount);
}
}
}
// Customer2.cs
using System;
namespace CSharpFeatures
{
partial class Customer
{
private int amount;
public int Amount { get => amount; set => amount = value; }
// Withdraw function
public void withdraw(int w_amount)
{
amount -= w_amount;
Console.WriteLine(w_amount+" is withdrawn");
Console.WriteLine("Available balance is: "+amount);
}
}
}
using System;
namespace CSharpFeatures
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
customer.Amount = 2000;
Console.WriteLine("Current balance is: "+ customer.Amount);
customer.depositAmount(1000);
// Accessing seperate file function
customer.withdraw(500);
}
}
}
Output:
Current balance is: 2000
amount is deposited
Available balance is: 3000
500 is withdrawn
Available balance is: 2500