1

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

I have a class:

namespace ProjectLibrary
{
    public class 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 something
        obj.SaveToFile();// => available only in namespace ProjectOnPC
    }
}

Thank you for help

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
A.Pissicat
  • 3,023
  • 4
  • 38
  • 93

3 Answers3

3

You can use extension methods.

Example:

namespace ProjectOnPC
{
    public static void SaveToFile(this Class myClass)
    {
      //Save to file.
    }
}
Carra
  • 17,808
  • 7
  • 62
  • 75
2

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");
}
Community
  • 1
  • 1
Tatranskymedved
  • 4,194
  • 3
  • 21
  • 47
1

You can create an extension method for this purpose.

Here's an example.
In your ProjectOnPc namespace create a class like this:

public static class ClassAExtension
{
    public static void SaveToFile(this ClassA obj)
    {
        // write your saving logic here.
        // obj will represent your current instance of ClassA on which you're invoking the method.
        SaveObject(obj).
    }
}

You can learn more about extension methods here:
https://msdn.microsoft.com/en-us//library/bb383977.aspx

Mitulát báti
  • 2,086
  • 5
  • 23
  • 37