Click here to close now.


Microservices Expo Authors: Liz McMillan, Lori MacVittie, Pat Romanski, Elizabeth White, Rex Morrow, Datical

Related Topics: Microsoft Cloud

Microsoft Cloud: Article

Dealing With The C# 2.0 Genericity

Leverage generics for flexible code, the forthcoming .NET 2.0 Framework will introduce new important features

The forthcoming .NET 2.0 Framework will introduce new important features. One of those features is genericity. Genericity is not really a new concept. It has been included in some previous languages as ADA, C++, Eiffel, and in the mathematical model of abstract data types (ADT). However, the C# 2.0 notation for genericity (see the first entry in the References section), the integration of genericity in the .NET type system, the efficient implementation of genericity in the CLR-JIT process, and the new generic features included in the reflection mechanism will strengthen .NET programmers' output.

Genericity in .NET rests on the same basic reasons for which .NET promotes strongly typed languages:

  • Readability: Explicit declarations tell readers about the intended meaning of the code
  • Reliability: Thanks to explicit type declarations, a compiler can easily detect inconsistencies and erroneous operations
  • Efficiency: By knowing the types early, a compiler will be able to generate a more efficient code
The first section of this article starts by presenting arrays, the humble and anonymous generic construction embedded in C# and many programming languages. The second section explains how a limited form of generic types can be currently implemented in C#, based on the object type. In the third section the main characteristics and benefits of genericity in C# 2.0 are illustrated, including the notion of constrained genericity. An additional section explains how we can interact between generics and non-generics. Finally, we present an interesting example about simulation of multiple inheritance with genericity.

Arrays: The Implicit Generic Construction Embedded in .NET
Perhaps because arrays are predefined in C# and embedded in the CLR, when using them programmers don't realize that they are dealing with a truly an efficient generic construction.

When you write a declaration like int[] a you are instantiating a generic container, known as an array of items of type int. Any type T can be used to define an array through the notation T[]. A set of common properties and functionalities implicitly applies to arrays no matter what type T is:

  • All array objects are created with the notation new T[k] where k must be a positive expression that defines the numbers of items in the array.
  • An int property Length applies to every array (no matter the type T) to return the number of items of the array. Items are numbered from 0 to Length-1.
  • All items of an array of type T[] have the same type T. Items of a value type T are initialized as such value type (zero for numeric types, false for bool type, and so on) and items of a reference type T are initialized to null.
    1.  For an array T[] a, a[i] acts as a variable of type T denoting the item at position i. When using in the right side, a[i] returns an item of type T, and when using in a left side, a[i]=x; x must be of type T.
Unfortunately, before C# 2.0, programmers could not define a custom parameterized type based on a type T.

Genericity Based on the "Wild card type" Object
Today C# programmers who want to define a stack type of int objects must write the code in Listing 1a. If they wish to define a stack of objects of a type Person they could write the code in Listing 1b (for simplicity, this is only a rough implementation of a stack). Note that both classes Stackofint and StackofPerson have similar codes. They differ only in the type they are based on (int or Person). We can avoid that replication by defining a sole Stack type based on the root type object (see Listing 2).

Here object acts like a wild card type. Since every type in .NET inherits from the base object type, and thanks to the boxing and unboxing features of .NET, programmers can seamless push either a reference object or a value object into a stack. Note that the parameter of Push is of type object, then some calls like s.Push(3) or s.Push(new Person(...)) are correct, because any type conforms to object.

The approach above has the benefit of no code replication, but it has the following flaws:

  • It is not possible to enforce the kind of data to be placed in the stack. As the following code snippet shows, we could create a stack and push an assortment of objects on it.

    Stack s = new Stack(10);
    s.Push(new Date(10,10,2000);
    s.Push(new Person(...));

  • Boxing and unboxing operations that apply when pushing and retrieving objects of value types can be particularly onerous.
  • Because the compiler only knows that objects in the stack have the general type object, when we retrieve the objects from the stack we must cast them to the real type they have:

    int k = (int) s.Pop();
    Person p = (Person) s.Pop();

However casting has a run-time cost, and even worse, it is an error-prone approach because it is possible to write a wrong cast.

It would be significant if we could have the safety and efficiency of specific type definitions (as shown in Listing 1), and, at the same time, we could avoid code replication. Both benefits could be achieved with the forthcoming genericity of C# 2.0.

Genericity in C# 2.0
In C# 2.0 the aforementioned definition of Stack could be best obtained by using the generic notation shown in Listing 3.

Here Stack<T> denotes a generic type and T denotes a type parameter of this generic type. Instantiating this type parameter with an actual type will result in a type of specific stack:

Stack<Person> persons = new Stack<Person>(10);.

Now persons has the type Stack<Per-son>. This has the following benefits:

  • All operations defined in Stack<T> are applied to Stack<Person> without programming duplication
  • Compiler can accept the following code without doing casting:

    Person harry = new Person(...);
    Person p = persons.Pop();

  • In an attempt to push on persons, an object of a type not conforming to Person will result in a compilation error:

    persons.Push(23); //Error because 23 is not of type Person

    It is possible to push on the stack persons an object of a subtype of Person. If the class Employee inherits from Person, then the following code is correct:

    persons.Push(new Employee(...));

A type parameter can be used as an instantiation parameter of another generic type. Note that in the Stack<T> definition, the parameter T is used to instantiate the internal array T[] items. It means that when we write Stack<Person>, its instance variable items will be of type Person[].

Furthermore, generic instantiation can be done recursively. For example, a three-dimensional list can be defined as follows:

List<List<List<string>>> stringCube =
new List<List<List<string>>>(5);

Multiple Type Parameters
A generic type can have any number of type parameters. For example, in the generic dictionary type

class Dictionary<TKey, TValue> {...}

TKey must be instantiated with the type that we want to use as the type of the key (the object to search in the dictionary), and TValue must be instantiated as the type of the object associated with the key. Some examples are:

Dictionary<string, string> englishSpanish = new Dictionary<string, string>();
Dictionary<string, long> phoneList = new Dictionary<string, long>();
Dictionary<string, Person> contactList = new Dictionary<string, Person>();

More Stories By Miguel Katrib

Miguel Katrib is a PhD and a professor in the Computer Science Department at the University of Havana. He is also the head of the WEBOO group dedicated to Web and object-oriented technologies. Miguel is also a scientific advisor in .NET for the software enterprise CARE Technologies, Denia, Spain.

More Stories By Mario del Valle

Mario del Valle is working toward his MS at the Computer Science Department at the University of Havana, and is a software developer at the WEBOO group dedicated to Web and object-oriented technologies.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

Most Recent Comments
.NET News Desk 12/06/05 06:45:57 PM EST

The forthcoming .NET 2.0 Framework will introduce new important features. One of those features is genericity. Genericity is not really a new concept. It has been included in some previous languages as ADA, C++, Eiffel, and in the mathematical model of abstract data types (ADT). However, the C# 2.0 notation for genericity (see the first entry in the References section), the integration of genericity in the .NET type system, the efficient implementation of genericity in the CLR-JIT process, and the new generic features included in the reflection mechanism will strengthen .NET programmers' output.

@MicroservicesExpo Stories
Containers Expo Blog covers the world of containers, as this lightweight alternative to virtual machines enables developers to work with identical dev environments and stacks. Containers Expo Blog offers top articles, news stories, and blog posts from the world's well-known experts and guarantees better exposure for its authors than any other publication. Bookmark Containers Expo Blog ▸ Here Follow new article posts on Twitter at @ContainersExpo

Let's just nip the conflation of these terms in the bud, shall we?

"MIcro" is big these days. Both microservices and microsegmentation are having and will continue to have an impact on data center architecture, but not necessarily for the same reasons. There's a growing trend in which folks - particularly those with a network background - conflate the two and use them to mean the same thing.

They are not.

One is about the application. The other, the network. T...

Disruptive macro trends in technology are impacting and dramatically changing the "art of the possible" relative to supply chain management practices through the innovative use of IoT, cloud, machine learning and Big Data to enable connected ecosystems of engagement. Enterprise informatics can now move beyond point solutions that merely monitor the past and implement integrated enterprise fabrics that enable end-to-end supply chain visibility to improve customer service delivery and optimize sup...
SYS-CON Events announced today that MetraTech, now part of Ericsson, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Ericsson is the driving force behind the Networked Society- a world leader in communications infrastructure, software and services. Some 40% of the world’s mobile traffic runs through networks Ericsson has supplied, serving more than 2.5 billion subscribers.
The Internet of Things (IoT) promises to evolve the way the world does business; however, understanding how to apply it to your company can be a mystery. Most people struggle with understanding the potential business uses or tend to get caught up in the technology, resulting in solutions that fail to meet even minimum business goals. In his session at @ThingsExpo, Jesse Shiah, CEO / President / Co-Founder of AgilePoint Inc., showed what is needed to leverage the IoT to transform your business. ...
Grow your business with enterprise wearable apps using SAP Platforms and Google Glass. SAP and Google just launched the SAP and Google Glass Challenge, an opportunity for you to innovate and develop the best Enterprise Wearable App using SAP Platforms and Google Glass and gain valuable market exposure. In his session at @ThingsExpo, Brian McPhail, Senior Director of Business Development, ISVs & Digital Commerce at SAP, outlined the timeline of the SAP Google Glass Challenge and the opportunity...
What are the benefits of using an enterprise-grade orchestration platform? In their session at 15th Cloud Expo, Nate Gordon, Director of Technology at Appcore, and Kedar Poduri, Senior Director of Product Management at Citrix Systems, took a closer look at the architectural design factors needed to support diverse workloads and how to run these workloads efficiently as a service provider. They also discussed how to deploy private cloud environments in 15 minutes or less.
I read an insightful article this morning from Bernard Golden on DZone discussing the DevOps conundrum facing many enterprises today – is it better to build your own DevOps tools or go commercial? For Golden, the question arose from his observations at a number of DevOps Days events he has attended, where typically the audience is composed of startup professionals: “I have to say, though, that a typical feature of most presentations is a recitation of the various open source products and compo...
In the first four parts of this series I presented an introduction to microservices along with a handful of emerging microservices patterns, and a discussion of some of the downsides and challenges to using microservices. The most recent installment of this series looked at ten ways that PaaS facilitates microservices development and adoption. In this post I’ll cover some words of wisdom, advice intended for individuals, teams, and organizations considering a move to microservices. I've gleaned...
Many people recognize DevOps as an enormous benefit – faster application deployment, automated toolchains, support of more granular updates, better cooperation across groups. However, less appreciated is the journey enterprise IT groups need to make to achieve this outcome. The plain fact is that established IT processes reflect a very different set of goals: stability, infrequent change, hands-on administration, and alignment with ITIL. So how does an enterprise IT organization implement change...
There’s a lot of discussion around managing outages in production via the likes of DevOps principles and the corresponding software development lifecycles that does enable higher quality output from development, however, one cannot lay all blame for “bugs” and failures at the feet of those responsible for coding and development. As developers incorporate features and benefits of these paradigm shift, there is a learning curve and a point of not-knowing-what-is-not-known. Sometimes, the only way ...
Right off the bat, Newman advises that we should "think of microservices as a specific approach for SOA in the same way that XP or Scrum are specific approaches for Agile Software development". These analogies are very interesting because my expectation was that microservices is a pattern. So I might infer that microservices is a set of process techniques as opposed to an architectural approach. Yet in the book, Newman clearly includes some elements of concept model and architecture as well as p...
This is the final installment of the six-part series Microservices and PaaS. It seems like forever since I attended Adrian Cockroft's meetup focusing on microservices. It's actually only been a couple of months, but much has happened since then: countless articles, meetups, and conference sessions focusing on microservices have been delivered, many meetings and design efforts at companies moving towards a microservices-based approach have been endured, and five installments of this blog series ...
Over the years, a variety of methodologies have emerged in order to overcome the challenges related to project constraints. The successful use of each methodology seems highly context-dependent. However, communication seems to be the common denominator of the many challenges that project management methodologies intend to resolve. In this respect, Information and Communication Technologies (ICTs) can be viewed as powerful tools for managing projects. Few research papers have focused on the way...
As the world moves from DevOps to NoOps, application deployment to the cloud ought to become a lot simpler. However, applications have been architected with a much tighter coupling than it needs to be which makes deployment in different environments and migration between them harder. The microservices architecture, which is the basis of many new age distributed systems such as OpenStack, Netflix and so on is at the heart of CloudFoundry – a complete developer-oriented Platform as a Service (PaaS...
How can you compare one technology or tool to its competitors? Usually, there is no objective comparison available. So how do you know which is better? Eclipse or IntelliJ IDEA? Java EE or Spring? C# or Java? All you can usually find is a holy war and biased comparisons on vendor sites. But luckily, sometimes, you can find a fair comparison. How does this come to be? By having it co-authored by the stakeholders. The binary repository comparison matrix is one of those rare resources. It is edite...
SYS-CON Events announced today that O'Reilly Media has been named “Media Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York City, NY. O'Reilly Media spreads the knowledge of innovators through its books, online services, magazines, and conferences. Since 1978, O'Reilly Media has been a chronicler and catalyst of cutting-edge development, homing in on the technology trends that really matter and spurring their adoption...
In her General Session at 15th Cloud Expo, Anne Plese, Senior Consultant, Cloud Product Marketing, at Verizon Enterprise, focused on finding the right mix of renting vs. buying Oracle capacity to scale to meet business demands, and offer validated Oracle database TCO models for Oracle development and testing environments. Anne Plese is a marketing and technology enthusiast/realist with over 19+ years in high tech. At Verizon Enterprise, she focuses on driving growth for the Verizon Cloud platfo...
I’ve been thinking a bit about microservices (μServices) recently. My immediate reaction is to think: “Isn’t this just yet another new term for the same stuff, Web Services->SOA->APIs->Microservices?” Followed shortly by the thought, “well yes it is, but there are some important differences/distinguishing factors.” Microservices is an evolutionary paradigm born out of the need for simplicity (i.e., get away from the ESB) and alignment with agile (think DevOps) and scalable (think Containerizati...
The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that produce software that is obsolete at launch. DevOps may be disruptive, but it is essential. The DevOps Summit at Cloud Expo – to be held June 3-5, 2015, at the Javits Center in New York City – will expand the DevOps community, enable a wide...