Saturday, 19 May 2012

Partial classes in C#

Partial Classes in C#--> Partially define some methods in one file , add new methods to a class in another file, as shown below. it can be applied to class, struct or interface.

keyword: partial

file1.cs

namespace ConsoleApplication5
{
    public partial class Person
    {
        int Age;
        string Name;
        public Person(int age, string n)
        {
            Age = age;
            Name = n;
        }

        public bool isEligible() { if (Age > 18) return true; else return false; }
    }
}
file2.cs
namespace ConsoleApplication5
{
     public partial class Person
    {
         int pin;
         public Person(int p)
         {
             pin = p;
         }
         public bool isPinValid()
         {
             if (pin >100000 && pin > 999999) return false;
             else return true;
         }
     }
}

Program.cs(application Main file)

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person(20,"sitapati");
            Console.WriteLine(p.isEligible());
        }
    }
}

No comments:

Post a Comment