0
class A : N
{
     void sinefunc()
     {
           //some stuff here
     }
}

class B : N
{

    void sinefunc()
    {
        //some stuff here
    }
}

class C : N
{ 
    void sinefunc()
    {
         //some stuff here
    }
}

The sinefunc() is a common function. but, the classes A,B and C exists in different projects under a solution. The classes already inherit a common class N and now,

  1. To avoid code repetition, the sinefunc() can be moved outside of these classes.
  2. But, since Multiple inheritance is not allowed. what is the efficient method or feasible way to make the function common ? (Please note that I don't want to put the sinefunc() in class N. Its been already written and I don't want to disturb that class.

3 Answers 3

4

(Please note that I dont want to put the sinefunc() in class N. Its been already written and I dont want to disturb that class)

Without moving the function to N class, you can't do that. You can have an interface which will have the method signature, but then you have to define implementation at each class.

One way to do it would be to write an extension method to class N and you can use that in the inherited classes.

EDIT:

Define a static class to hold the extension method like:

public static class ExtensionClass
{
    public static void sinefunc(this N obj)
    {
        // your code
    }
}

Later you can call it like:

static void Main(string[] args)
{
    A objA = new A();
    objA.sinefunc();
}

Remember to include the namespace which is holding the extension method, otherwise it will not be visible. You can read more at: Extension methods MSDN

Sign up to request clarification or add additional context in comments.

3 Comments

Extension method is the "C#onic" way to add the function to multiple subclasses of N without changing N. That said, if you have multiple subclasses with identical functionality it seems like moving it into N really is the right thing to do.
Thanks for letting me know the extension methods Habib. pretty new here.. some code samples will be greatly appreciated.
Thanks Habib.. it was helpful. trying to implement it now.
2

You could create an intermediate class which acts as a facade to class N:

class A : X {    }

class B : X {    }

class C : X {    }

class X : N
{
     protected void sinefunc()
     {
           //some stuff here
     }
}

2 Comments

you mean the multilevel inheritance ?
Thanks you for an another way!
0

if The sinefunc() is a common function, why don't you put it into another class. For example, you can make it a static method in Utility class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.