Welcome!

Microsoft Cloud Authors: Janakiram MSV, Yeshim Deniz, David H Deans, Andreas Grabner, Stackify Blog

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

.NET 1.1 is full of types that are replicated only by changing the types they are based on. Good examples are all delegates, which define the control's event handlers. You can find delegates such as

delegate void MouseEventHandler(object sender, MouseEventArgs args);

or

delegate void KeyEventHandler(object sender, KeyEventArgs args);

These delegates are only different in the type of the parameter args. Now instead of defining events as:

public event MouseEventHandler MouseUp;
public event KeyEventHandler KeyDown;

the following generic delegate instantiation can be used:

public event EventHandler<MouseEventArgs> MouseUp;
public event EventHandler<KeyEventArgs> MouseUp;

The following handling methods can be used to directly hook to the events defined above:

private void MyControl_MouseUp(object sender, MouseEventArgs args) {...}
private void MyControl_KeyDown(object sender, KeyEventArgs args) {...}

The collection hierarchy of the .NET 1.1 is based on object, thereby forcing the use of casting as it was previously explained. .NET 2.0 keeps these classes but also includes their generic versions, so it now has Stack<T>, List<T> (for ArrayList), Queue<T>, Dictionary<TKey, TValue>, and so on.

However, in .NET 1.1 there are types using specific collection classes that are not offered in their corresponding generic version. For instance, classes of the namespace System.Windows.Form have not being adapted to the new generic classes and they continue using the old delegates and specific classes as ControlsCollection or TabPagesCollections. These are only samples of how specific replicated types or "generic" types based on object will coexist with codes based on the new generic capabilities. The next section proposes a solution to do a seamless transition from non generic to generic and vice versa.

Between Generics and Non-Generics: A Seamless Transition
In contexts where types such as IList<T> have been used frequently, the following assignments could be very useful:

IList<T> controls = panel.Controls; 1
ControlsCollection controls = new List<Control>();

Unfortunately the aforementioned assignments are not allowed in C# 2.0. We can neither do the casting:

IList<Control> controls = (IList<Control>) panel.Controls;

nor the following:

ControlCollection controls = (ControlCollection) new List<Control>();

because there is not a type-subtype relationship between IList<Control> and ControlCollection types.

However, by using the classes of the namespaces Reflection and Reflection.Emit, we implemented the generic method:

class Converters
{
    ...
public static T TypeConvert<T>(object source);
}

With the method TypeConverter it is possible to emulate the casting by doing:

IList<Control> controls =
Converters.TypeConvert<IList<Control>> (panel.Controls);
ControlCollection controls =
Converters.TypeConvert<ControlCollection> (new List<Control>());

At run time, the method TypeConverter emits a proxy type that inherits from the actual type used to instantiate T. For each method in this latter type a proxy method is emitted in the proxy type. The proxy method calls the corresponding method through the source parameter.

For example, when executing the call (Controls is a property of type ControlsCollection):

Converters<IList<Control>>.TypeConvert(panel.Controls);

a type that is similar to the code excerpt shown in Listing 5 will be emitted.

Simulating Multiple Inheritance with Genericity
.NET lacks multiple inheritance. This section shows how to emulate multiple inheritance based on genericity and reflection.

Suppose a C class would like to inherit from both A and B classes. Listing 6 shows the classic simulation pattern of the multiple inheritance. Type C will inherit only from A and will delegate its B functionality in a private object of type B. The implicit operator allows the assignment B b = new C(); as if C were inherited also from B.

Now a similar pattern can be obtained by using genericity (Listing 7). The generic class inherits from A and uses its generic type to emulate the other base class. Then in order to obtain the effect of class C inheriting from A and B, C can simply be defined as follows:

public class C : A<B>{...}

Note that an assignment A a = new C(); is allowed because C inherits A<B> and A<B> inherits from A, and an assignment B b = new C(); is also allowed because of the implicit conversion operator that returns an object of the generic parameter (B in this example).

Overriding Methods
In a real multiple-inheritance scenario where a class C inherits from A and B, the following code should execute the F method of C (since F is a virtual method).

B b = new C();
b.F();

However, for a class C obtained with the pattern of Listing 7 the F method called is still the F of B.

To solve this problem, suppose that all virtual methods of B that should be polymorphic are collected in the interface

interface IBMethods
{
...
void F(...);
}

Now we could try to define the generic class A<T> as shown in Listing 8. Note that the constrained genericity forces the type used to instantiate the generic parameter to implement the interface IBMethods. Thus, B must implement IBMethods.

We use an inner class to obtain the polymorphic effect of the B methods. Then we have the code

class C: A<B>{...}
...
C c = new C(...);
B b = c;
b.F()

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.

@ThingsExpo Stories
What is the best strategy for selecting the right offshore company for your business? In his session at 21st Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, will discuss the things to look for - positive and negative - in evaluating your options. He will also discuss how to maximize productivity with your offshore developers. Before you start your search, clearly understand your business needs and how that impacts software choices.
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
SYS-CON Events announced today that Golden Gate University will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Since 1901, non-profit Golden Gate University (GGU) has been helping adults achieve their professional goals by providing high quality, practice-based undergraduate and graduate educational programs in law, taxation, business and related professions. Many of its courses are taug...
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
SYS-CON Events announced today that CAST Software will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
SYS-CON Events announced today that SourceForge has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. SourceForge is the largest, most trusted destination for Open Source Software development, collaboration, discovery and download on the web serving over 32 million viewers, 150 million downloads and over 460,000 active development projects each and every month.
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...
SYS-CON Events announced today that TidalScale will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, will lead you through the exciting evolution of the cloud. He'll look at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering ...
As hybrid cloud becomes the de-facto standard mode of operation for most enterprises, new challenges arise on how to efficiently and economically share data across environments. In his session at 21st Cloud Expo, Dr. Allon Cohen, VP of Product at Elastifile, will explore new techniques and best practices that help enterprise IT benefit from the advantages of hybrid cloud environments by enabling data availability for both legacy enterprise and cloud-native mission critical applications. By rev...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...