Wednesday, 30 December 2020

Certificates and Provisioning profile for uploading app to app store.

Certificates - This is a cryptographic certificate granted to you by Apple.  It works just like SSL where you get a certificate signed by an authority.  Apple signs the private key that you use to sign different pieces of your application.  Different certificates create different types of trust.  Some allow you to sign and submit your application for the App Store, while others allow your application's web server to send push notifications to users via APNS.  In the latter case, for instance, Apple uses this certificate to trust the web server sending the push notification.  Otherwise, it would be easy for an attacker to spoof a valid push notification and spam users.  The most common certificate you would create signs the key you use to deploy your application to a device or submit it to the App Store.


When you create a certificate through Apple's developer portal, you have to create your key pair and send a "Certificate Signing Request," which at first is likely pretty confusing to developers just trying to see their application run on a device.
If you visit the developer portal, you'll find you can create certificates for Development or Distribution.  These certificates are rooted to different authorities, so that the two worlds are never confused (though all iOS devices trust both in a seemingly equal fashion).
Provisioning Profiles - Probably the most confusing component in the system, a provisioning profile indicates the devices for which an application is correctly signed.  If you visit the developer portal, you'll notice you can create two types (again called Development and Distribution).  Provisioning profiles say "applications with this Identifier signed with this Certificate's private key are okay to run on these devices."  Now that you know a provisioning profile is tied to a certificate, you can see why you have to decide whether to create a Development or Distribution profile.  Development profiles are limited to 100 devices.  Distribution profiles can either be Ad-Hoc or App Store distribution profiles.  I am not sure whether Ad Hoc profiles have device limits.
You might ask, then, why not always use a Distribution profile?  It can deploy to an unlimited number of devices, and is still attached to a certificate owned by the developer.  Another piece of Apple's security puzzle are Entitlements.  In an iOS application's bundle, you'll find Entitlements.plist, which is a list of capabilities that an application wants.  When signing your application using a certificate intended for distribution, Xcode (really the signing utility) will not allow an entitlement with get-task-allow set to YES.  This is because get-task-allow is what allows a debugger to connect to a process, and Apple doesn't want that happening on apps meant for distribution.


Short Ans : 

1. A Certificate authenticates you as an entity. It can represent you as an individual, or your company.
2. The Identifier is a unique ID for your mobile app.
3. A provisioning profile associates your certificate with the App ID. It is the link between #1 and #2 above.

Monday, 28 December 2020

C# - Delegates

  • C# delegates are similar to pointers to functions, in C or C++. 
  • delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.
  • Delegates are especially used for implementing events and the call-back methods. 
  • All delegates are implicitly derived from the System.Delegate class.
For example, if you click an Button on a form (Windows Form application), the program would call a specific method. In simple words, it is a type that represents references to methods with a particular parameter list and return type and then calls the method in a program for execution when it is needed.
  • Provides a good way to encapsulate the methods.
  • Delegates are the library class in System namespace.
  • These are the type-safe pointer of any method.
  • Delegates are mainly used in implementing the call-back methods and events.
  • Delegates can be chained together as two or more methods can be called on a single event.
  • It doesn’t care about the class of the object that it references.
  • Delegates can also be used in “anonymous methods” invocation.
  • Anonymous Methods(C# 2.0) and Lambda expressions(C# 3.0) are compiled to delegate types in certain contexts. Sometimes, these features together are known as anonymous functions.
Declaring Delegates
public delegate int MyDelegate (string s);
delegate <return type> <delegate-name> <parameter list>
Instantiating Delegates
public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);



using System;
delegate int NumberChanger(int n);
namespace DelegateAppl {
class TestDelegate {
static int num = 10;
public static int AddNum(int p) {
num += p;
return num;
}
public static int MultNum(int q) {
num *= q;
return num;
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
//calling the methods using the delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
Value of Num: 35
Value of Num: 175
x

A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered.

Important Points About Delegates:

Delegate declaration determines the methods that can be referenced by the delegate. A delegate can refer to a method, which has the same signature as that of the delegate.

For example, consider a delegate −

The preceding delegate can be used to reference any method that has a single string parameter and returns an int type variable.

Syntax for delegate declaration is −

Once a delegate type is declared, a delegate object must be created with the new keyword and be associated with a particular method. When creating a delegate, the argument passed to the new expression is written similar to a method call, but without the arguments to the method. For example −

Following example demonstrates declaration, instantiation, and use of a delegate that can be used to reference methods that take an integer parameter and returns an integer value.

When the above code is compiled and executed, it produces the following result −

Wednesday, 23 December 2020

Model-View-ViewModel (MVVM) & MVC & MVP

 

Model–view–viewmodel (MVVM) is a software architectural pattern that facilitates the separation of the development of the graphical user interface (the view) – be it via a markup language or GUI code – from the development of the business logic or back-end logic (the model) so that the view is not dependent on any specific model platform. The view model of MVVM is a value converter, meaning the view model is responsible for exposing (converting) the data objects from the model in such a way that objects are easily managed and presented.  




--Ref : "wikipedia"


DESCRIPTION OF MODEL :


MODEL: ( Reusable Code – DATA ) Business Objects that encapsulate data and behavior of application domain, Simply holds the data.
VIEW: ( Platform Specific Code – USER INTERFACE ) What the user sees, The Formatted data.
VIEWMODEL: ( Reusable Code – LOGIC ) Link bewteen Model and View OR It Retrieves data from Model and exposes it to the View. This is the model specifically designed for the View.

FEATURES:

  • Life Cycle state of Application will be maintained.
  • The application will be in the same position as to where the user left it.
  • UI Components are kept away from Business Logic.
  • Business Logic is kept away from Database operations.
  • Easy to understand and read.

  • Get some more details : 

The Model

The model is what I like to refer to as the domain object. The model represents the actual data and/or information we are dealing with. An example of a model might be a contact (containing name, phone number, address, etc) or the characteristics of a live streaming publishing point.

The key to remember with the model is that it holds the information, but not behaviors or services that manipulate the information. It is not responsible for formatting text to look pretty on the screen, or fetching a list of items from a remote server (in fact, in that list, each item would most likely be a model of its own). Business logic is typically kept separate from the model, and encapsulated in other classes that act on the model.

This is not always true: for example, some models may contain validation.

It is often a challenge to keep a model completely “clean.” By this I mean a true representation of “the real world.” For example, a contact record may contain a last modified date and the identity of the modifying user (auditing information), and a unique identifier (database or persistence information). The modified date has no real meaning for a contact in the real world but is a function of how the model is used, tracked, and persisted in the system.

Here is a sample model for holding contact information:

namespace MVVMExample
{
    public class ContactModel : INotifyPropertyChanged
    {
        private string _firstName;

        public string FirstName
        {
            get { return _firstName; }
            set
            {
                _firstName = value;
                RaisePropertyChanged("FirstName");
                RaisePropertyChanged("FullName");
            }
        }

        private string _lastName;

        public string LastName
        {
            get { return _lastName; }
            set
            {
                _lastName = value;
                RaisePropertyChanged("LastName");
                RaisePropertyChanged("FullName");
            }
        }

        public string FullName
        {
            get { return string.Format("{0} {1}", FirstName, LastName); }
        }

        private string _phoneNumber;

        public string PhoneNumber
        {
            get { return _phoneNumber; }
            set
            {
                _phoneNumber = value;
                RaisePropertyChanged("PhoneNumber");
            }
        }

        protected void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public override bool Equals(object obj)
        {
            return obj is ContactModel && ((ContactModel) obj).FullName.Equals(FullName);
        }

        public override int GetHashCode()
        {
            return FullName.GetHashCode();
        }
    }
}

The View

The view is what most of us are familiar with and the only thing the end user really interacts with. It is the presentation of the data. The view takes certain liberties to make this data more presentable. For example, a date might be stored on the model as number of seconds since midnight on January 1, 1970 (Unix Time). To the end user, however, it is presented with the month name, date, and year in their local time zone. A view can also have behaviors associated with it, such as accepting user input. The view manages input (key presses, mouse movements, touch gestures, etc) which ultimately manipulates properties of the model.

In MVVM, the view is active. As opposed to a passive view which has no knowledge of the model and is completely manipulated by a controller/presenter, the view in MVVM contains behaviors, events, and data-bindings that ultimately require knowledge of the underlying model and viewmodel. While these events and behaviors might be mapped to properties, method calls, and commands, the view is still responsible for handling it’s own events and does not turn this completely over to the viewmodel.

One thing to remember about the view is that it is not responsible for maintaining its state. Instead, it will synchronize this with the viewmodel.

Here is an example view, expressed as XAML:

<UserControl x:Class="MVVMExample.DetailView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding CurrentContact}">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="Name:" HorizontalAlignment="Right" Margin="5"/>
        <TextBlock Text="{Binding FullName}" HorizontalAlignment="Left" Margin="5" Grid.Column="1"/>
        <TextBlock Text="Phone:" HorizontalAlignment="Right" Margin="5" Grid.Row="1"/>
        <TextBlock Text="{Binding PhoneNumber}" HorizontalAlignment="Left" Margin="5" Grid.Row="1" Grid.Column="1"/>
    </Grid>
</UserControl>

Note that the various bindings are the integration/synchronization points with the viewmodel.

The ViewModel (Our Controller/Presenter)

The viewmodel is a key piece of the triad because it introduces Presentation Separation, or the concept of keeping the nuances of the view separate from the model. Instead of making the model aware of the user’s view of a date, so that it converts the date to the display format, the model simply holds the data, the view simply holds the formatted date, and the controller acts as the liaison between the two. The controller might take input from the view and place it on the model, or it might interact with a service to retrieve the model, then translate properties and place it on the view.

The viewmodel also exposes methods, commands, and other points that help maintain the state of the view, manipulate the model as the result of actions on the view, and trigger events in the view itself.

Here is what a sample view model might look like. We’ve created a BaseINPC class (for “INotifyPropertyChanged”) that has a method to make it easy for raising the property changed event.

namespace MVVMExample
{
    public class ContactViewModel : BaseINPC
    {
        public ContactViewModel()
        {
            Contacts = new ObservableCollection<ContactModel>();
            Service = new Service();
            
            Service.GetContacts(_PopulateContacts);

            Delete = new DeleteCommand(
                Service, 
                ()=>CanDelete,
                contact =>
                    {
                        CurrentContact = null;
                        Service.GetContacts(_PopulateContacts);
                    });
        }

        private void _PopulateContacts(IEnumerable>ContactModel> contacts)
        {
            Contacts.Clear();
            foreach(var contact in contacts)
            {
                Contacts.Add(contact);
            }
        }

        public IService Service { get; set; }

        public bool CanDelete
        {
            get { return _currentContact != null; }
        }

        public ObservableCollection<ContactModel> Contacts { get; set; }

        public DeleteCommand Delete { get; set; }

        private ContactModel _currentContact;

        public ContactModel CurrentContact
        {
            get { return _currentContact; }
            set
            {
                _currentContact = value;
                RaisePropertyChanged("CurrentContact");
                RaisePropertyChanged("CanDelete");
                Delete.RaiseCanExecuteChanged();
            }
        }
    }
}

This view model is obviously designed to manage a list of contacts. It also exposes a delete command and a flag to indicate whether delete is allowed (thus maintaining state for the view). Often the flag would be part of the command object, but the example is in Silverlight 3 which does not have native support for command binding, and I wanted to show a simple solution that didn’t require a fancy framework. The view model here makes a concrete reference to the service, you would most likely wire in that reference externally or use a dependency injection framework. What’s nice is we have the flexibility to build it like this initially and then refactor as needed. It fetches the list of “contacts” right away, which is a hard-coded list of me and someone a little more popular. The phone numbers, of course, are faked.

The View and the ViewModel

  • The view and the viewmodel communicate via data-binding, method calls, properties, events, and messages
  • The viewmodel exposes not only models, but other properties (such as state information, like the “is busy” indicator) and commands
  • The view handles its own UI events, then maps them to the viewmodel via commands
  • The models and properties on the viewmodel are updated from the view via two-way databinding.

DIFFERENCES BETWEEN MVVM AND MVC:

MVVMMVC:
The Model is somewhat similar to MVC but here we have ViewModels which are passed to the view and
all the logic is in the ViewModel and hence no controller is there. Example: Knockout.js
In this pattern, we have models which are basic objects with no code and just properties, View’s
contributes to presentation items (HTML, WinForms, etc) and Controllers focuses on the logic part.
Examples: ASP.NET MVC, Angular
In MVVM your DeletePerson would be called off of your view modelWe have a PersonController with an Action DeletePerson that creates a person
We are on the client side so we can hold on to objects and do a lot more logic in a non-disconnected
state.
MVC is typically used when things are transactional and disconnected as is the case with server-side
web. In ASP MVC we send the view through the wire and then the transaction with the client is over.

ADVANTAGES:

  • Maintainability – Can remain agile and keep releasing successive versions quickly.
  • Extensibility – Have the ability to replace or add new pieces of code.
  • Testability – Easier to write unit tests against a core logic.
  • Transparent Communication – The view model provides a transparent interface to the view controller, which it uses to populate the view layer and interact with the model layer, which results in a transparent communication between the layers of your application.

DISADVANTAGES:

  • Some people think that for simple UIs, MVVM can be overkill.
  • In bigger cases, it can be hard to design the ViewModel.
  • Debugging would be a bit difficult when we have complex data bindings.

MVP :


MVP stands for Model View Presenter, and the MVP pattern is the successor of the MVC (Model View Controller) model. In simple words,  
" the MVP is the much-awaited update with a better user interface and was redesigned for smoother code modification ."

The MVP pattern is further divided into three different layers, which are: Model, Presenter, and View.

1. Model

The first layer is the Model that contains the data; we can say that the model is the only gateway to the business logic as they merely store the data. These models are treated as objects because they also consist of properties including details like Name, Type, Date and many more.

The model layer stores the JavaBeans data from several sources like the cache, android file system, database, etc.

2. Presenter

The second layer is that of the Presenter, which is also known as the middle-man between the two other layers. So, the part coupling between the Model layer and the View layer is the Presenter layer. The responsibility of the presenter layer is to pass the data from one layer to another by analyzing it and providing interaction between the layers.

The division of the Presenter layer is responsible for allowing the substitution of the coding parts, connecting layers as interfaces, and also the proper testing.

3. View

The third and the last layer is the View layer whose responsibility is to provide the visual display of the mobile apps in sync with the data and information that is provided as input by the user. The critical function of the view layer is first to detect the input, if any and then proceed with visualization based on actions like swipe, tap, touch, etc.

The view layer is to take care of the UI component which further controls the viewing properties and is responsible for displaying the data on the screen.

Pros of MVP Pattern

  • MVP has better testing possibilities because here the complete business logic is separated from the UI segment and that's why the data is more straightforward to imitate.
  • The view layer in this architecture is comparatively light as it has few clear lines of code just to support visualization.
  • Unlike other architecture, the developer can easily change the framework because in MVP all the ties are described in the form of interfaces.

Cons of MVP Pattern

  • The size of the code in Model View Presenter (MVP) is excessive which further makes it a little bit complex.
  • In the MVP architecture, a large number of interfaces are used for interaction between the three layers.
  • Because each interface only covers a small fraction of the interactions, this leads to a large variety of methods to implement.

Reasons to Pick MVVM in the MVP vs. MVVM Comparison

Below is the comparison between the MVP and the MVVM architectures based on the features like:

  • Logic: In the MVVM model, the code class of ViewModel is the application, and its View is the interface between the user and the app for the interaction purpose. Whereas in the case of MVP, the View is the app and the Presenter is handling the flow of the application.
  • Data Input: The process in MVP initiated from the View and not with the Presenter, but in the case of MVVM, it begins with View and not from the ViewModel.
  • Maintainability: It is easy to add new features in the ViewModel if the app developer has some prior experience with the particular library.
  • Code Metrics: The Model View Presenter creates more code and Java classes than the ViewModel architecture.

We favor MVVM over the MVP model because in the MVVM pattern the separation is possible between the View layer and the ViewModel that means a separation can exist between the User Interface (UI) and the logical code respectively.

The app developers can also write their UI tests by using Expresso which is highly preferred. But the best part about MVVM that makes it a more attractive option than MVP is that it provides the ease of maintenance to the user by allowing them to make changes to codebase efficiently.

So, that was our shot in comparison of two of the most popular android app development architectures, i.e., MVP vs. MVVM models. Hopefully, you liked the insights on the main difference between the MVP vs. MVVM android architecture model.



Thursday, 17 December 2020

Integrating Fingerprint Authentication with App Login for iOS and Android

One of the common use cases is to enable fingerprint login for an app. This adds additional security and also makes it convenient to use. Fingerprint scanning is platform specific; however, in this article we will use a plug-in available for Xamarin Forms to enable fingerprint detection.

Description

To begin with, create a solution using the template 'Multiplatform' --> Forms App. In this example, we name it 'FingerprintDemo.' Add the 'Plugin.Fingerprint' package to the cross-platform forms and also to the device-specific projects.



In this sample application, we will create an authentication page, where the user will key in the credentials to log in to the app. The app uses the saved fingerprint information on the device. The app saves the user login details for the first time. Future logins are enabled by using the fingerprint login and the saved credentials. If the credentials or the fingerprint don't validate, the user is required to key in the credentials again.

Xamarin Forms Level Changes

Create a new XAML form that will be the login page. This will be the starting point of the app. In the XAML, add two entry fields to key in the username/password. Add a button that lets the user authenticate. We will wrap the entry fields in the stack layout to hide or show the section based on whether or not the fingerprint login is available. If fingerprint login is available, the user just presses the 'Login' button.

<StackLayout>
   <Label Text="Authentication" VerticalOptions="Center"
      HorizontalOptions="Center" />
   <StackLayout x:Name="inputContainer">
      <Entry Placeholder="Username" x:Name="txtUsername" />
      <Entry Placeholder="Password" IsPassword="true"
         x:Name="txtPassword" />
   </StackLayout>
   <Button Clicked="OnLogin_Clicked" x:Name="btnLogin"
      Text="Login" />
</StackLayout>

In the code behind file, we declare the following properties:

   public string Username { get; set; }
   public string Password { get; set; }
   public bool IsFingerprintLoginAvailableForUser { get; set; }
   private bool _storedCredentialsExists { get; set; }

In the constructor, add the following code to initialize the application:

   var init = Init();
   init.Wait();

Define a method named 'Init,' as shown below:

   public async Task Init()
   {
      // Check if the user has stored credentials from a
      // prior login
      if (Application.Current.Properties.ContainsKey("Username"))
      {
         _storedCredentialsExists = true;
      }
      var fingerprintSupported = await
         CrossFingerprint.Current.IsAvailableAsync();
      IsFingerprintLoginAvailableForUser = fingerprintSupported
         && _storedCredentialsExists;

      if(IsFingerprintLoginAvailableForUser)
      {
         inputContainer.IsVisible = false;
      }

   }

This method checks whether the user credentials are stored in the application properties. It also checks if the fingerprint is supported.

In the login button clicked event, add the following code:

 1. public void OnLogin_Clicked(object sender, System.EventArgs e)
 2. {
 3.    if (IsFingerprintLoginAvailableForUser)
 4.    {
 5.       Task.Run(async () => { await Authenticate(); });
 6.    }
 7.    else
 8.    {
 9.       if (Application.Current.Properties
                .ContainsKey("Username"))
10.          Application.Current.Properties["Username"] =
                txtUsername.Text;
11.       else
12.          Application.Current.Properties.Add("Username",
                txtUsername.Text);

13.       if (Application.Current.Properties
                .ContainsKey("Password")
14.          Application.Current.Properties["Password"] =
                txtPassword.Text;
15.       else
16.          Application.Current.Properties.Add("Password",
                txtPassword.Text);
17.
18.       if (
19.          ValidateUsernamePassword(
20.             Application.Current.Properties["Username"]
                   .ToString(),
                Application.Current.Properties["Password"]
                   .ToString()))
                {
                   // Navigate to the home/landing page

                }
          else
          {
             Task.Run(async () =>
             {
                await DisplayAlert("Login Error",
                   "Invalid Username/Password", "Cancel");
                // Disable biometric login
                IsFingerprintLoginAvailableForUser = false;
             });
          }
       }
    }

The code checks if the fingerprint login is available for the user. If yes, it executes the 'Authenticate' method. If there is no fingerprint available, it stores the currently entered username/password to the application properties.

The "Authenticate" method definition is as demonstrated below:

1. public async Task Authenticate()
2. {
3.    if (IsFingerprintLoginAvailableForUser)
4.    {
5.       // Configure the fingerprint request dialog
6.       var biometricConfig = new
            AuthenticationRequestConfiguration("Fingerprint Auth")
            {
               CancelTitle = "Cancel",
               FallbackTitle = "Done"
            };
7.       var biometricResult = await CrossFingerprint.Current
               .AuthenticateAsync
            (biometricConfig);

         if (biometricResult.Authenticated)
         {

            if (ValidateUsernamePassword(
               Application.Current.Properties["Username"]
                  .ToString(),
               Application.Current.Properties["Password"]
                  .ToString()))
            {
               // Navigate to the home/landing page

            }
            else
            {
               await DisplayAlert("Login Error",
                  "Invalid UserName/Password", "Cancel");

                  IsFingerprintLoginAvailableForUser = false;
                  inputContainer.IsVisible = true;
            }
         }
         else if (biometricResult.Status ==
            FingerprintAuthenticationResultStatus.UnknownError)
         {
            await DisplayAlert("Error",
               biometricResult.ErrorMessage, "Cancel");
         }
      }
   }

Line 6 of the 'Authenticate' method configures the fingerprint request dialog and Line 7 prompts the dialog for the fingerprint authentication. When the user presses their finger against the fingerprint reader, it validates the fingerprint. If fingerprint is authenticated, it authenticates the app with the stored credential information and navigates the user to the next page.

Ref :  https://www.nuget.org/packages/Plugin.Fingerprint/



Virtual Method in C# - Polymorphism

The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism, a person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. So the same person posses different behavior in different situations. This is called polymorphism. Polymorphism is considered as one of the important features of Object Oriented Programming.

In C++ polymorphism is mainly divided into two types:

  • Compile time Polymorphism
  • Runtime Polymorphism

What Is A Virtual Method?(Function Overriding)

A virtual method is a class method that offers functionality to the programmer to override a method in the derived class that has the same signature. Virtual methods are mainly used to perform polymorphism in the OOPs environment.

A virtual method can have an implementation in both derived and base classes. It is mainly used when a user needs to have more functionality in the derived class.

A virtual method is first created in a base class and then it is overridden in the derived class. A virtual method can be created in the base class by using the “virtual” keyword and the same method can be overridden in the derived class by using the “override” keyword.

Virtual Methods: Few Points To Remember

  • The virtual method in the derived class has the virtual keyword and the method in derived class should have an override keyword.
  • If a method is declared as a virtual method in the base class, then it’s not always required by the derived class to override that method i.e. its optional to override a virtual method in the derived class.
  • If a method has the same definition in both the base and derived class then it’s not required to override the method. Override is only required if both have a different definition.
  • The overriding method allows us to use more than one form for the same method, hence it also shows polymorphism.
  • All the methods are non-virtual by default.
  • A virtual modifier cannot be used together with Private, Static, or Abstract modifiers.
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.
 
When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.
 

Virtual Method in C#

  1. By default, methods are non-virtual. We can't override a non-virtual method.
  2. We can't use the virtual modifier with the static, abstract, private or override modifiers.

What Is The Use Of Virtual Keyword In C#?

The virtual keyword in C# is used to override the base class member in its derived class based on the requirement.

A virtual keyword is used to specify the virtual method in the base class and the method with the same signature that needs to be overridden in the derived class is preceded by override keyword.

Difference Between Abstract Method And Virtual Method

Virtual methods contain implementation and allow the derived class to override it whereas the abstract method does not offer any implementation and it forces the programmers to write override methods in the derived class.

Hence, in simple words, the abstract methods don’t have any code inside them whereas the virtual method has its own implementation.

Difference Between Virtual And Override In C#

The virtual keyword is usually followed by the signature of the method, property, etc. and allows it to be overridden in the derived class. The override keyword is used in the derived class with the same method/property signature as in the base class to achieve override in the derived class.

Is It Mandatory To Override Virtual Method In C#?

The compiler will never enforce programmers to override a virtual method. It’s not always required by the derived class to override the virtual method.

Example

Let’s have a look at an example to understand more clearly about the virtual methods.

In this example, we will be using two different methods in the base class, the first one is a non-virtual method and the other one is a virtual method with the virtual keyword. Both these methods will be overridden in the derived class.

Let us have a look:

Program

using System;
                     
public class Program
     
     {
       public static void Main(string[] args)
       {
           calculate calc = new calculate ();
           numbers nmbr = calc;
           calc.addition();
           nmbr.addition();
           calc.subtraction();
           nmbr.subtraction();
 
        }
    }
 
    public class numbers
    {
       public void addition(){
      Console.WriteLine("This is addition method");
     }
 
      public virtual void subtraction(){
      Console.WriteLine("This is subtraction method");
       }
 
    }
 
    public class calculate : numbers
    {
          public void addition(){
 
          Console.WriteLine("This is addition method in the derived class");
       }
 
       public override void subtraction(){
 
       Console.WriteLine("This is subtraction method override in derived class");
       }
    }

Output

The output of the above program is:

This is addition method in the derived class
This is addition method
This is subtraction method override in derived class
This is subtraction method override in derived class

Explanation

In the above example, we have two classes i.e. Number and Calculate. The base class Number has two methods i.e. addition and subtraction where addition is a non-virtual method and subtraction is a virtual method. Hence, when we execute this program the base class virtual method “addition” is overridden in the derived class Calculate.

In another class “Program” we create an entry point to create an instance of the derived class Calculate and then we assign the same instance to the instance object of the base class.

When we call the virtual and non-virtual methods by using the class instances then we see that the virtual method got overridden by using both the instances whereas the non-virtual method was overridden only while calling the derived class.

Conclusion :

The virtual keyword is useful in modifying a method, property, indexer, or event. When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime.

Example :

using System;

namespace PolymorphismApplication {
   class Shape {
      protected int width, height;
   
      public Shape( int a = 0, int b = 0) {
         width = a;
         height = b;
      }

      public virtual int area() {
         Console.WriteLine("Parent class area :");
         return 0;
      }
   }

   class Rectangle: Shape {
      public Rectangle( int a = 0, int b = 0): base(a, b) {

      }

      public override int area () {
         Console.WriteLine("Rectangle class area ");
         return (width * height);
      }
   }

   class Triangle: Shape {
      public Triangle(int a = 0, int b = 0): base(a, b) {
   }

   public override int area() {
      Console.WriteLine("Triangle class area:");
      return (width * height / 2);
   }
}

class Caller {
   public void CallArea(Shape sh) {
      int a;
      a = sh.area();
      Console.WriteLine("Area: {0}", a);
   }
}

class Tester {
   static void Main(string[] args) {
      Caller c = new Caller();
      Rectangle r = new Rectangle(10, 7);
      Triangle t = new Triangle(10, 5);

      c.CallArea(r);
      c.CallArea(t);
      Console.ReadKey();
   }
   }
}

    All About .NET MAUI

      What’s .NET MAUI? .NET MAUI (.NET Multi-platform App UI) is a framework for building modern, multi-platform, natively compiled iOS, Androi...

    Ads2