Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. C# Question with Generics [modified]

C# Question with Generics [modified]

Scheduled Pinned Locked Moved C#
questioncsharpdatabase
20 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D darkelv

    I am not sure if this is what you want: class DBStore where T : class, new() { public T CreateObject() { return new T(); } public void DeleteObject(int id) { Type t = typeof(T); // Do you stuff here using theObject; } public DBStore() { } } abstract class DomainObject where T : class, new() { protected int _id; protected DBStore _dbStore; public void Delete () { _dbStore.DeleteObject(_id); } } class Boat : DomainObject { public Boat() { } public Boat(int id) { this._id = id; this._dbStore = new DBStore(); } } class Car : DomainObject { public Car() { } public Car(int id) { this._id = id; this._dbStore = new DBStore(); } } class TestClass { public void Run() { Boat boat = new Boat(1234); boat.Delete(); Car car = new Car(5678); car.Delete(); } }

    M Offline
    M Offline
    malharone
    wrote on last edited by
    #11

    If I'm not mistaken, then you're suggesting something like: public abstract class DomainObject<T> This will break majority of the app where I'm simply keeping a reference to the base DomainObject as opposed to DomainObject for Car. You could help clarify my misunderstanding .. but: Assuming I changed the class declaration as above (with generics), what should I change my dependent method signature for the classes that do NOT inherit from generics? e.g.

    01. class ListViewEx
    02. {
    03.
    04. DomainObject _selectedObject;
    05.
    06. public void AddItem (DomainObject obj)
    07. { ... }
    08.
    09. public DomainObject SelectedObject
    10. { get { return _selectedObject; }
    11. set { ... } }
    12.}

    - What should the line #4, 6 & 9 look like after genericising DomainObject? - And one thing to note is that currently, ListViewEx.AddItem is designed to allow consumer to pass both objects of type Car AND Boat. If I genericize the ListViewEx to class ListViewEx <T> then a. I'll lose the functionality of adding items of multiple types, and b. Win form designer will no longer work. Thanks, - Malhar

    1 Reply Last reply
    0
    • M malharone

      If I'm not mistaken, then you're suggesting something like: public abstract class DomainObject<T> This will break majority of the app where I'm simply keeping a reference to the base DomainObject as opposed to DomainObject for Car. You could help clarify my misunderstanding .. but: Assuming I changed the class declaration as above (with generics), what should I change my dependent method signature for the classes that do NOT inherit from generics? e.g.

      01. class ListViewEx
      02. {
      03.
      04. DomainObject _selectedObject;
      05.
      06. public void AddItem (DomainObject obj)
      07. { ... }
      08.
      09. public DomainObject SelectedObject
      10. { get { return _selectedObject; }
      11. set { ... } }
      12.}

      - What should the line #4, 6 & 9 look like after genericising DomainObject? - And one thing to note is that currently, ListViewEx.AddItem is designed to allow consumer to pass both objects of type Car AND Boat. If I genericize the ListViewEx to class ListViewEx <T> then a. I'll lose the functionality of adding items of multiple types, and b. Win form designer will no longer work. Thanks, - Malhar

      M Offline
      M Offline
      mike montagne
      wrote on last edited by
      #12

      I don't see enough here to say what your line 4 should be (unless maybe I'm supposed to study the previous code or something). Sorry, not enough time for that. But yes, you are correct in understanding what I am suggesting. In my haste to make the previous post, I neglected to write my < and > with code. As to what you need to do with your line 4, I think it's a larger matter than that. If you declare your generic to descend from a base class B, then keep a reference to B. I don't see why you would have a problem with using that reference to refer to your domain object then.

      M 1 Reply Last reply
      0
      • M malharone

        I wished! C# compiler expects a class, and not a variable of type 'type'.

        Type t = GetType();
        _dbStore.DeleteObject (_id);

        --> The type or namespace name 't' could not be found (are you missing a using directive or an assembly reference?) -- modified at 21:22 Wednesday 21st February, 2007

        M Offline
        M Offline
        mike montagne
        wrote on last edited by
        #13

        Giving serious attention to this is going to swerve me way off course at the moment. Generics should always be addressed very carefully. I think you have some really sour syntax here. When you call your DeleteObject() method, it must be able to handle an object of class/type t. You shouldn't have to tell it what class to handle at that point. Your method should just act on an index, and assumably remove a reference. I think the compiler is possibly trying to interpret your _dbStore.DeleteObject <t> (_id); statement as a type declaration, and before it gets very far with that, it chokes on the <t> syntax.

        M 1 Reply Last reply
        0
        • M mike montagne

          I don't see enough here to say what your line 4 should be (unless maybe I'm supposed to study the previous code or something). Sorry, not enough time for that. But yes, you are correct in understanding what I am suggesting. In my haste to make the previous post, I neglected to write my < and > with code. As to what you need to do with your line 4, I think it's a larger matter than that. If you declare your generic to descend from a base class B, then keep a reference to B. I don't see why you would have a problem with using that reference to refer to your domain object then.

          M Offline
          M Offline
          malharone
          wrote on last edited by
          #14

          What I meant was currently line #4 is: DomainObject _selectedObject #6 is: public void AddItem (DomainObject obj) #9 is: public DomainObject SelectedObject If DomainObject is converted to a generic class, then I can't really compile the ListViewEx class with the above code lines. I must change the declarations as well to .. : #4 is: DomainObject<_**??**_> _selectedObject #6 is: public void AddItem (DomainObject<_**??**_> obj) #9 is: public DomainObject<_**??**_> SelectedObject So the correct question is, what would I substitue "??" with? if you're implying the following, then there may be a possiblity but that'd just create unnecessary classes and cause confusion:

          abstract class BaseObj
          {
          }
          abstract class DomainObject <T> : BaseObj
          {
          }
          class Car : DomainObject <Car>
          {
          }
          class Boat : DomainObject <Boat>
          {
          }
          class ListViewEx
          {
          void AddItem (BaseObj obj)
          {
          }
          }

          The "BaseObj" is simply an empty class and it just changes the object model where consumers can begin using 'baseobj' instead of DomainObject -- since classes such as "ListViewEx" have been changed to accept BaseObj. - Malhar

          1 Reply Last reply
          0
          • M mike montagne

            Giving serious attention to this is going to swerve me way off course at the moment. Generics should always be addressed very carefully. I think you have some really sour syntax here. When you call your DeleteObject() method, it must be able to handle an object of class/type t. You shouldn't have to tell it what class to handle at that point. Your method should just act on an index, and assumably remove a reference. I think the compiler is possibly trying to interpret your _dbStore.DeleteObject <t> (_id); statement as a type declaration, and before it gets very far with that, it chokes on the <t> syntax.

            M Offline
            M Offline
            malharone
            wrote on last edited by
            #15

            mike montagne wrote:

            When you call your DeleteObject() method, it must be able to handle an object of class/type t.

            I couldnt agree with you more on this point. But there are cases when from you non-generic class, you want to call a generic method and all you want do is to pass the "current type" and not any other type. In most cases, you will hard-code the class name, but if you're working in the base class, you would not know the type of the deriving class. The only workaround for this limiation, is to make the method from your base class abstract and let the deriving classes implement the call. That said, if I have to do this, then I'm working against the what the intention of generics was in the first place. e.g.

            class DomainObject
            {
            abstract bool Delete(int id)
            }
            class Car
            {
            override bool Delete(int id)
            {
            DBStore.SomeGenericMethod<Car>(args);
            }
            }
            class Boat
            {
            override bool Delete(int id)
            {
            DBStore.SomeGenericMethod<Boat>(args);
            }
            }

            Anyways, your input is much appreciated .. I'm simply being a devil's advocate here. I'm sure i'm not the only person encountering such scenarios and this would a common problem. - Malhar

            M 4 Replies Last reply
            0
            • M malharone

              mike montagne wrote:

              When you call your DeleteObject() method, it must be able to handle an object of class/type t.

              I couldnt agree with you more on this point. But there are cases when from you non-generic class, you want to call a generic method and all you want do is to pass the "current type" and not any other type. In most cases, you will hard-code the class name, but if you're working in the base class, you would not know the type of the deriving class. The only workaround for this limiation, is to make the method from your base class abstract and let the deriving classes implement the call. That said, if I have to do this, then I'm working against the what the intention of generics was in the first place. e.g.

              class DomainObject
              {
              abstract bool Delete(int id)
              }
              class Car
              {
              override bool Delete(int id)
              {
              DBStore.SomeGenericMethod<Car>(args);
              }
              }
              class Boat
              {
              override bool Delete(int id)
              {
              DBStore.SomeGenericMethod<Boat>(args);
              }
              }

              Anyways, your input is much appreciated .. I'm simply being a devil's advocate here. I'm sure i'm not the only person encountering such scenarios and this would a common problem. - Malhar

              M Offline
              M Offline
              mike montagne
              wrote on last edited by
              #16

              malharone wrote:

              I couldnt agree with you more on this point. But there are cases when from you non-generic class, you want to call a generic method and all you want do is to pass the "current type" and not any other type. In most cases, you will hard-code the class name, but if you're working in the base class, you would not know the type of the deriving class.

              I think there's a conceptual problem here. First of all, you can overload your method if you need to process a handful of known classes, or you can simply let descendants override your method (if they need to), and whatever calls the method ends up firing, being as they belong to the instance you (or whoever) calls them on, this ends up firing the method implementation of the closest descendant to the class it's called on (which may be the instance class itself). As your class design is a matter of writing these methods *for each class* (if necessary to override them), this *is* the right method (whether overloads or overrides are necessary or not -- they may very well not be). Now, if you need to identify the class otherwise (which isn't evident from your example), you can also pass your own identifier argument. It doesn't even have to be a real class -- it could be an enumerated type... anything, even an integer. C++ guys do this all the time to eliminate dynamic casting, and it's perfectly sound if you cover your bases... and faster than greased things unmentionable in C# forums. Reflection will also work to determine the class (although I have to admit I'm a bit raw with this with C#, as it's something I'll be getting to in the near future). I know for instance I have substantial notes and collected material on the Activator class, which I intend to use to create instances of unknown classes, which certainly is an intersecting area. ----- Now, I also have another thought. You have a mixture of generics and non-generics interacting. Something you wrote earlier also tells me you are flexible -- you could write this as all non-generic then? If you can, that's a good way to work out the problem. Get it working without generics. This will tell you exactly how to build generics into it, if that is a good thing to do. It probably is a good thing to do if you have to do any casting, because it can eliminate casting altogether, and provide wholy type safe operation with minimal code. I really can't see what the problem is. I look at your question, and you say you have to pass the

              1 Reply Last reply
              0
              • M malharone

                mike montagne wrote:

                When you call your DeleteObject() method, it must be able to handle an object of class/type t.

                I couldnt agree with you more on this point. But there are cases when from you non-generic class, you want to call a generic method and all you want do is to pass the "current type" and not any other type. In most cases, you will hard-code the class name, but if you're working in the base class, you would not know the type of the deriving class. The only workaround for this limiation, is to make the method from your base class abstract and let the deriving classes implement the call. That said, if I have to do this, then I'm working against the what the intention of generics was in the first place. e.g.

                class DomainObject
                {
                abstract bool Delete(int id)
                }
                class Car
                {
                override bool Delete(int id)
                {
                DBStore.SomeGenericMethod<Car>(args);
                }
                }
                class Boat
                {
                override bool Delete(int id)
                {
                DBStore.SomeGenericMethod<Boat>(args);
                }
                }

                Anyways, your input is much appreciated .. I'm simply being a devil's advocate here. I'm sure i'm not the only person encountering such scenarios and this would a common problem. - Malhar

                M Offline
                M Offline
                mike montagne
                wrote on last edited by
                #17

                PS. My own use of (or need to use) generics has never encountered any challenging hurdle that I can't just write them at will -- and any usage has always been very straightforward. I still think you have a basic conceptual class design problem, but just in case you might find deep generic study helpful, I think Richter is a truly excellent source (CLR Via C#, Second Edition). On p. 374, you will find an excellent chapter on Generic Methods. On p. 375, there is an excellent subtitle on Generic Methods and Type Inference. Much further material addresses everything you need to know about generics. I highly encourage you to use them for the same reasons Richter does -- processing is inherently much faster, because casting/boxing are eliminated (he cites many examples, and practice proves they are quite correct). Good programming will always use them where they benefit a project in this way -- generics are unavoidable necessities to good practice. But they really aren't that difficult.

                1 Reply Last reply
                0
                • M malharone

                  mike montagne wrote:

                  When you call your DeleteObject() method, it must be able to handle an object of class/type t.

                  I couldnt agree with you more on this point. But there are cases when from you non-generic class, you want to call a generic method and all you want do is to pass the "current type" and not any other type. In most cases, you will hard-code the class name, but if you're working in the base class, you would not know the type of the deriving class. The only workaround for this limiation, is to make the method from your base class abstract and let the deriving classes implement the call. That said, if I have to do this, then I'm working against the what the intention of generics was in the first place. e.g.

                  class DomainObject
                  {
                  abstract bool Delete(int id)
                  }
                  class Car
                  {
                  override bool Delete(int id)
                  {
                  DBStore.SomeGenericMethod<Car>(args);
                  }
                  }
                  class Boat
                  {
                  override bool Delete(int id)
                  {
                  DBStore.SomeGenericMethod<Boat>(args);
                  }
                  }

                  Anyways, your input is much appreciated .. I'm simply being a devil's advocate here. I'm sure i'm not the only person encountering such scenarios and this would a common problem. - Malhar

                  M Offline
                  M Offline
                  mike montagne
                  wrote on last edited by
                  #18

                  Just for example (before I get back to work), Here's a declaration from current work which is not really difficult to grasp. It's declaring an outer generic container of 2 levels of inner generic containers. What are the ramifications of this? Not much, really. It just allows me to do a lot of work without casting -- which in fact is very important to high speed iterative processes which have to act very often on each internal instance.

                  protected List<List<List<Bitmap>>> v_Maps_MASTER = new List<List<List<Bitmap>>>( );
                  

                  This is just a container for further generics which are declared like this:

                  protected List<Bitmap> v_Maps_Button_UP = new List<Bitmap>( );
                  

                  In the end however, every member is just a bitmap, and therefore every instance can be called just as "if" it is a bitmap, because *it IS* a bitmap ("generic" or not):

                                                                    if ( ( enumContours.TopAndBottom == f_Contours ) || ( enumContours.TopOnly == f_Contours ) )
                                                                         {
                                                                         v_Maps_UP[ i_Btn_BL_BR ][ i_NF ].SetPixel( 0, 0,
                                                                              Color_IncOrDecLum( v_cBaseUP_Glossed, lumDiffAccumulated_I + f_LumDif_EdgeBevels ) );
                                                                         }
                                                                    else
                                                                         {
                                                                         v_Maps_UP[ i_Btn_BL_BR ][ i_NF ].SetPixel( 0, 0,
                                                                              Color_IncOrDecLum( v_cFLATFILL_UPContours, lumDiffAccumulated_I + f_LumDif_EdgeBevels ) );
                                                                         }
                  

                  So this is just basic practice. Generics just help us process *a class* (or classes, as they are usually processed).

                  M 1 Reply Last reply
                  0
                  • M mike montagne

                    Just for example (before I get back to work), Here's a declaration from current work which is not really difficult to grasp. It's declaring an outer generic container of 2 levels of inner generic containers. What are the ramifications of this? Not much, really. It just allows me to do a lot of work without casting -- which in fact is very important to high speed iterative processes which have to act very often on each internal instance.

                    protected List<List<List<Bitmap>>> v_Maps_MASTER = new List<List<List<Bitmap>>>( );
                    

                    This is just a container for further generics which are declared like this:

                    protected List<Bitmap> v_Maps_Button_UP = new List<Bitmap>( );
                    

                    In the end however, every member is just a bitmap, and therefore every instance can be called just as "if" it is a bitmap, because *it IS* a bitmap ("generic" or not):

                                                                      if ( ( enumContours.TopAndBottom == f_Contours ) || ( enumContours.TopOnly == f_Contours ) )
                                                                           {
                                                                           v_Maps_UP[ i_Btn_BL_BR ][ i_NF ].SetPixel( 0, 0,
                                                                                Color_IncOrDecLum( v_cBaseUP_Glossed, lumDiffAccumulated_I + f_LumDif_EdgeBevels ) );
                                                                           }
                                                                      else
                                                                           {
                                                                           v_Maps_UP[ i_Btn_BL_BR ][ i_NF ].SetPixel( 0, 0,
                                                                                Color_IncOrDecLum( v_cFLATFILL_UPContours, lumDiffAccumulated_I + f_LumDif_EdgeBevels ) );
                                                                           }
                    

                    So this is just basic practice. Generics just help us process *a class* (or classes, as they are usually processed).

                    M Offline
                    M Offline
                    mike montagne
                    wrote on last edited by
                    #19

                    PS. *If one or however many of the instances descended from Bitmap, it still could legally be assigned to the instance pointer comprising each "member." If my methods act on that instance, and if it overrides a Bitmap method that I call, the proper method is automatically called.

                    1 Reply Last reply
                    0
                    • M malharone

                      mike montagne wrote:

                      When you call your DeleteObject() method, it must be able to handle an object of class/type t.

                      I couldnt agree with you more on this point. But there are cases when from you non-generic class, you want to call a generic method and all you want do is to pass the "current type" and not any other type. In most cases, you will hard-code the class name, but if you're working in the base class, you would not know the type of the deriving class. The only workaround for this limiation, is to make the method from your base class abstract and let the deriving classes implement the call. That said, if I have to do this, then I'm working against the what the intention of generics was in the first place. e.g.

                      class DomainObject
                      {
                      abstract bool Delete(int id)
                      }
                      class Car
                      {
                      override bool Delete(int id)
                      {
                      DBStore.SomeGenericMethod<Car>(args);
                      }
                      }
                      class Boat
                      {
                      override bool Delete(int id)
                      {
                      DBStore.SomeGenericMethod<Boat>(args);
                      }
                      }

                      Anyways, your input is much appreciated .. I'm simply being a devil's advocate here. I'm sure i'm not the only person encountering such scenarios and this would a common problem. - Malhar

                      M Offline
                      M Offline
                      mike montagne
                      wrote on last edited by
                      #20

                      malharone wrote:

                      But there are cases when from you non-generic class, you want to call a generic method and all you want do is to pass the "current type" and not any other type.

                      Whenever you need to do this, this is the way to write your call:

                      ( CurrentType )InstanceReference.Method( args )
                      
                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups