Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Generics 1

Status
Not open for further replies.

Badgers

Programmer
Nov 20, 2001
187
US
Hi

I have a function below of which I want to make the second param a generic so I could pass in different data types.

private string GetElementText(ref XmlReader xmlReader, ref string nodeValue)
{

if (xmlReader.IsStartElement())
{
// Read to get the first child of the node
// and make sure it has no name
xmlReader.Read();
if (string.IsNullOrEmpty(xmlReader.Name))
{

nodeValue = FormatNodeValue(xmlReader.Value);
}
}
else
{
//By passing in nodeValue, if end of element then we donot overwrite it.
}

return nodeValue;
}

Thanks inadvance.
 
Just use "ref Object nodeValue" but later you'll have to cast and probably put in "if" statement to get typeof

If your talking about collections then yeah,

using System.Collections.Generic;
....ref List<oYourObject> nodeValue...
 
Tim is looking for something like this
Code:
private string GetElementText<T>(XmlReader xmlReader, ref T nodeValue)
{
   if (xmlReader.IsStartElement())
   {
      xmlReader.Read();
      if (string.IsNullOrEmpty(xmlReader.Name))
      {
         nodeValue = (T)Convert.ChangeType(typeof(T), xmlReader.Value);
      }
   }
   else
   {
   }
   return nodeValue;
}
although I don't understand why you would ref the parameter nodeValue and return nodeValue and the result of the function. I would pick one or the other.

Generics are much more powerful than List<T>. If you look at an of the fluent API's out there (StructureMap, being #1, Castle Windsor and Fluent NHiberate close behind) they heavily rely on generics to enable compile time checks.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top