0

With generic-types, it's possible to give a dynamic type, but is it possible to also give a dynamic value ?

For example, I receive an XML response from a Rest API and I want to Deserialize it into an object:

<tsResponse>
   <value id="hello"/>
</tsResponse>
[XmlRoot("tsResponse")]
public class TsResponse<T, string myNodeName>
{
    [XmlElement(myNodeName)]
    public T Object { get; set; }
}

public class User
{
    [XmlAttribute("id")]
    public string Id { get; set; }
}

To make it works I need to call something like this:

using (StringReader sr = new StringReader(xml))
{
    XmlSerializer serializer = new XmlSerializer(typeof(TsResponse<User>));
    TsResponse<User, "value"> responseXml = (TsResponse<User, "value">)serializer.Deserialize(sr);
}

Is it possible to do something like this ?

8
  • What is the context when you say "With template, it's possible to give a dynamic type"? What "template" are you referring to? (Do you mean an XSD Schema and/or XML DTD? If so, then those aren't templates...) Commented Nov 2, 2022 at 15:47
  • @Dai A class template something like public class A<T> Commented Nov 2, 2022 at 15:48
  • 1
    Generic-types aren't templates. Despite many similarities, they are fundamentally different concepts, and C# does not support templates. Commented Nov 2, 2022 at 15:48
  • 1
    That's not possible. Generics are a compile-time-thing, whereas you want to provide something at runtime. Furthermor XmlElement - as attributes in general - only work with compile-time literals, so you cannot provide a dynamic value to them. Commented Nov 2, 2022 at 15:51
  • What you're after isn't directly achievable in C#/.NET as generic-type parameters are always type-names (and never values), but what you're ultimately trying to accomplish might be possible with C# 11's static interface members... depending on if it supports const members of interface types, then you could pass that to XmlElement( here ). Hmmm.... UPDATE: Nevermind, only static abstract members can, not const members. Commented Nov 2, 2022 at 15:52

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.