Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using class name as method parameter and return type

Tags:

c#

I have an extension method for deserialization of an XDocument.

I use CarConfiguration as variable in this method, but I have another class configurations:

public static CarConfiguration Deserialize(this XDocument xdoc)
{
    XmlSerializer serializer = new XmlSerializer(typeof(CarConfiguration));

    using (StringReader reader = new StringReader(xdoc.ToString()))
    {
        CarConfiguration cfg = (CarConfiguration) serializer.Deserialize(reader);
        return cfg;
    }
}

class CarConfiguration 
{
    //car 
}

class BikeConfiguration 
{
    //bike 
}

So, there are 2 questions here:

  1. Can I use class name as parameter for this method? Something like this:

    static CarConfiguration Deserialize(this XDocument xdoc, class classname) {        
        var serializer = new XmlSerializer(typeof(classname));
    
  2. Can I make this method generic for all required types(CarConfiguration, BikeConfiguration etc.)? I mean for example dependency of return type on input class:

    static <classname> Deserialize(this XDocument xdoc, class classname) {
    
like image 549
Vladimir Avatar asked Jan 17 '26 20:01

Vladimir


1 Answers

The key word in your question is generic, so yes you can do this by utilising C# generics. For example:

public static T Deserialize<T>(this XDocument xdoc)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));

    using (StringReader reader = new StringReader(xdoc.ToString()))
    {
        T cfg = (T) serializer.Deserialize(reader);
        return cfg;
    }
}

And now you call it like this:

CarConfiguration x = xmlDocument.Deserialize<CarConfiguration>();
like image 191
DavidG Avatar answered Jan 19 '26 09:01

DavidG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!