CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9

Thread: generics

  1. #1
    Join Date
    Jul 2007
    Posts
    273

    generics

    hello folk,

    Does anyone know if C# permits to declare generic methods ? How do they work, please? Could you give a simple example to understand, please?

    thanks,

  2. #2
    Join Date
    Jul 2007
    Location
    Illinois
    Posts
    517

    Re: generics

    C# does permit generic methods. Something like this:

    Code:
    private long GetLength<T>(T streamObject) where T : Stream
    {
       return streamObject.Length;
    }
    A generic method with a generic constraint. Not a very good example but I dont use generics that much, Im more into polymorphism and the like. If someone else has a better example, I hope they post it, but at least this one will help you see the syntax.
    R.I.P. 3.5" Floppy Drives
    "I know not with what weapons World War III will be fought, but World War IV will be fought with sticks and stones." - Albert Einstein

  3. #3
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: generics

    I'm not sure if this is a 'better' example, but here is some code that uses generics to help with the XmlSerializer class. It's part of a sample I created for this post.

    Code:
    public static class XmlHelper< T >
    {
        public static T Load( string fileName )
        {
            XmlSerializer serializer = new XmlSerializer( typeof( T ) );
    
            using( XmlReader reader = XmlReader.Create( fileName ) )
            {
                return ( T )serializer.Deserialize( reader );
            }
        }
    
        public static void Save( string fileName, T o )
        {
            XmlSerializer serializer = new XmlSerializer( typeof( T ) );
                
            XmlWriterSettings xws = new XmlWriterSettings( );
            xws.Indent = true;
    
            using( XmlWriter writer = XmlWriter.Create( fileName, xws ) )
            {
                serializer.Serialize( writer, o ); 
            }
        }
    }
    Generics in this class allow you to save and load any serializable class.

    It's used like this (notice how the class name is specified within the generic brackets):

    Code:
    private void buttonSave_Click( object sender, EventArgs e )
    {
        XmlHelper<Settings>.Save( "Settings.xml"
            , Settings.Create( _textBoxUserName.Text, _textBoxPassword.Text ) );
    }
    
    private void buttonLoad_Click( object sender, EventArgs e )
    {
        Settings settings = XmlHelper<Settings>.Load( "Settings.xml" );
    
        _textBoxUserName.Text = settings.UserName;
        _textBoxPassword.Text = settings.Password;
    }
    The static load method creates an XmlSerializer of type T (in this case a Settings object), reads the 'Settings.xml' file and deserializes it into a Settings object. When the Load method returns the object is cast to the proper type (i.e. Settings). Save works similarly where the type T object is again used to create the XmlSerializer.

  4. #4
    Join Date
    Jul 2007
    Posts
    273

    Re: generics

    mmmm so the "generics" refers only to class name? I'll try it but one more question: can this methods be virtual too? Does it make any sense?

    thanks,

  5. #5
    Join Date
    Mar 2004
    Location
    Prague, Czech Republic, EU
    Posts
    1,701

    Re: generics

    More precisely, "generics" refer to code parametrized by type. Generics improves maintability and readability of the code, but it doesn't offer significant new abilities. Is some situations, they can slightly improve performance.

    Generic methods can definitely be virtual.
    • Make it run.
    • Make it right.
    • Make it fast.

    Don't hesitate to rate my post.

  6. #6
    Join Date
    Jul 2007
    Posts
    273

    Re: generics

    The generics (in java and C#) implements ( I think) parametric polymorphism; In c++, parametric polym. is obtained with templates; Wich mechanism exploit java and C# to implements generics? Is it clear?

    thanks,

  7. #7
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: generics

    Quote Originally Posted by boudino
    Generics improves maintability and readability of the code, but it doesn't offer significant new abilities.
    I like the type safety that it provides. For example consider using a generic dictionary<Tkey, Tvalue> as compared to the older non-generic hashtable. The generic approach prevents accidently storing the wrong type into the container. If you tried to store a different type into the dictionary<> you'd get a compile error. With a hashtable, you would only get a runtime error.

  8. #8
    Join Date
    Jul 2008
    Posts
    3

    Exclamation Re: generics

    I have a very simple example of Generics method which i currently using, this method will must take an array of controls which are inherited from Control class(like webcontrol) and a second array of boolean to set the visible property of the controls.

    public static void SetVisibleControls<T>(T[] controlsArray, Boolean[] controlsVisibleValue) where T : Control
    {
    int i = 0;

    //If Length of both arrays is not equal then throws an exception

    if (controlsArray.Length != controlsVisibleValue.Length)
    throw new Exception("Both Arrays should contain equal elements in them or Both Arrays should be equal in length");

    //Iterate each object and set the visible property by getting the value from controlsVisibleProperty

    foreach (T obj in controlsArray)
    {
    obj.Visible = controlsVisibleValue[i];
    i += 1;
    }

  9. #9
    Join Date
    Mar 2004
    Location
    Prague, Czech Republic, EU
    Posts
    1,701

    Re: generics

    Definitelly.
    • Make it run.
    • Make it right.
    • Make it fast.

    Don't hesitate to rate my post.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured