Note that there are some explanatory texts on larger screens.

plurals
  1. POCast Boxed Object back to Original Type
    primarykey
    data
    text
    <p>I expect there's one of two answers to this, either impossible or extremely simple and I've overlooked the obvious Google query.</p> <p>The underlying issue is that I have a generic object being passed in via an <code>EventHandler</code> that boxes the object and obfuscates the true type; only at runtime do I know what the object is.</p> <p>Admittedly the <code>dynamic</code> keyword can get around the issue, but I'd like to not lose IntelliSense and everything if I can avoid it. Plus, it doesn't solve not knowing what each of the properties of the generic object are without massive amounts of reflection.</p> <p>EDIT: The idea is to be able to determine the true type of the an object in a method parameter, and then cast that object as it's true type without knowing it in advance. This is but a simplified example. Boxed may have been the wrong term.</p> <p>An example:</p> <pre><code>public class Program { static void Main(string[] args) { var container = new Container&lt;Containee&gt;( new Containee { Property1 = Guid.NewGuid(), Property2 = "I'm a property!", Property3 = DateTime.Now } ); var boxed = (object)container; var originalType = boxed.GetType(); // DOES NOT COMPILE: would like an operation like this // EDIT: Request for more detail var actualType = boxed as originalType; actualType.Entity.Property2 = "But I like this better."; } } public class Containee { public Guid Property1 { get; set; } public string Property2 { get; set; } public DateTime Property3 { get; set; } } public class Container&lt;T&gt; { public Container(T entity) { Entity = entity; } public T Entity { get; internal set; } } </code></pre> <p>Clearly that won't compile, as there's not really a way to cast as a variable. However, I'm hoping there's a way to get a reference to the actual object and type, or at least, a way to dynamically re-create the type.</p> <p>I expect there's something simple I'm overlooking, or a better way to get around it in general. The point is to be able to wrap any object in the container, and figure out later what it was.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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