Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to share a function between two class files

Tags:

methods

c#

class

There are two files A.cs and B.cs. There is a method fn() which is used in both the classes.

Method fn() is used in both class files. This increases code complexity if I need this method in many class files (say 100 files).

I know that we can call this method by creating an object for the class in which this method is defined. How can I share this function between two or more classes without creating an object every time for accessing this method?

like image 240
Anandaraj Avatar asked Aug 22 '13 09:08

Anandaraj


People also ask

How do you share a function between two classes?

There is a method fn() which is used in both the classes. Method fn() is used in both class files.

What is a class member?

A Class Member is a person or entity who belongs to a specific group that is directly affected by allegations against a defendant in a class action lawsuit. When a class action lawsuit is filed, the plaintiff files it on behalf of a proposed Class that was affected by some harmful action or omission by a defendant.


1 Answers

Put the method in a static class:

public static class Utils
{
     public static string fn()
     {
         //code...
     }
}

You can then call this in A.cs and B.cs without creating a new instance of a class each time:

A foo = new A();
foo.Property = Utils.fn();

Alternatively, you could create a BaseClass that all classes inherit from:

public class BaseClass
{
    public BaseClass() { }
    public virtual string fn()
    {
        return "hello world";
    }
}

public class A : BaseClass
{
    public A() { }
}

You would then call fn() like so:

A foo = new A();
string x = foo.fn();
like image 197
DGibbs Avatar answered Sep 28 '22 23:09

DGibbs