Note that there are some explanatory texts on larger screens.

plurals
  1. POCasting to generic type in non-generic method
    primarykey
    data
    text
    <p>What I'm doing now:</p> <pre><code>void Main() { var command1 = new PersistenceCommand(new MyIntBO()); var command2 = new PersistenceCommand(new MyGuidBO()); var command3 = new PersistenceCommand(new PersistentBO()); Console.WriteLine(command1.ToString()); Console.WriteLine(command2.ToString()); Console.WriteLine(command3.ToString()); } public class PersistenceCommand { public PersistenceCommand(PersistentBO businessObject) { _businessObject = businessObject; } public override string ToString() { string result = _businessObject.GetType().Name; var keyed = _businessObject as IPrimaryKeyed&lt;int&gt;; if (keyed != null) { result += " " + keyed.Id.ToString(); } return result; } private readonly PersistentBO _businessObject; } public interface IPrimaryKeyed&lt;out TKey&gt; { TKey Id { get; } } public class PersistentBO {} public class MyIntBO : PersistentBO, IPrimaryKeyed&lt;int&gt; { public int Id { get { return 1008; } } } public class MyGuidBO : PersistentBO, IPrimaryKeyed&lt;Guid&gt; { public Guid Id { get { return new Guid("6135d49b-81bb-43d4-9b74-dd84c2d3cc29"); } } } </code></pre> <p>This prints:</p> <pre>MyIntBO 1008 MyGuidBO PersistentBO</pre> <p>I'd like it to print:</p> <pre>MyIntBO 1008 MyGuidBO 6135d49b-81bb-43d4-9b74-dd84c2d3cc29 PersistentBO</pre> <p>What's the most elegant way to do that?</p> <p>I want to support all types of keys - <code>int</code>, <code>long</code>, <code>Guid</code>, etc. - so I'd rather not do multiple casts. Note that not every business object implements that interface (some do not have a single primary key).</p> <p>I realize I could use reflection and try to access the <code>Id</code> property. I was wondering if there's a better solution.</p> <p><strong>Clarification:</strong> To address @Acaz Souza and @Petar Ivanov's answers, we have dozens of classes scattered over multiple assemblies that already implement <code>IPrimaryKeyed&lt;T&gt;</code>. I do not want to break all of them by extending the interface contract. If I were designing this from scratch, their solutions would work.</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.
    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