These types of methods have always bothered me. Without digging through the code, I have no idea what the key or sub-value is supposed to be in this dictionary. I've done this myself about a thousand times, I'm sure. But it has always bothered me because it lacks so much information.
IDictionary<int,HashSet<int>> GetExportedCharges()
{
...
}
void GetVisitStatuses(IDictionary<int,HashSet<int>> exportedCharges)
{
...
}
Having the material in a dictionary makes sense, but all of the IDictionary methods have very abstract parameters. I suppose I could create a new class, implement IDictionary, and rename all of the parameters. It just seems like overkill. Makes be wish c# had a 'typdef' directive.
How do you avoid returning dictionaries like this? Or do you avoid this at all?
There is a very simple solution that you might find adequate:
public class IdToSetOfWidgetNumbersMap : Dictionary<int,HashSet<int>> { }
Advantages:
Seeing a method returning an IdToSetOfWidgetNumbersMap doesn't leave many questions open
The class can be left totally empty, or you can choose to provide aliases for the members exposed by Dictionary if you prefer
Disadvantage:
You need to create a do-nothing class for each type of dictionary
Personally I don't avoid returning dictionaries.
I agree, having only method signature it all looks very vague. So my rule is to ALWAYS write comments in a style "Dictionary (logical description of the keys) - (logical description of values)". And to hope that I will not need to use something horrible like
Dictionary<SomeType, <Dictionary<...>>
Related
First just to clarify and avoid unnecessary duplicate tagging, this question is not a duplicate of this one, neither a duplicate of this other one or others I have already searched. Why? they all talk about public fields or private fields WITH the classical C#'s "properties".
My question is why should I write something like this (Public Properties)
class myClass{
public int AValue{get; set;}
}
when I can write instead (Private fields without any properties involved) (Just classic old C++ style way of writing things)
class myClass{
private int aValue;
public int getValue{ return aValue;}
public void setValue(int value){ aValue=value;}
I am scratching my head, reading many many resources, answers and questions, and no one of them answer this question. They all talk about the advantages over public fiels (which I am not asking about) or about the advantages of the new automatic properties over the old ones (which I am not asking either).
I guess my question is why C# does not use the same way of writing that has worked well in Java or C++ that works well. I don't see any advantage. I would very much appreciate someone teaches me the advantage because afaik is not written anywhere else. (not even in my C# books)
From my understanding the public properties that you are referring to are merely syntactic sugar wrapping the pattern that you describe above.
It comes down to readablity and platform standards I guess. While there is nothing wrong with the way that you are talking about, we also need to consider maintainability. To another .Net developer, that pattern does not fit what they are used to and could cause confusion.
And the there is the superficial reason, it is just a lot more code to write. Especially when you have something like a DTO.
The properties in c# are further encapsulated and eventually translated into an intermediate language of a private field and the corresponding Get Set method, so you don't have to be bothered
Auto-accessors are syntactical sugar for exactly that. The generated code has a backing field and get/set methods. Fields don't have accessors, whereas properties do.
Public/private is about encapsulation/security, i.e. who should be able to access your information.
In the way you presented it (writing get and set method) is good, but you have two methods - one for setting the value of the field and one for getting this value. Using properties, it's more natural to me, since you "encapsulate" set and get method under one name and accessing it is better this way (in my opinion).
The main reason for using public int AValue { get; set; } instead of a private field and a getAValue and setAValue pair of functions is that that's just the way that things are done in C#. From a "what the code does at runtime" perspective, the two are pretty much the same as an "auto property" (the type of property you've got where you let the compiler take care of generating a private backing field) compiles down into code very similar to that which you've written (see this stackoverflow questions accepted answer for an example).
The main "advantage" in the context of your question (why use a property instead of a field and a get/set pair of methods) is predictability and comprehensibility. Anyone who's working with your code will expect to see properties, rather than a private field/get/set implementation and thus your code will be more immediately comprehensible to them. Seeing it implemented differently will cause them to question why, assume that there's a reason for it and thus slow them down when it comes to understanding your code.
C#'s getter and setter is syntactic sugar, which remove noisy method names (SetValue or GetValue vs just Value) and increase readability of the code.
Readability is much better in consuming code
// Without properties
var myClass = new MyClass();
myClass.SetAValue(aValue);
myClass.SetBValue(bValue);
//And with properties
var myClass = new MyClass
{
AValue = aValue,
BValue = bValue
}
Because it is only syntactic sugar - every developer/team are free to not use
it.
Some teams have "rules" that properties should be used only for getting/setting values without any "heavy" logic in getters/setters. And methods should be used for setting or getting values which executes some "heavy" operations.
I'm curious as to the difference between these two methods. I'm implementing a decorator pattern with open generics and whether I use AddAllTypesOf or ConnectImplementationsToTypesClosing it doesn't matter, I get the same functionality.
public class CommandRegistry : Registry
{
public CommandRegistry()
{
For<CommandProcessor>().Use<DefaultCommandProcessor>().Transient();
Scan(scanner =>
{
scanner.AssemblyContainingType<SaveCoolCommandHandler>();
//scanner.AddAllTypesOf(typeof(CommandHandler<>));
//scanner.AddAllTypesOf(typeof(IValidator<>));
//scanner.AddAllTypesOf(typeof(LogMehh<>));
scanner.ConnectImplementationsToTypesClosing(typeof(CommandHandler<>));
scanner.ConnectImplementationsToTypesClosing(typeof(IValidator<>));
scanner.ConnectImplementationsToTypesClosing(typeof(LogMehh<>));
});
var handlerType = For(typeof(CommandHandler<>));
handlerType.DecorateAllWith(typeof(CommandValidator<>)); //Second
handlerType.DecorateAllWith(typeof(CommandLogger<>)); //First
// ObjectFactory.WhatDoIHave();
}
}
The call to ObjectFactory.WhatDoIHave() also gives me the same results no matter which method I choose.
I've looked at the source code and these methods are definately doing different things, I just haven't been able to determine exactly what the difference is. Are there any guidelines or scenarios when one is preferred over the other?
Caveat: I haven't used StructureMap in a commercial project for several years now. Things may have changed since then, but your example code looks completely familiar so I am guessing it hasn't changed much.
The only reason I'm aware of where you'll want to favour one over the other is when you want to explicitly define the convention(s) which will be used for mapping concrete implementations to T. Both can do it but the robustness of the implementation differs.
If you use ConnectImplementationsToTypesClosing<T>, during the Scan() setup you pass in a convention class which inherits from IRegistrationConvention. For me at least it just worked without any hassles.
AddAllTypesOf<T> supposedly has similar functionality through ITypeScanner but in practice we had all sorts of weird issues with it like duplicate type registrations, types not getting registered if in a different namespace from T, and often not finding the specific implementations they were supposed to. These problems all went away when using ConnectImplementationsToTypesClosing<T>.
If you aren't trying to do anything too clever and the default conventions work for you, you should notice no difference between the two. If you need to override the default conventions for any reason I would strongly favour ConnectImplementationsToTypesClosing<T>.
Is there a sane way in C# to achieve the following construct (in pseudocode):
void Method(MyClass<Attribute1, Attribute2, ...> foo)
{
// here I am guaranteed that foo has the specified attributes
}
Where Attribute* are, for example, enum values, such that only instances of MyClass instantiated with the attributes required by the method can be passed to the method (and otherwise fail to compile)?
I tried looking at generics since I know that C++ templates can make this work so it seemed like a logical starting point, but I couldn't get it working elegantly (I tried using interfaces to constrain the types of the parameter in this fashion but it was very bulky and frankly unusable since I have at least 4 attributes).
I want to do this to avoid having lots of annoying checks at the beginning of each method. I am doing DirectX 11 graphics development so I am kind of constrained by the API which does not make it particularly easy to pass objects around in this "type-safe" manner (in DirectX every resource has a large "Description" structure which contains information about what the resource can and cannot do, is and is not, etc.. and is tedious and error-prone to parse, so I am trying to write a wrapper around it for my and my users' convenience).
I also cannot have different class types for every case because there are a lot of combinations, so this seems like the most comfortable way to write code like this, and I am hoping C# makes this possible.
I'm sure there is a name for this kind of language feature (if you know it please let me know, I would have googled but this is kind of hard to search for when you don't know the proper keywords...)
Generic type parameters in .NET must be types themselves. You can't create a generic type/method that is specific to a particular value of the Generic type parameter only.
If you do not want or cannot create a type that represents the attribute values you want your method being restricted to, you will have to do sanity checks in your method to ensure that the proper attribute values are used in the provided "foo" object.
Using specific types as representation of specific attribute values might be an answer for the problem you asked about, but it has the disadvantage of not supporting switch-case statements (see further below). Please also read the final note at the end of my answer.
Say, you want a type that represents textures. Textures can have different number of channels, and different bit depths. You could then declare a generic texture type like this:
class Texture<TChannels, TBPC>
where TChannels : INumOfChannels,new()
where TBPC : IBitsPerChannel,new()
INumOfChannels and IBitsPerChannel are just interfaces and can be empty.
The new() constraint prevents creation of a concrete Texture type by using the interfaces themselves.
For different channels and different BPCs, you will create empty types extending from the respective base interfaces, for example:
class FourChannels : INumOfChannels {};
class ThreeChannels : INumOfChannels {};
class BitsPerChannel_24 : IBitsPerChannel {};
class BitsPerChannel_32 : IBitsPerChannel {};
Using this, you can restrict your generic method to certain attribute combinations. In case your method should only deal with 4-channel and 32bpc textures:
void MyMethod<TChannels, TBPC>(Texture<TChannels, TBPC> foo)
where TChannels : FourChannels
where TBPC : BitsPerChannel_32
Now, every good thing also has dark sides. How would you do something like this (written as pseudo-code)?
switch (NumOfChannelsAttribute)
{
case FourChannels:
// do something
break;
case ThreeChannels:
// do something else
break;
}
You can't, at least not in an easy and simple way, because "FourChannel" and "ThreeChannel" are types, not integral values.
Of course, you can still use if constructs. For this to work you would need to implement a property in the generic texture type which provides the used attributes:
class Texture<TChannels, TBPC> where TChannels : INumOfChannels,new() where TBPC : IBitsPerChannel,new()
{
public Type ChannelsAttribute
{
get { return typeof(TChannels); }
}
public Type BitsPerChannelAttribute
{
get { return typeof(TBPC); }
}
}
In an if construct, you could utilize this as follows:
var myTex = new Texture<FourChannels, BitsPerChannel_32>();
if (myTex.ChannelsAttribute == typeof(FourChannels))
{
... do something with 4 channels
}
else
{
... though luck, only 4 channels are supported...
}
A final note and advice:
While this might work for your problem, resorting to these kind of 'tricks' usually is an indication of a flawed design. I think it is well-invested time if you revisit the design choices you made in your code, so you don't need to rely on crutches like this.
C# doesn't have such a feature. You mention you have tried using interfaces, but don't specify how. The way I'd suggest you try using them is by using generics with multiple constraints, eg
void Method(T foo) where T : IAttribute1, IAttribute2, IAttribute3, IAttribute4
{
}
Let's say one such attribute class is then ICpuMappable, then you can constrain types that can be used with Method1 with:
void Method1(T foo) where T : ICpuMappable
{
}
and you can know any foo passed to Method1 is CPU mappable.
You'll likely end up with lots of interfaces, but as many will be treated as "flags", they shouldn't be too difficult to maintain.
We recently learned about generic classes in C#, but our teacher failed to mention what they can be used for. I can't really find any good examples and would be extremly happy if somebody help me out :)
Have you made your own generic class, and what did you use it for?
Some code examples would make me, and my classmates, really happy! Pardon the bad english, I am from sweden :)
happy programming!
Sorry- I think I could have written the question a bit better. I am familar with generic collections. I just wondered what your own generic classes can be used for.
and thank you for the MSDN links, I did read them before posting the question, but maybe I missed something? I will have a second look!
Generic Collections
Generics for collections are very useful because they allow compile time type safety. This is useful for a few reasons:
No casting is required when retreiving values. This is not only a performance benefit but also eliminates the risk of there being a casting exception at runtime
When value types are added to a non generic list such as an ArrayList, the value's have to be boxed. This means that they are stored as reference types. It also means that not only does the value get stored in memory, but so does a reference to it, so more memory than necessery is used. This problem is eliminated when using generic lists.
Generic Classes
Generic classes can be useful for reusing common code for different types. Take for example a simple non generic factory class:
public class CatFactory
{
public Cat CreateCat()
{
return new Cat();
}
}
I can use a generic class to provide a factory for (almost) any type:
public class Factory<T> where T : new()
{
public T Create()
{
return new T();
}
}
In this example I have placed a generic type constraint of new() on the type paramter T. This requires the generic type to contain a parameterless contructor which enables me to create an instance without knowing the type.
Just because you said you are Swedish, I thought I'd give an example integrating IKEA furniture. Your kit couches are an infestation in north america, so I thought I'd give something back :) Imagine a class which represents a particular kit for building chairs and tables. To remain authentic, I'll even use nonsense swedish linguistic homonyms:
// interface for included tools to build your furniture
public interface IToolKit {
string[] GetTools();
}
// interface for included parts for your furniture
public interface IParts {
string[] GetParts();
}
// represents a generic base class for IKEA furniture kit
public abstract class IkeaKit<TContents> where TContents : IToolKit, IParts, new() {
public abstract string Title {
get;
}
public abstract string Colour {
get;
}
public void GetInventory() {
// generic constraint new() lets me do this
var contents = new TContents();
foreach (string tool in contents.GetTools()) {
Console.WriteLine("Tool: {0}", tool);
}
foreach (string part in contents.GetParts()) {
Console.WriteLine("Part: {0}", part);
}
}
}
// describes a chair
public class Chair : IToolKit, IParts {
public string[] GetTools() {
return new string[] { "Screwdriver", "Allen Key" };
}
public string[] GetParts() {
return new string[] {
"leg", "leg", "leg", "seat", "back", "bag of screws" };
}
}
// describes a chair kit call "Fnood" which is cyan in colour.
public class Fnood : IkeaKit<Chair> {
public override string Title {
get { return "Fnood"; }
}
public override string Colour {
get { return "Cyan"; }
}
}
public class Snoolma : IkeaKit<Chair> {
public override string Title {
get { return "Snoolma "; }
}
public override string Colour {
get { return "Orange"; }
}
}
Ok, so now we've got all the bits we need to figure out how to build some cheap furniture:
var fnood = new Fnood();
fnood.GetInventory(); // print out tools and components for a fnood chair!
(Yes, the lack of instructions and the three legs in the chair kit is deliberate.)
Hope this helps in a cheeky way.
If one has a List object (non-generic), one can store into it anything that can be cast into Object, but there's no way of knowing at compile time what type of things one will get out of it. By contrast, if one has a generic List<Animal>, the only things one can store into it are Animal or derivatives thereof, and the compiler can know that the only things that will be pulled out of it will be Animal. The compiler can thus allow things to be pulled out of the List and stored directly into fields of type Animal without any need for run-time type checking.
Additionally, if the generic type parameter of a generic class happens to be a value type, use of generic types can eliminate the need for casting to and from Object, a process called "Boxing" which converts value-type entities into reference-type objects; boxing is somewhat slow, and can sometimes alter the semantics of value-type objects, and is thus best avoided when possible.
Note that even though an object of type SomeDerivedClass may be substitutable for TheBaseClass, in general, a GenericSomething<SomeDerivedClass> is not substitutable for a GenericSomething<TheBaseClass>. The problem is that if one could substitute e.g. a List<Giraffe> for a List<Zebra>, one could pass a List<Zebra> to a routine that was expecting to take a List<Giraffe> and store an Elephant in it. There are a couple of cases where substitutability is permitted, though:
Arrays of a derived type may be passed to routines expecting arrays of base type, provided that those routines don't try to store into those arrays any items that are not of the proper derived type.
Interfaces may be declared to have "out" type parameters, if the only thing those interfaces will do is return ("output") values of that type. A Giraffe-supplier may be substituted for an Animal-supplier, because all it's going to do is supply Giraffes, which are in turn substitutable for animals. Such interfaces are "covariant" with respect to those parameters.
In addition, it's possible to declare interfaces to declare "in" type parameters, if the only thing the interfaces do is accept parameters of that type by value. An Animal-eater may be substituted a Giraffe-eater, because--being capable of eating all Animals, it is consequently capable of eating all Giraffes. Such interfaces are "contravariant" with respect to those parameters.
The most common example is for collections such as List, Dictionary, etc. All those standard classes are implemented using generics.
Another use is to write more general utility classes or methods for operations such as sorting and comparisons.
Here is a Microsoft article that can be of help: http://msdn.microsoft.com/en-us/library/b5bx6xee%28v=vs.80%29.aspx
The largest benefit that I've seen is the compile-time safety of generics, as #Charlie mentioned. I've also used a generic class to implement a DataReader for bulk inserts into a database.
Well, you have a lot of samples inside the framework. Imagine that you need to implement a list of intergers, and later a list of strings... and later a list of you customer class... etc. It would be very painfull.
But, if you implements a generic list the problem is solved in less time, in less code and you only have to test one class.
Maybe one day you will need to implement your own queue, with rules about the priority of every element. Then, it would be a good idea to make this queue generic if it is possible.
This is a very easy sample, but as you improve your coding skills, you will see how usefull can be to have (for example) a generic repository (It's a design patters).
Not everyday programmers make generic classes, but trust me, you will be happy to count with such tool when you need it.
real world example for generics.
Think u have a cage where there are many different birds(parrot,pegion,sparrow,crow,duck) in it(non generic).
Now you are assigned a work to move the bird to seperate cages(specifically built for single bird) from the cage specified above.
(problem with the non generic list)
It is a tedious task to catch the specific bird from the old cage and to shift it to the cage made for it.(Which Type of bird to which cage --Type casting in c#)
generic list
Now think you have a seperate cage for seperate bird and you want to shift to other cages made for it. This will be a easy task and it wont take time for you to do it(No type casting required-- I mean mapping the birds with cages).
My friend is not a programmer and I would like to explain what is generics? I would explain him generics as below. Thus this is a real-world scenario of using generics.
"There is this manufacturer in the next street. He can manufacture any automobile. But at one instance he can manufacture only one type of automobile. Last week, he manufactured a CAR for me, This week he manufactured a TRUCK for my uncle. Like I said this manufacturing unit is so generic that it can manufacture what the customer specifies. But note that when you go to approach this manufacturer, you must go with a type of automobile you need. Otherwise approaching him is simply not possible."
Have a look at this article by Microsoft. You have a nice and clear explanation of what to use them for and when to use them. http://msdn.microsoft.com/en-us/library/ms172192.aspx
The various generic collections are the best example of generics usage but if you want an example you might generate yourself you could take a look at my anwer to this old question:
uses of delegates in c or other languages
Not sure if it's a particularly great example of generics usage but it's something I find myself doing on occasion.
Are you talking about a base class (or perhaps an abstract class)? As a class that you would build other classes (subclasses) off of?
If that's the case, then you'd create a base class to include methods and properties that will be common to the classes that inherit it. For example, a car class would include wheels, engine, doors, etc. Then maybe you'd maybe create a sportsCar subclass that inherits the car class and adds properties such as spoiler, turboCharger, etc.
http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)
enter link description here
It's hard to understand what you mean by "generic class" without some context.
I know the answer is not going to be simple, and I already use a couple of (I think ugly) cludges. I am simply looking for some elegant answers.
Abstract class:
public interface IOtherObjects;
public abstract class MyObjects<T> where T : IOtherObjects
{
...
public List<T> ToList()
{
...
}
}
Children:
public class MyObjectsA : MyObjects<OtherObjectA> //(where OtherObjectA implements IOtherObjects)
{
}
public class MyObjectsB : MyObjects<OtherObjectB> //(where OtherObjectB implements IOtherObjects)
{
}
Is it possible, looping through a collection of MyObjects (or other similar grouping, generic or otherwise) to then utilise to ToList method of the MyObjects base class, as we do not specifically know the type of T at this point.
EDIT
As for specific examples, whenever this has come up, I've thought about it for a while, and done something different instead, so there is no current requirement. but as it has come up quite frequently, I thought I would float it.
EDIT
#Sara, it's not the specific type of the collection I care about, it could be a List, but still the ToList method of each instance is relatively unusable, without an anonymous type)
#aku, true, and this question may be relatively hypothetical, however being able to retrieve, and work with a list of T of objects, knowing only their base type would be very useful. Having the ToList returning a List Of BaseType has been one of my workarounds
EDIT # all: So far, this has been the sort of discussion I was hoping for, though it largely confirms all I suspected. Thanks all so far, but anyone else, feel free to input.
EDIT#Rob, Yes it works for a defined type, but not when the type is only known as a List of IOtherObjects.
#Rob Again Thanks. That has usually been my cludgy workaround (no disrespect :) ). Either that or using the ConvertAll function to Downcast through a delegate. Thanks for taking the time to understand the problem.
QUALIFYING EDIT in case I have been a little confusing
To be more precise, (I may have let my latest implementation of this get it too complex):
lets say I have 2 object types, B and C inheriting from object A.
Many scenarios have presented themselves where, from a List of B or a List of C, or in other cases a List of either - but I don't know which if I am at a base class, I have needed a less specific List of A.
The above example was a watered-down example of the List Of Less Specific problem's latest incarnation.
Usually it has presented itself, as I think through possible scenarios that limit the amount of code that needs writing and seems a little more elegant than other options. I really wanted a discussion of possibilities and other points of view, which I have more or less got. I am surprised no one has mentioned ConvertAll() so far, as that is another workaround I have used, but a little too verbose for the scenarios at hand
#Rob Yet Again and Sara
Thanks, however I do feel I understand generics in all their static contexted glory, and did understand the issues at play here.
The actual design of our system and usage of generics it (and I can say this without only a touch of bias, as I was only one of the players in the design), has been done well. It is when I have been working with the core API, I have found situations when I have been in the wrong scope for doing something simply, instead I had to deal with them with a little less elegant than I like (trying either to be clever or perhaps lazy - I'll accept either of those labels).
My distaste for what I termed a cludge is largely that we require to do a loop through our record set simply to convert the objects to their base value which may be a performance hit.
I guess I was wondering if anyone else had come across this in their coding before, and if anyone had been cleverer, or at least more elegant, than me in dealing with it.
why do you have a collection of MyObjects? Is there a specific reason you don't have a List?
In your case MyObjectsA and MyObjectsB don't have common predecessor. Generic class is template for different classes not a common base class. If you want to have common properties in different classes use interfaces. You can't call ToList in a loop cause it has different signature in different classes. You can create ToList that returns objects rather than specific type.
If you have
class B : A
class C : A
And you have
List<B> listB;
List<C> listC;
that you wish to treat as a List of the parent type
Then you should use
List<A> listA = listB.Cast<A>().Concat(listC.Cast<A>()).ToList()
You can still probably access the ToList() method, but since you are unsure of the type, won't this work?
foreach(var myObject in myObjectsList)
foreach(var obj in myObject.ToList())
//do something
Of course this will only work on C# 3.0.
Note that the use of var is merely to remove the requirement of knowing what type the lists contain; as opposed to Frank's comments that I have delusions that var will make typing dynamic.
OK, I am confused, the following code works fine for me (curiosity got the better of me!):
// Original Code Snipped for Brevity - See Edit History if Req'd
Or have I missed something?
Update Following Response from OP
OK now I am really confused..
What you are saying is that you want to get a List of Typed values from a generic/abstract List? (the child classes therefore become irrelevant).
You cannot return a Typed List if the Types are children/interface implementors - they do not match! You can of course get a List of items that are of a specific type from the abstract List like so:
public List<OfType> TypedList<OfType>() where OfType : IOtherObjects
{
List<OfType> rtn = new List<OfType>();
foreach (IOtherObjects o in _objects)
{
Type objType = o.GetType();
Type reqType = typeof(OfType);
if (objType == reqType)
rtn.Add((OfType)o);
}
return rtn;
}
If I am still off-base here can you please reword your question?! (It doesn't seem like I am the only one unsure of what you are driving at). I am trying to establish if there is a misunderstanding of generics on your part.
Another Update :D
Right, so it looks like you want/need the option to get the typed List, or the base list yes?
This would make your abstract class look like this - you can use ToList to get the concrete type, or ToBaseList() to get a List of the interface type. This should work in any scenarios you have. Does that help?
public abstract class MyObjects<T> where T : IOtherObjects
{
List<T> _objects = new List<T>();
public List<T> ToList()
{
return _objects;
}
public List<IOtherObjects> ToBaseList()
{
List<IOtherObjects> rtn = new List<IOtherObjects>();
foreach (IOtherObjects o in _objects)
{
rtn.Add(o);
}
return rtn;
}
}
Update #3
It's not really a "cludgy" workaround (no disrespect taken) - thats the only way to do it.. I think the bigger issue here is a design/grok problem. You said you had a problem, this code solves it. But if you were expecting to do something like:
public abstract class MyObjects<T> where T : IOtherObjects
{
List<T> _objects = new List<T>();
public List<IOtherObjects> Objects
{ get { return _objects; } }
}
#warning This won't compile, its for demo's sake.
And be able to pick-and-choose the types that come out of it, how else could you do it?! I get the feeling you do not really understand what the point of generics are, and you are trying to get them to do something they are not designed for!?
I have recently found the
List<A>.Cast<B>().ToList<B>()
pattern.
It does exactly what I was looking for,
Generics are used for static time type checks not runtime dispatch. Use inheritance/interfaces for runtime dispatch, use generics for compile-time type guarantees.
interface IMyObjects : IEnumerable<IOtherObjects> {}
abstract class MyObjects<T> : IMyObjects where T : IOtherObjects {}
IEnumerable<IMyObjects> objs = ...;
foreach (IMyObjects mo in objs) {
foreach (IOtherObjects oo in mo) {
Console.WriteLine(oo);
}
}
(Obviously, I prefer Enumerables over Lists.)
OR Just use a proper dynamic language like VB. :-)