views:

140

answers:

4
+2  Q: 

C# -Generics Help

Just i started learning Collection and Generics in C# .I visited MSDN resource page.It directed me to lot of sub pages ,i was going page after page,finally got confused.

Can anybody help me where to start and what are the essential things to learn bot about collection (non-generics) and generics?.

MSDN articles are dragging me by putting many links !!!!!!!!

+1  A: 

This link has excellent collection:

http://www.c-sharpcorner.com/Forums/ShowMessages.aspx?ThreadID=48031

P.K
+2  A: 

For a really brief explanation: Regular collections store objects. The system doesn't know what kind of object is stored, so you have to cast them to the desired type when you work with them. Generic collections declare what kind of object is being put in at the time you create it. Then you always know what is there. it's like the difference between an object array and a String array.

I would definitely check out the list of links on the page PK posted for a more thorough understanding.

sql_mommy
+2  A: 

I also recommend the following book which has pretty much all the details you could want on Generics in .NET 2.0 onwards, including Generic classes, methods, delegates and constraints, how they differ from C++ templates, and the generics in the BCL.

Russ Cam
+1  A: 

1) Classes can be defined with a generic type.

 public class MyClass<TClass>

2) The types can be constrained using this syntax.

where TClass: struct

3) Methods also can gave generic types.

public TMethod ConvertTo<TMethod>()

4) Full Example

public class MyClass<TClass> where TClass: struct
{
    private TClass _Instance;

    public MyClass(TClass instance)
    {
        _Instance = instance;
    }

    public TMethod ConvertTo<TMethod>()
    {
        return (TMethod)Convert.ChangeType(_Instance, typeof(TMethod));
    }
}
ChaosPandion
This is a good example of beginning generics, but should it be encouraged to reinvent the wheel with so many explanations out there?
Yuriy Faktorovich