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. struct and class

struct and class

Scheduled Pinned Locked Moved C#
16 Posts 7 Posters 1 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.
  • J jitendra sandu

    Dear Sir, can you tell me when do i use struct and when i use class

    D Offline
    D Offline
    DaveyM69
    wrote on last edited by
    #7

    Structs are value types - what that means in your situation is that it should only be used to represent a value. For example an int has one particular value lets say 1. If you need an int with the value of 2 then it must be a different int as there is no way that 1 can be 2. Therefore, once a value is set for a struct it should not be changed by a property, method or anything else. This is called immutability and something all structs should adhere to (although there are exeptions in the framework). So all properties will be readonly and any methods that normally mutate the object should return a new instance of the struct with the required values and leave the original instance intact. Also, the fields that make up a struct (must be private) should be value types themselves and should not, when combined, have a large memory footprint.

    Dave

    If this helped, please vote & accept answer!

    Binging is like googling, it just feels dirtier. (Pete O'Hanlon)
    BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

    1 Reply Last reply
    0
    • OriginalGriffO OriginalGriff

      Calla wrote:

      Use a struct if you have no need for methods or to use inheritance and you only need a structure to store data

      Sounds like you can't use methods to me! :laugh: Seriously, I don't think it's fair on beginners to give information that is misleading (not that you meant to, I'm sure) - it could send them down completely the wrong path. The difference between a struct and a class is a bugger to explain unless you can see how they are reacting to the info, which is why I suggested a book!

      You should never use standby on an elephant. It always crashes when you lift the ears. - Mark Wallace C/C++ (I dont see a huge difference between them, and the 'benefits' of C++ are questionable, who needs inheritance when you have copy and paste) - fat_boy

      C Offline
      C Offline
      Calla
      wrote on last edited by
      #8

      OriginalGriff wrote:

      Sounds like you can't use methods to me!

      ...or like you read the reply as the devil reads the bible ;) Seriously though, I admit it's a poor description but only as a result of trying to keep things short and provide a quick reply. I do realize you have a responsability when providing an answer to a beginner of making sure it's accurate and not misleading. :-O

      1 Reply Last reply
      0
      • OriginalGriffO OriginalGriff

        I'm sorry, but that answer is wrong in so many ways: A struct can have methods, (and properties, and events), and can inherit from interfaces. It is true that it is automatically sealed, so you cannot inherit from a struct, but a struct can inherit if it needs to. A struct is an object, just it derives from System.ValueType which forces it to be stack allocated rather than heap. It is this that means it is passed by value rather than by reference, nothing else.

        You should never use standby on an elephant. It always crashes when you lift the ears. - Mark Wallace C/C++ (I dont see a huge difference between them, and the 'benefits' of C++ are questionable, who needs inheritance when you have copy and paste) - fat_boy

        G Offline
        G Offline
        Gideon Engelberth
        wrote on last edited by
        #9

        I'm afraid your answer is also wrong. Structs are not forced to be stack allocated. The runtime simply chooses to use the stack in a limited set of circumstances just because it can. However, your statement about passing by value instead of reference is correct and points to the real distinction between structs and classes.

        OriginalGriffO 1 Reply Last reply
        0
        • G Gideon Engelberth

          I'm afraid your answer is also wrong. Structs are not forced to be stack allocated. The runtime simply chooses to use the stack in a limited set of circumstances just because it can. However, your statement about passing by value instead of reference is correct and points to the real distinction between structs and classes.

          OriginalGriffO Offline
          OriginalGriffO Offline
          OriginalGriff
          wrote on last edited by
          #10

          You are right, I'm wrong :doh: Structs (and all ValueType derived objects) can be allocated on the heap - for example they are if they are part of a class instance. If I had been involved, the only difference between a struct and a class would have been: "structs are imutable, classes are not". I personally think the "stack / heap" and "value / reference" distinction makes it harder to read code and work out what is happening: all parameters should be pass-by-reference unless otherwise specified - and yes, I do know stack allocation improves performance... But I wasn't involved, so we have to live with it... :laugh:

          You should never use standby on an elephant. It always crashes when you lift the ears. - Mark Wallace C/C++ (I dont see a huge difference between them, and the 'benefits' of C++ are questionable, who needs inheritance when you have copy and paste) - fat_boy

          "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
          "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

          L D G 3 Replies Last reply
          0
          • C Calla

            Hrm.. I never said a struct couldn't have methods, properties or events (though I can understand how my reply could be interpreted like that). I was only trying to give a (simple) direction of when to use a struct and when to use a class. But maybe I was being slobby..

            P Offline
            P Offline
            PIEBALDconsult
            wrote on last edited by
            #11

            It was clear enough to anyone who already knows what what you mean. :~

            1 Reply Last reply
            0
            • J jitendra sandu

              Dear Sir, can you tell me when do i use struct and when i use class

              P Offline
              P Offline
              PIEBALDconsult
              wrote on last edited by
              #12

              Keep it simple; don't use structs. :-D

              1 Reply Last reply
              0
              • OriginalGriffO OriginalGriff

                You are right, I'm wrong :doh: Structs (and all ValueType derived objects) can be allocated on the heap - for example they are if they are part of a class instance. If I had been involved, the only difference between a struct and a class would have been: "structs are imutable, classes are not". I personally think the "stack / heap" and "value / reference" distinction makes it harder to read code and work out what is happening: all parameters should be pass-by-reference unless otherwise specified - and yes, I do know stack allocation improves performance... But I wasn't involved, so we have to live with it... :laugh:

                You should never use standby on an elephant. It always crashes when you lift the ears. - Mark Wallace C/C++ (I dont see a huge difference between them, and the 'benefits' of C++ are questionable, who needs inheritance when you have copy and paste) - fat_boy

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #13

                You want to make .NET even slower than it already is? Or would you make int/float/etc ugly special cases - in which case performance would still be impacted sometimes (but less often)

                1 Reply Last reply
                0
                • OriginalGriffO OriginalGriff

                  You are right, I'm wrong :doh: Structs (and all ValueType derived objects) can be allocated on the heap - for example they are if they are part of a class instance. If I had been involved, the only difference between a struct and a class would have been: "structs are imutable, classes are not". I personally think the "stack / heap" and "value / reference" distinction makes it harder to read code and work out what is happening: all parameters should be pass-by-reference unless otherwise specified - and yes, I do know stack allocation improves performance... But I wasn't involved, so we have to live with it... :laugh:

                  You should never use standby on an elephant. It always crashes when you lift the ears. - Mark Wallace C/C++ (I dont see a huge difference between them, and the 'benefits' of C++ are questionable, who needs inheritance when you have copy and paste) - fat_boy

                  D Offline
                  D Offline
                  DaveyM69
                  wrote on last edited by
                  #14

                  OriginalGriff wrote:

                  structs are imutable, classes are not

                  Structs should be immutable but are not forced to be. System.Drawing.Size IIRC (not at a dev machine at the moment) is an example where MS haven't enforced this - both Width and Height properties are settable X| Also many structs used for P/Invoke by necessity are mutated by unmanaged code. It's a good rule to follow and will avoid major problems if used in a hash set of some description (the hash code will probably be invalid if it's mutated), but it's not set in stone. [edit] Just realized you were stating what you would have done if you were involved in the C# spec, not how it actually is! Apologies! :doh: [/edit]

                  Dave

                  If this helped, please vote & accept answer!

                  Binging is like googling, it just feels dirtier. (Pete O'Hanlon)
                  BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

                  OriginalGriffO 1 Reply Last reply
                  0
                  • D DaveyM69

                    OriginalGriff wrote:

                    structs are imutable, classes are not

                    Structs should be immutable but are not forced to be. System.Drawing.Size IIRC (not at a dev machine at the moment) is an example where MS haven't enforced this - both Width and Height properties are settable X| Also many structs used for P/Invoke by necessity are mutated by unmanaged code. It's a good rule to follow and will avoid major problems if used in a hash set of some description (the hash code will probably be invalid if it's mutated), but it's not set in stone. [edit] Just realized you were stating what you would have done if you were involved in the C# spec, not how it actually is! Apologies! :doh: [/edit]

                    Dave

                    If this helped, please vote & accept answer!

                    Binging is like googling, it just feels dirtier. (Pete O'Hanlon)
                    BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

                    OriginalGriffO Offline
                    OriginalGriffO Offline
                    OriginalGriff
                    wrote on last edited by
                    #15

                    That's ok - I was just writing to remind you of that when I saw your edit! :laugh:

                    You should never use standby on an elephant. It always crashes when you lift the ears. - Mark Wallace C/C++ (I dont see a huge difference between them, and the 'benefits' of C++ are questionable, who needs inheritance when you have copy and paste) - fat_boy

                    "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                    "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                    1 Reply Last reply
                    0
                    • OriginalGriffO OriginalGriff

                      You are right, I'm wrong :doh: Structs (and all ValueType derived objects) can be allocated on the heap - for example they are if they are part of a class instance. If I had been involved, the only difference between a struct and a class would have been: "structs are imutable, classes are not". I personally think the "stack / heap" and "value / reference" distinction makes it harder to read code and work out what is happening: all parameters should be pass-by-reference unless otherwise specified - and yes, I do know stack allocation improves performance... But I wasn't involved, so we have to live with it... :laugh:

                      You should never use standby on an elephant. It always crashes when you lift the ears. - Mark Wallace C/C++ (I dont see a huge difference between them, and the 'benefits' of C++ are questionable, who needs inheritance when you have copy and paste) - fat_boy

                      G Offline
                      G Offline
                      Gideon Engelberth
                      wrote on last edited by
                      #16

                      That's an interesting hypothetical world. In the real world, if I do this:

                      static void Main(string[] args)
                      {
                      List<int> items = new List<int>(new int[] { 1, 2, 3, 4, 5, 1, 2, 3, 4 });

                      List<int> nextIndices = new List<int>();
                      try
                      {
                          for (int i = 0; i < items.Count() - 1; i++)
                          {
                      
                              nextIndices.Add(FindIndexAfter(items, i, toMatch => toMatch == items\[i\]));
                          }
                      }
                      catch (Exception ex)
                      {
                          Console.WriteLine(ex);
                      }
                      
                      for (int j = 0; j < nextIndices.Count(); j++)
                      {
                          Console.WriteLine(nextIndices\[j\]);
                      }
                      
                      Console.WriteLine("Program complete...");
                      Console.ReadKey();
                      

                      }

                      static int FindIndexAfter<T>(List<T> items, int startIndex, Func<T, bool> predicate)
                      {
                      if (startIndex < 0)
                      throw new ArgumentOutOfRangeException("startIndex",
                      "Start index cannot be negative.");
                      if (startIndex >= items.Count())
                      throw new ArgumentOutOfRangeException("startIndex",
                      "Start index must be less than the number of items");
                      startIndex++;
                      while (startIndex < items.Count())
                      {
                      if (predicate(items[startIndex]))
                      return startIndex;
                      startIndex++;
                      }

                      return -1;
                      

                      }

                      I print:

                      5
                      6
                      7
                      8
                      -1
                      -1
                      -1
                      -1
                      Program Complete

                      Passing startIndex as ref (which is close to what you are suggesting as the default), I get this:

                      1
                      3
                      5
                      7
                      Program Complete

                      Since structs are just immutable classes, you now also return by reference, which would mean that you would be filling the list with references to variable i instead of the values returned by the function. I'm not going to try to simulate that sort of return, but I'm pretty sure you would end up with a list filled with items.Count() when you were done. So, now you either have to invent some "return by value" notation or do something like return new int(startIndex); Along the same line, you also now only have assignment by reference. Which means that

                      int i = 1;
                      int j = i;
                      j++;
                      Console.WriteLine(i);

                      now prints 2 instead of 1. Again, you would need some new syntax to specify "assign by value" instead of by reference. All in all, I just don't think "structs are just immutable classes" (and the default pass-by-reference that comes from it) would actuall

                      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