Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a method or property in C# that is public, yet not inheritable?

Here is an example. I have two classes, one inherited, and both have a function with the same name, but different arguments:

public class MyClass
{
    //public class members

    public MyClass()
    {
        //constructor code
    }

    public void Copy(MyClass classToCopy)
    {
        //copy code
    } 
}

public class InheritedClass : MyClass
{
    //public class members

    public InheritedClass():base()
    {
        //constructor code
    }

    public void Copy(InheritedClass inheritedClassToCopy)
    {
        //copy code
    } 
}

My question is how do I make the base class' copy method (MyClass.Copy) non-inheritable or non-visible in InheritedClass? I don't want to be able to do this:

MyClass a;
InheritedClass b;
b.Copy(a);

Does this make sense, or should I keep this functionality in there? Can what I'm asking even be done?

like image 715
Mike Webb Avatar asked Nov 27 '22 01:11

Mike Webb


1 Answers

Does this make sense, or should I keep this functionality in there? Can what I'm asking even be done?

Trying to hide a public method like this when used by a base class is problematic. You're purposely trying to violate the Liskov substitution principle.

alt text

like image 98
Reed Copsey Avatar answered Dec 19 '22 07:12

Reed Copsey