none
Virtual method vs Interface RRS feed

  • Question

  • I made a form(base class) which perform data input.

    Two new class will be inherited from this base class.

    The SaveData() method will be implemented from inherited class.

    However I can't decide whether I have base class's SaveData as virtual method or inherit from interface.

    I can implement with those two ways but want to know any rule which can decide between virtual or interface.

    Friday, March 20, 2020 1:59 AM

Answers

  • Greetings Jeff.

    Generally speaking, interfaces are for unrelated classes which have methods in common, not classes which are related by having the same base.

    If your classes are derived from the same base anyway, you might as well put the common method in the base as a virtual. That way, whenever you derive from that base in the future, you will be forced to provide the method. But if you use an interface as well, you will have to remember to add the interface to the class declaration every time you derive from that base.

    • Marked as answer by Jeff0803 Saturday, March 21, 2020 11:14 PM
    Friday, March 20, 2020 5:58 AM
  • using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace csWinForms
    {
        // You can "inherit" from as many interfaces as you like, in any class
        interface someInterface
        {
            int someIntProperty { get; set; }
            void someVoidFunc();
        }
    }

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace csWinForms
    {
        // Any class can only inherit from 1 base class
        class someBaseClass
        {
            public virtual void someBaseVirtFunc()
            {
                System.Windows.Forms.MessageBox.Show(@"someBaseVirtFunc() fired from BASE");
            }
        }
    }

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace csWinForms
    {
        // Consider a class that inherits from both a base class and an interface
        //
        // If you don't define ALL the interface member fields and functions, 
        // you can't even compile.
        //
        // Defining overrides of inherited fields or methods from base classes
        // is totally optional
        class someDerivedClass : someBaseClass, someInterface
        {
            // Implementing the interface property
            public int someIntProperty
            {
                get
                {
                    return 0;
                }
                set
                {
                    // Just an example.  Not doing anything.
                }
            }
    
            // Implementing the interface method
            public void someVoidFunc()
            {
                // Just an example.  Not doing anything.
            }
    
            // Overriding this method from the base class is totally optional.
            public override void someBaseVirtFunc()
            {
                // Unlike when you use an interface, you can call back to the base 
                // or default function from inside the overriden version in the 
                // consumer/s.
                base.someBaseVirtFunc();
    
                System.Windows.Forms.MessageBox.Show(@"someBaseVirtFunc() fired from DERIVED");
    
                // You can actually call the base class' virtual func from anywhere in the 
                // derived override - even repeatedly if there's good reason for it
                base.someBaseVirtFunc();
            }
        }
    }

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace csWinForms
    {
        class someConsumerClass
        {
            void baseClassParameter(someBaseClass sbc)
            {
                // Consumers of someDerivedClass can treat instances of someDerivedClass 
                // like instances of someBaseClass.
                sbc.someBaseVirtFunc();
            }
    
            void ifaceParameter(someInterface sif)
            {
                // Consumers of someDerivedClass can treat instances of someInterface 
                // as if someInterface was directly instantiated, where someInterface 
                // can never be instantiated on its own.
                System.Windows.Forms.MessageBox.Show((sif.someIntProperty + 5).ToString());
            }
    
            void consumerParameter(someDerivedClass scc)
            {
                // An example of passing instances of someConsumerClass as if it were 
                // of a derived type/interface
                this.baseClassParameter((someBaseClass)scc);
                this.ifaceParameter((someInterface)scc);
            }
        }
    }
    So an Interface is a contract with the Consumer that ALL of the interface properties and methods will be implemented in any derived or inheriting class, while a Base Class is just a thing you inherited from because it was faster to do that than to rewrite (and reupdate in the future) the same code over and over again.

    Before you can learn anything new you have to learn that there's stuff you don't know.


    • Edited by Andrew B. Painter Saturday, March 21, 2020 6:37 PM
    • Marked as answer by Jeff0803 Saturday, March 21, 2020 11:28 PM
    Saturday, March 21, 2020 6:36 PM

All replies

  • Hi Jeff0803,
    A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived the class. It is used when a method's basic functionality is the same but sometimes more functionality is needed in the derived class.
    When a method is declared as a virtual method in a base class and that method has the same definition in a derived class then there is no need to override it in the derived class. But when a virtual method has a different definition in the base class and the derived class then there is a need to override it in the derived class.
    An interface contains definitions for a group of related functionalities that a non-abstract class or a struct must implement.
    The advantage of interfaces is that you declare an interface that can be implemented by two completely different classes. As long as the method you want to call is declared in the interface they share, you can run the same code on two different classes.
    In a general sense, one would use an interface when one wants to enforce a contract. And the methods of which must be implemented by all derived classes. One would use virtual when one wants to define default implementation details while allowing for the option of derived classes overriding and defining their own implementations. 
    Here are some related documents you can refer to.
    [Interfaces (C# Programming Guide)]
    [virtual (C# Reference)]
    Hope these are helpful to you.
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, March 20, 2020 5:24 AM
  • Greetings Jeff.

    Generally speaking, interfaces are for unrelated classes which have methods in common, not classes which are related by having the same base.

    If your classes are derived from the same base anyway, you might as well put the common method in the base as a virtual. That way, whenever you derive from that base in the future, you will be forced to provide the method. But if you use an interface as well, you will have to remember to add the interface to the class declaration every time you derive from that base.

    • Marked as answer by Jeff0803 Saturday, March 21, 2020 11:14 PM
    Friday, March 20, 2020 5:58 AM
  • Instances of interfaces cannot be created (we cannot do a new for an interface); interfaces are used by inheriting a real class from them. Also, interfaces do not have implementations; we list what methods need to exist in interfaces but we do not provide any code for doing any of the methods.

    Also, interface applies to objects and virtual applies to methods of objects. They are not compatible for the purpose of choosing which to use.



    Sam Hobbs
    SimpleSamples.Info


    Friday, March 20, 2020 8:28 PM
  • using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace csWinForms
    {
        // You can "inherit" from as many interfaces as you like, in any class
        interface someInterface
        {
            int someIntProperty { get; set; }
            void someVoidFunc();
        }
    }

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace csWinForms
    {
        // Any class can only inherit from 1 base class
        class someBaseClass
        {
            public virtual void someBaseVirtFunc()
            {
                System.Windows.Forms.MessageBox.Show(@"someBaseVirtFunc() fired from BASE");
            }
        }
    }

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace csWinForms
    {
        // Consider a class that inherits from both a base class and an interface
        //
        // If you don't define ALL the interface member fields and functions, 
        // you can't even compile.
        //
        // Defining overrides of inherited fields or methods from base classes
        // is totally optional
        class someDerivedClass : someBaseClass, someInterface
        {
            // Implementing the interface property
            public int someIntProperty
            {
                get
                {
                    return 0;
                }
                set
                {
                    // Just an example.  Not doing anything.
                }
            }
    
            // Implementing the interface method
            public void someVoidFunc()
            {
                // Just an example.  Not doing anything.
            }
    
            // Overriding this method from the base class is totally optional.
            public override void someBaseVirtFunc()
            {
                // Unlike when you use an interface, you can call back to the base 
                // or default function from inside the overriden version in the 
                // consumer/s.
                base.someBaseVirtFunc();
    
                System.Windows.Forms.MessageBox.Show(@"someBaseVirtFunc() fired from DERIVED");
    
                // You can actually call the base class' virtual func from anywhere in the 
                // derived override - even repeatedly if there's good reason for it
                base.someBaseVirtFunc();
            }
        }
    }

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace csWinForms
    {
        class someConsumerClass
        {
            void baseClassParameter(someBaseClass sbc)
            {
                // Consumers of someDerivedClass can treat instances of someDerivedClass 
                // like instances of someBaseClass.
                sbc.someBaseVirtFunc();
            }
    
            void ifaceParameter(someInterface sif)
            {
                // Consumers of someDerivedClass can treat instances of someInterface 
                // as if someInterface was directly instantiated, where someInterface 
                // can never be instantiated on its own.
                System.Windows.Forms.MessageBox.Show((sif.someIntProperty + 5).ToString());
            }
    
            void consumerParameter(someDerivedClass scc)
            {
                // An example of passing instances of someConsumerClass as if it were 
                // of a derived type/interface
                this.baseClassParameter((someBaseClass)scc);
                this.ifaceParameter((someInterface)scc);
            }
        }
    }
    So an Interface is a contract with the Consumer that ALL of the interface properties and methods will be implemented in any derived or inheriting class, while a Base Class is just a thing you inherited from because it was faster to do that than to rewrite (and reupdate in the future) the same code over and over again.

    Before you can learn anything new you have to learn that there's stuff you don't know.


    • Edited by Andrew B. Painter Saturday, March 21, 2020 6:37 PM
    • Marked as answer by Jeff0803 Saturday, March 21, 2020 11:28 PM
    Saturday, March 21, 2020 6:36 PM
  • Yes I know they are not compatible.

    However we can make code using interface or virtual for this feature.

    I just wanted to know which way is correct.

    Saturday, March 21, 2020 11:27 PM
  • Neither of them are correct if they are not correct for requirements. One of them might be correct or maybe both of them are correct. If it were true that one of them is always incorrect then it would be stupid for it to exist in the language. Both virtual methods and interfaces are extremely common in the .Net classes because they both are useful depending on needs.


    Sam Hobbs
    SimpleSamples.Info

    Saturday, March 21, 2020 11:41 PM
  • Yes I know they are not compatible.

    However we can make code using interface or virtual for this feature.

    I just wanted to know which way is correct.

    If you have a need for a base class that presents fields x and y, with serialization (ie SaveData()) for those 2 fields, and then you have a separate need for a derived class that presents fields x and y and z, then you can safely inherit from a base class and use the virtual function with callbacks to base.SaveData() to serialize x and y before serializing z in the derived.

    If instead you have a need for several classes that match a specific signature or layout but do significantly different jobs, then you need an Interface.

    Think of an Interface as if it was a Delegate or predefined function signature, except applied to classes and structs instead of event handlers or callbacks.


    Before you can learn anything new you have to learn that there's stuff you don't know.

    Sunday, March 22, 2020 5:38 AM