Click to See Complete Forum and Search --> : generics
mickey0
July 21st, 2008, 07:05 PM
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,
RaleTheBlade
July 21st, 2008, 07:17 PM
C# does permit generic methods. Something like this:
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.
Arjay
July 21st, 2008, 07:34 PM
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 (http://www.codeguru.com/forum/showthread.php?t=457626&page=2).
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):
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.
mickey0
July 22nd, 2008, 03:47 AM
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,
boudino
July 22nd, 2008, 03:58 AM
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.
mickey0
July 22nd, 2008, 06:52 PM
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,
Arjay
July 22nd, 2008, 08:05 PM
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.
Ahmish
July 22nd, 2008, 11:38 PM
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;
}
boudino
July 23rd, 2008, 01:12 AM
Definitelly.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.