Simple example of partial method

Partial methods allow developpers to reserve a name for a mthod that can optionally be implemented by consumers of their code, they are declared inside partial classes:

The MyPartialMethod is not implemented in this first declaration for MyPartialClass. This is an invitation to the developer to implement this method if desired in a second declaration for MyPartialClass. The invitation is called a defining partial method declaration. (Charlie Calvert)

Partial methods

must be declared inside a partial class
must not return a type -declaration "partial void"
cannot be marked as extern
cannot be marked a static
can be marked as generic
can have ref parameter but not out paremeters
cannot be referenced as delegate until they are implemented
cannot have access modifiers as public , private , intern ( are implicitely marked as private)

 

using System;
using System.IO;

namespace AbstractMethod
{
    public partial class MyPartialClass
    {
        partial void MyPartialMethod();

        public void WriteFile(string fileName, string contents)
        {
            TextWriter textWriter = new StreamWriter(fileName);
            textWriter.Write(contents);
            textWriter.Close();  

            MyPartialMethod();
        }       
    }

    public partial class MyPartialClass
    {
        partial void MyPartialMethod()
        {
            Console.WriteLine("File written");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyPartialClass m = new MyPartialClass();
            m.WriteFile(@".\data.txt", "passaddhi");
        }
    }
}

Publicités
Cet article a été publié dans DotNet. Ajoutez ce permalien à vos favoris.

Laisser un commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l'aide de votre compte WordPress.com. Déconnexion / Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion / Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion / Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion / Changer )

Connexion à %s