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?
There is a method fn() which is used in both the classes. Method fn() is used in both class files.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With