Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to Cast to Generic Parameter in C#?
    text
    copied!<p>I'm trying to write a generic method for fetching an <code>XElement</code> value in a strongly-typed fashion. Here's what I have:</p> <pre><code>public static class XElementExtensions { public static XElement GetElement(this XElement xElement, string elementName) { // Calls xElement.Element(elementName) and returns that xElement (with some validation). } public static TElementType GetElementValue&lt;TElementType&gt;(this XElement xElement, string elementName) { XElement element = GetElement(xElement, elementName); try { return (TElementType)((object) element.Value); // First attempt. } catch (InvalidCastException originalException) { string exceptionMessage = string.Format("Cannot cast element value '{0}' to type '{1}'.", element.Value, typeof(TElementType).Name); throw new InvalidCastException(exceptionMessage, originalException); } } } </code></pre> <p>As you can see on the <code>First attempt</code> line of <code>GetElementValue</code>, I'm trying to go from string -> object -> TElementType. Unfortunately, this does not work for an integer test case. When running the following test:</p> <pre><code>[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&lt;int&gt;(xElement, elementName); Assert.AreEqual(expectedValue, value, "Expected integer value was not returned from element."); } </code></pre> <p>I get the following exception when <code>GetElementValue&lt;int&gt;</code> is called:</p> <blockquote> <p>System.InvalidCastException : Cannot cast element value '5' to type 'Int32'.</p> </blockquote> <p>Am I going to have to handle each casting case (or at least the numeric ones) separately?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload