Skip to main content

How Implementing Generic Method with Constraints Can Save You Many Troubles



Generics provides you with the ability to create classes and methods that are independent of contained types. One of the cool advantage of generics is performance and easy way to provide type safety. Generics solves the problem of writing many classes or method with same features for different types, with generics you can create just one class or method that serves different types.

I came across a code:   
 The purpose was to iterate all elements of a collection and get the summation of the amount.


public class Grocery
  {
       Public string Item {get;}
       Public double Amount {get;}
  }

All the grocery in which the amount will be iterated and summed are added to a grocery list of type
List<Grocery>.

var grocery = new List<Grocery>()
{
    new Grocery("Bread", 15),
    new Grocery("Pasta", 10)
}

In this case we will be using Foreach statement to get all the elements in the collection because Foreach statement uses IEnumerable interface for iteration of items of a collection and as such it works with every object implementing the IEnumerable interface.

Public static class SampleCode
{
    public static double IterateGrocery(IEnumerable<Grocery> fetch)
    {
        foreach (var myitem in fetch)
        {
            // summation
        }
        return summation;
    }
}

The downside of IterateGrocery method, it implements only the Grocery objects. To implements other object means writing of more method that will be specific to there object types, and this is one issue that generic method solves.

Implementing Generic Method with Constraints.
Implementing generic method with constraints will solve the problem of implementing methods that works only with a specific objects type. Generic method with constraint makes it easy to implements method that works with any type that implements the interface. Constraints are basically used by generic class to invoke methods from a generic type and can also be used by methods. You can instantiate a constraints by using the where clause.
 
Public static double IterateGrocery<TGrocery> (IEnumerable<TGrocery> fetch)
   where TGrocery : IGrocery
{
        foreach (TGrocery myitem in fetch)
        {
            //summation
        }
        return summation;
}


Because the interface will be used only for retrieving elements, it defines only the read-only properties.

Public interface IGrocery
{
    double Amount {get;}
    string Item {get;}
}


 
The Glocery class will implement the interface IGrocery.


public class Grocery : IGrocery
  {
       Public string Item {get;}
       Public double Amount {get;}
  }

The IterateGrocery method can now be invoked by using the following syntax.
            double totalAmount = classname. IterateGrocery(grocery);

 
SUMMARY
The main idea behind the use of generic method with constraint is to make our code cleaner, compact and simpler, you don't have to write a method for every object you want to use, with generic method with constraints you can write one method that works with any type, all the type has to do is to inherit the interface.




Comments

Popular posts from this blog

How to implement RESTful API Versioning in ASP.NET Web API 2 using IHttpRouteConstraint

The only thing constant in life is change, and that is proved everyday in our industry, API’s are cool to extend the functionality of your application and expose it to other developers. The cool thing about IT and software, it’s that things changes quite rapidly and so it’s the technology, hence technology can change and the needs of your organisation can change, hence in order to keep serving this evolving needs and keep been relevant, your api might need to change also. Small changes can be accommodated within the initial version, but changes that will risked breaking the existing code, will required the need for versioning.

Implementing a custom IHttpRouteConstraint

According to msdn, a IHttpRouteConstraint simply Represents a base class route constraint. What then is a route constraint? A route constraint simply gets or sets a dictionary of expressions that specify valid values for a URL parameter.

publicclassApiVersionRouteConstraint : IHttpRouteConstraint
  {

publicApiVersionRouteCo…

How to implement multi-tenancy with subdomains using Route Constraint in ASP.NET MVC

According to Wikipedia, The term "software multitenancy" refers to a software architecture in which a single instance of software runs on a server and serves multiple tenants. A tenant is a group of users who share a common access with specific privileges to the software instance. With a multitenant architecture, a software application is designed to provide every tenant a dedicated share of the instance - including its data, configuration, user management, tenant individual functionality and non-functional properties. Multitenancy contrasts with multi-instance architectures, where separate software instances operate on behalf of different tenants. By giving companies, access to a tenant through a subdomain of choice, will help to personalise the experience more and gives a sense of ownership to each tenant. This will go along way to bring consistency in there branding.
Implementing Route Constraint
You use route constraints to restrict the browser requests that match a partic…

How to do partial update for HTTP APIs in ASP.NET CORE MVC with JSON Patch

JSON Patch is a format for describing changes to a JSON document. It can be used to avoid sending a whole document when only a part has changed. When used in combination with the HTTP PATCH method, it allows partial updates for HTTP APIs in a standards compliant way. A JSON Patch document is just a JSON file containing an array of patch operations. The patch operations supported by JSON Patch are “add”, “remove”, “replace”, “move”, “copy” and “test”. The operations are applied in order: if any of them fail then the whole patch operation should abort.
The JSON Patch supports the following operations:
Add - Adds a value to an object or inserts it into an array.Remove -  Removes a value from an object or array. Replace - Replaces a value. Equivalent to a “remove” followed by an “add”. Copy - Copy a value from one location to another within the JSON document. Both from and path are JSON Pointers. Move - Move a value from one location to the other. Both from and path are JSON Pointers. Test - Te…