© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
48 replies
stigzler

How to pass a Type to a method for a return of the same type

Struggling to find the right syntax for this. I'm trying to specify a type that should be used to create a new instance and then return it. Example code (doesn't compile):

 private T SingleDataObjectFromXDoc<T>(XDocument xDoc, string elementName)
 {
     XElement SingleElement = xDoc.Descendants(elementName).First();
     return new (T)(SingleElement);
 }
 private T SingleDataObjectFromXDoc<T>(XDocument xDoc, string elementName)
 {
     XElement SingleElement = xDoc.Descendants(elementName).First();
     return new (T)(SingleElement);
 }


In this instance, the constructors of each Type I'll be passing will receive the XElement and subsequently update its properties from the XElement.

Example calls would be:

object DataObject1 = SingleDataObjectFromXDoc<Server>(xdoc1, "server");
object DataObject2 = SingleDataObjectFromXDoc<User>(xdoc2, "user");
object DataObject1 = SingleDataObjectFromXDoc<Server>(xdoc1, "server");
object DataObject2 = SingleDataObjectFromXDoc<User>(xdoc2, "user");

the
return new...
return new...
is essentially
return new Server(XElement)
return new Server(XElement)
and
return new User(XElement)
return new User(XElement)
(if that makes sense?)

(I know I'm assigning it to an object, but don't worry about that bit!)
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Return in the middle of a method
C#CC# / help
3y ago
(MONOGAME )How to pass a method with parameters to the update method
C#CC# / help
17mo ago
Is it possible to change the return type of interface method to the type of the implementing struct?
C#CC# / help
2y ago
✅ How to return null in a generalized method?
C#CC# / help
4y ago