Click here to Skip to main content
15,908,768 members
Please Sign up or sign in to vote.
4.00/5 (3 votes)
See more:
Hello,

I have some doubts on generics:

1)Why does CLR not allow the creation of generic enumerations?

2)Classes encapsulate algorithms which can be applied on types so we have generic classes, similarly methods can also encapsulate algorithms so we can have generic methods(Correct me if i am wrong). So can i say that which ever entity that is subjected to an algorithm can be treated as a generic entity?

3)What is an indexer method? How does it qualify to become a generic method?

4)Generics dont have many virtual classes. How does having a fewer virtual classes increase the performance of generic entities?

5)We have both generic and non generic interface for backward compatibility, actually speaking i read a sentence which states the reason for backward compatibility : It goes like this:
"If the List<t> class implemented only the IList<t> interface, no code could consider a List<datetime> object an IList.". I couldnt understand the meaning of this statement.

Thanks and regards
Posted

1. What would be the point? Enumerations are simply an easy way to refer to a group of inter-related constants or flags. I'm not sure I can think of a reason that you would want to use a generic enumeration, since you can declare an enumeration as any value type, like:

C#
enum MyEnum : int
{
  ...
}


2. Classes and methods don't always encapsulate algorithms. Classes are there for the purpose of Object Oriented Programming. You define objects and give those objects properties and behaviors (methods). The only thing you can say about generics is that you don't have to define the type of data that the object operates on until runtime. Obviously if you have a generic method or class, and you use a generic type inside that method or class, you can say that the class or method itself is generic, but that doesn't mean that the data you passed into it is generic.

For example, if I have a generic method MyMethod<T>(T value) whatever I pass in for value is not considered generic, the method is. Its not to say that T couldn't be a generic type in-itself (like List<string>), but it doesn't automatically mean that it is.

3. An indexer is a method for iterating through data that the type contains. Most collections contain some kind of indexer. Its relation to generics is not direct, the type that defines the indexer may be generic, but the return value of an indexer is not a generic type, its whatever data the collection class contains when the collection types were defined. The presence of an indexer does not mean that the containing type is a generic, for example value array types have indexers and are not generic.

4. I'm really not sure what you mean by this, do you mean interfaces? There is no such thing as a "virtual class", there are abstract classes that define virtual methods, but no virtual classes. Either way, the presence or absence of a type inheritance chain has little to no effect on the performance of the child classes.

5. Please reference where you read that, but I would say "don't believe everything you read on the internet". We don't have non-generic classes just for backwards compatibility, there are some real reasons to use non-generic classes yet, and the generic classes are typically built on non-generic ones. The .NET framework has evolved for a reason, its built on the stepping stones of the versions before it.
 
Share this answer
 
v4
Comments
CPallini 4-Jan-14 16:34pm    
My 5.
Ron Beyer 4-Jan-14 17:41pm    
Thanks
BillWoodruff 4-Jan-14 22:58pm    
Excellent, Ron ! +5
Ron Beyer 4-Jan-14 23:23pm    
Thanks Bill.
Rahul VB 5-Jan-14 14:32pm    
Respected Sir,
In the 4th point i just wanted to ask: that how does having less virtual methods increase the performance. I am actually reading CLR via C# by Jefrey Ritcher, so some things just went over my head. While reading i make points about the topics i dont understand. May by i am unable to express my questions properly. Thanks for reading out and patiently answering my questions.

Thanks a lot,
Rahul
First of all: there are always design decisions also for language design, runtime environments, etc. From that perspective, the "why" question is often simply answered by "since the people in charge felt it is a good decision - or they did not think of it to be useful" ;-)

I have several items I'd love to have in C#/CLR, but they do not exist - so I have to work around or simply live with the current state of it.
- real RAII support
- better generic constraint support
- generic properties
- static interface methods
- ...

You can view generic concept as code generators: you write *one* template construct that generates usable code when parametrized with real types.
Generics allow to reduce copy-paste code. Instead of writing e.g. a Stack class for int, string, MyElement class, etc., a generic Stack class provides all the useful functions of a Stack, for any concrete type - *once for all*!

The early C# versions did not provide generics support, but only the awkward object-based version, which always required down-casting (BTW, I consider casting a code-smell in most of the cases).

To your questions:

  1. counter question: any good example for a generic enum type definition and usage?
  2. as mentioned above: it's you deciding if you consider some code to be useful to be parameterized by generics - containers are a good example where it is useful
  3. C# (like any other programming language) usually provide some syntactic-sugar[^] to write more expressive code. Properties, indexers, (un)registring to events, constructors, destructors are special functions that get translated into some underlaying functions that have reserved names (Property: get_Property/set_Property, Indexer: get_Item/set_Item, Event: add_Event/remove_Event, Constructor: .ctor/.cctor, Destructor: .dtor. You cannot declare these special functions as generics - they can only be part of some outer generic definition (e.g. a generic class can contain properties, but a single property cannot be defined with it's own generic parameters since the syntax does not allow for this and not because it would not make sense - this was a language design decision).

    For your question on indexer: you are free to *not* define an indexer in your class, but instead define two methods (e.g. TElement getAt(int pos);/void setAt(int pos, TElement item);).
  4. This is a weird question: you might want to re-phrase to make it more clear. What aspect of performance are you concerned about? As mentioned above, generic classes are code generators: write once, use multiple (parametrized by type). Inheritance or implementing interfaces (is this what you mean by "virtual classes"?) have no runtime speed impact (if this is what you mean by "performance") - except first time JIT compiling when other assemblies have to be loaded.
  5. The cited phrase does not make sense, please give a link to the original document. The designers of C# seem to have put some effort in supporting generic containers also for older C# code. So, they decided that a generic List class *implements* the generic as well as the non-generic IList *interfaces* (as well as other generic and non-generic interfaces).


Cheers
Andi
 
Share this answer
 
v5
Comments
BillWoodruff 5-Jan-14 0:16am    
+5 Very eloquent, and thoughtful, response !
Andreas Gieriet 5-Jan-14 7:52am    
Thanks for your 5!
Cheers
Andi
Rahul VB 5-Jan-14 11:31am    
Respected Sir,
Very nice, thanks a lot.

Thanks and Regards,
Rahul
Doubts are good ! When you stop having doubts, it is time to worry :)

I'll add a few thoughts here to the excellent responses of Ron and Andreas, but, first, a few general comments on what I believe is helpful in learning, and achieving mastery of, a programming language like C# in its "context" in the .NET FrameWork, and specific technology stacks, like Windows Forms, or WPF, and as a context for what can be loosely described as "object-oriented programming."

... begin sermon ...

You can spend a lot of time studying a programming language from "the top down," looking at how it implements what every programming language must implement ... flow-of-control ... conditional branching ... data storage and retrieval, transformation of data, re-usable components, etc.

And, you can easily become confused by the complexity of the implementation of something like C# and come to believe there are "principles" you don't understand that must explain what you see, and experience, as the quirks (or even contradictions) in the implementation.

Well, the problem is that there's lots of quirks :). And many of them just reflect the design decisions of the language creators, and the build-up of layer-after-layer of added-on features, and extensions.

The "danger" of "top-down" study is that you may waste a lot of time learning everything about the horse, its evolution, its anatomy, horse diseases, etc., but not be able to ride it, well.

Is it possible that you are somewhat over-concerned at this point with figuring out what it all means rather than getting-on with learning how to use it ?

... end of sermon ...

1)Why does CLR not allow the creation of generic enumerations?

This is like asking why chickens have feathers rather than hides like a crocodile, and can't sing like the bulbul: because the language evolved that way, by design. Enumerations are designed to be a "lightweight" grouping of named Constants for utility purposes, and they have a special functionality available, if used with the Flags Attribute, for bit-wise operations.

Specifically, Enums are designed to be compile-time Constants, and must be initialized where they are declared.

2)Classes encapsulate algorithms which can be applied on types so we have generic classes, similarly methods can also encapsulate algorithms so we can have generic methods(Correct me if i am wrong). So can i say that which ever entity that is subjected to an algorithm can be treated as a generic entity?

The word "algorithm" comes to us from the name of the great 16th. century Baghdad mathematician, Al Khwarazimi, mis-translated (confused with the Greek root ἀριθμός) in the so-called "Middle Ages" in Europe. It has been "re-purposed" in modern times to mean a systematic method for solving (or converging on a solution for) certain problems which are logical, as well as, mathematical.

Now that the word "algorithm" has moved into wide popular usage, outside mathematics, and computer science, the term has become "overlayed" with all kinds of cultural "baggage," and its meaning is less "distinct."

You can say that Classes, and computer Applications as a whole, express algorithms, use algorithms, implement algorithms.

I see no connection between the topic of algorithms and the specific computer-science programming language construct of "generic classes."

Perhaps it's valuable to think of the difference between a "method," and a "technique" ?

3)What is an indexer method? How does it qualify to become a generic method?

... revised based on Ron Beyer's comment ...

A method of supplying a means for access (sequential or random) via the special syntax [] to some Class/Struct, etc., you wish to "behave like" other .NET objects that use the [] syntax like: Array, List, string, etc.

I see no relevant connection between "indexer" and the general topic of generic methods. .NET supplies many objects which have

A custom indexer can be as simple as defining one extension method, as shown here: [^].

I can't make sense of your question which asks about how an indexer method it "becomes" a generic method. Are you thinking that an extension method is a generic method ?

4)Generics dont have many virtual classes. How does having a fewer virtual classes increase the performance of generic entities?

I see no connection between "virtual classes" and "generics:" not clear, to me, what you are asking about.

5)We have both generic and non generic interface for backward compatibility, actually speaking i read a sentence which states the reason for backward compatibility : It goes like this:

.NET evolved: new features were added, but the old features the new features extended, or enriched, were kept for compatibility: so old code won't break. This is absolutely the way that software, and programming languages, and operating systems, evolve: they are all (for better, and for worse) forced to support legacy code.

"If the List class implemented only the IList interface, no code could consider a List object an IList.". I couldnt understand the meaning of this statement."

The Generic List facilities in .NET 2.0 implement all kinds of Interfaces:

IList<T>, ICollection<T>, IEnumerable<T, IList, ICollection, IEnumerable

Those are choices the language designers made, but, you are not alone in asking (at least I think you are asking): why couldn't IList ... which implements some of the same Interfaces ... have been used without some of the other inherited Interfaces ?

If you really want to explore the deep black-hole of this particular "why," then I suggest you read Eric Lippert's (key member of the .NET team for many years, and a guru's guru) blog entry on the topic: [^].

best wishes for your continued progress !
 
Share this answer
 
v5
Comments
Ron Beyer 5-Jan-14 0:03am    
Very nice Bill, the only thing I would bring into question would be that indexers "provide sequential, ordered access"... I would point to the use of an indexer on a Hashtable, or Dictionary for example, or even a normal indexer; they provide random access, its only coincidence that we typically use them in order :) +5
BillWoodruff 5-Jan-14 0:14am    
That's a damn good point, Ron. It's interesting that my "instinct" is not to perceive accessing the Value of a Generic Dictionary KeyValuePair instance via [] as being indexing in the same sense as accessing a List<whatever> value by [] :)

I have had some students who were quite confused by the dual-purpose aspect of the [] syntax in C#, so this should be something I am aware of !
Rahul VB 5-Jan-14 14:42pm    
Respected Sir,
The 4th point where i said "virtual classes" i wanted to say : virtual methods not classes. I am sorry about that, my doubts about generics might be strange, may be i have not completely understood what i have read. May be a revision is required of my reading so that i can understand more properly. I am reading from : CLR via C# by Jefrey Ritcher 3rd edition: the statement :
"If the List class implemented only the IList interface, no code could consider a List object an IList: is given in the same book on page number 281 in the 3rd and 4th lines. I request you to kindly go through it when you find time.

Thanks a lot,
Rahul
Andreas Gieriet 5-Jan-14 7:51am    
Very good and elaborate answer! My 5!
Cheers
Andi
Rahul VB 5-Jan-14 11:32am    
Respected Sir,
Very nice, thanks a lot.

Thanks and Regards,
Rahul

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900