A.Pissicat A.Pissicat - 9 days ago 6
C# Question

Add method to a class from another project

Is it possible to add a method to a class from another project?

I have a class:

namespace ProjectLibrary
{
public ClassA
{
// some methods
}
}


I want to add a method to save my object in a file, but I don't want to add this method in my project
ProjectLibrary
because I don't want to add reference to System.IO (I want to use this project for android application and PC application).

Is there a possibility to add a method
SaveToFile()
usable only in another project? Or create an abstract method in ClassA but define it in other project.

Like this :

using ProjectLibrary;
namespace ProjectOnPC
{
void methodExample()
{
ClassA obj = new ClassA();
// do sommething
obj.SaveToFile();// => available only in namespace ProjectOnPC
}
}


Thank you for help

Answer

The thing You are looking for is called Extension method:

Code for base class:

namespace ProjectLibrary
{
    public ClassA
    {
        // some methods
    }
}

Extension method:

using ProjectLibrary;
namespace ProjectOnPC
{
    void SaveToFile(this ClassA Obj, string Path)
    {
        //Implementation of saving Obj to Path
    }
}

Calling in Your program:

using ProjectLibrary;
using ProjectOnPc; //if You won't include this, You cannot use ext. method

public void Main(string[] args)
{
    ClassA mObj = new ClassA();
    mObj.SaveToFile("c:\\MyFile.xml");
}
Comments