Butters
Butters

Reputation: 997

How to use a method in other classes?

I have a method that I want to use in almost all the classes within a same c# project.

public void Log(String line)
{
   var file = System.IO.Path.GetPathRoot(Environment.SystemDirectory)+ "Logs.txt";

   StreamWriter logfile = new StreamWriter(file, true);

   // Write to the file:
   logfile.WriteLine(DateTime.Now);
   logfile.WriteLine(line);
   logfile.WriteLine();

   // Close the stream:
   logfile.Close();
}

What is the approach to reuse this method in other classes of the project?

Upvotes: 2

Views: 1005

Answers (3)

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

You can use Extrension method in statis class

Sample on string extension

public static class MyExtensions
    {
        public static int YourMethod(this String str)
        {
        }
    }  

link : http://msdn.microsoft.com/fr-fr/library/vstudio/bb383977.aspx

Upvotes: 0

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

You can make a static class and put this function in that class.

public static MyStaticClass
{
    public static void Log(String line)
    {
        // your code
    }
}

Now you can call it elsewhere. (No need to instantiate because it's a static class)

MyStaticClass.Log("somestring");

Upvotes: 4

Mathew Thompson
Mathew Thompson

Reputation: 56429

If you want to use it in all classes, then make it static.

You could have a static LogHelper class to better organise it, like:

public static class LogHelper
{
    public static void Log(String line)
    {
        var file = System.IO.Path.GetPathRoot(Environment.SystemDirectory)+ "Logs.txt";

        StreamWriter logfile = new StreamWriter(file, true);

        // Write to the file:
        logfile.WriteLine(DateTime.Now);
        logfile.WriteLine(line);
        logfile.WriteLine();

        // Close the stream:
        logfile.Close();
    }
}

Then call it by doing LogHelper.Log(line)

Upvotes: 7

Related Questions