I am trying to write a generalized method to get the XElement value in a strongly typed form. Here is what I have:
public static class XElementExtensions { public static XElement GetElement(this XElement xElement, string elementName) {
As you can see in the First attempt GetElementValue , I'm trying to jump from the line -> object -> TElementType. Unfortunately, this does not work for an integer test case. When performing the following test:
[Test] public void GetElementValueShouldReturnValueOfIntegerElementAsInteger() { const int expectedValue = 5; const string elementName = "intProp"; var xElement = new XElement("name"); var integerElement = new XElement(elementName) { Value = expectedValue.ToString() }; xElement.Add(integerElement); int value = XElementExtensions.GetElementValue<int>(xElement, elementName); Assert.AreEqual(expectedValue, value, "Expected integer value was not returned from element."); }
I get the following exception when GetElementValue<int> is called:
System.InvalidCastException: Unable to set the value of element '5' for input 'Int32'.
Do I have to handle each casting case (or at least numerical) separately?
generics casting c # linq-to-xml xelement
Scott
source share