Note that there are some explanatory texts on larger screens.

plurals
  1. PONeed help regarding generics, interfaces, and base classes
    text
    copied!<p>Suppose I have these two objects:</p> <pre><code>public class Object1 { string prop1; string prop2; } public class Object2 { string prop1; int prop2; int prop3; } </code></pre> <p>and the following classes &amp; methods:</p> <pre><code>public class Object1Service { public Object1 GetObject(Object1 o) { return o; } public void SaveProperty2(Object1 o, string s) { o.prop2 = s; } } public class Object2Service { public Object2 GetObject(Object2 o) { return o; } public void SaveProperty2(Object2 o, int i) { o.prop2 = i; } } </code></pre> <p>How do I turn this into a generic? <br />I preferably need something so that the services implement an interface and just call some generic base class if possible. <br />Would it help if the two objects share a common parent class? If so, how will they be structured?</p> <hr> <p>Addendum:</p> <p>It's the return that is my real problem.</p> <pre><code>public T GetObjectByKey&lt;T&gt;(string key) { using (DBEntities db = new DBEntities()) { try { T returnedEntity = default(T); switch (EntityDictionary[typeof (T)]) // I have a dictionary setup like this dictionary&lt;type, string&gt; { case "Object1" : returnedEntity = ( from r in db.ObjectONESets where r.prop1 == key select new T { prop1 = r.prop1, prop2 = r.prop2 }).FirstOrDefault(); break ; case "Object2" : returnedEntity = ( from r in db.ObjectTWOSets where r.prop1 == key select new T { prop1 = r.prop1, prop2 = r.prop2, prop3 = r.prop3 }).FirstOrDefault(); break ; } return returnedEntity; } catch (NullReferenceException ) { return default(T); } } } </code></pre> <p>Without putting ALL my object properties in the base object, it has no way of knowing that prop1-3 is a property of T.<br /> If I do put all properties (common or not) in the base object, and if I need Object1, it then has a prop3 attached to it which I do not need.<br /> I'm not sure if I'm making much sense at this point, or if what I'm asking is even doable with Generics.</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