Reputation: 75
Below are the list of classes. These classes have a common method whose objective is same in classes. I want to remove the repetation of CommonMethod() by moving this method to Fourth Class and get it called from remaining Other class
Class First
{
string ClassField
method FirstClassMethodOne()
{
CommonMethod()
}
method CommonMethod()
{
classField = 1
}
}
Class Second
{
method SecondClassMethodOne()
{
CommonMethod()
}
method CommonMethod()
{
Fifth.classField = 1
}
}
Class Third
{
method ThirdClassMethodOne()
{
CommonMethod()
}
method CommonMethod(string a, string b)
{
stirng ClassField
classField = 1
}
}
Class Fourth
{
string FourtClassField
method FourtClassMethodOne()
{
}
}
Upvotes: 2
Views: 482
Reputation: 9789
Create a new class and add CommonMethod()
to that class. It looks like you have overloaded versions of CommonMethod()
so you'll need to account for different parameters in each of your overloaded methods. You will need an instance of your class or a static class for calling your method from each individual class.
Upvotes: 0
Reputation: 943
If your classes all inherit the common base ClassBase, then leaving the method in ClassBase would be appropriate.
class ClassBase
{
public static string ClassField;
public virtual void MethodOne()
{
CommonMethod();
}
public virtual void CommonMethod()
{
ClassField = "1";
}
}
class ClassOne : ClassBase
{
}
class ClassTwo : ClassBase
{
public void CommonMethod(string a, string b)
{
string localVariable;
base.CommonMethod();
}
}
Upvotes: 0
Reputation: 70718
You could move the method into Fourth
and call it via:
public class Fourth() {
public void Method() {
}
}
var fourth = new Fourth();
fourth.Method();
Or you can make an base / abstract class and inherit from that.
public class Base {
public void CommonMethod() { }
}
public class First : Base
{
}
public class Second : Base
{
}
var first = new First();
first.CommonMethod();
var second = new Second();
second.CommonMethod();
Upvotes: 1
Reputation: 4125
You could create a static class with the method inside. That method could accept some parameter to distinguish between the classes if needed.
Upvotes: 1
Reputation: 12837
You can move the method to a new class and make the 3 old classes inherit from that new class.
class BaseClass
{
public void YourMethod()
{
// ...
}
}
class FirstClass : BaseClass
{
}
Upvotes: 3