I am wondering if a struct is like an object or is an object.

For example a struct:

struct Books
   public string title;
   public string author;
   public string subject;
   public int book_id;

Defining this struct:

public class testStructure
   public static void Main(string[] args)

      Books Book1;        /* Declare Book1 of type Book */
      Books Book2;        /* Declare Book2 of type Book */

      /* book 1 specification */
      Book1.title = "C Programming";
      Book1.author = "Nuha Ali"; 
      Book1.subject = "C Programming Tutorial";
      Book1.book_id = 6495407;

      /* book 2 specification */
      Book2.title = "Telecom Billing";
      Book2.author = "Zara Ali";
      Book2.subject =  "Telecom Billing Tutorial";
      Book2.book_id = 6495700;


This is similar to how an object is created for example the class dog:

class dog
        public String Name;
        public String Sound;

and creating objects of class dog and defining:

private void button1_Click(object sender, EventArgs e)
            dog dogObj1 = new dog();
            dogObj1.Name = "dog1";
            dogObj1.Sound = "Woof";

            dog dogObj2 = new dog();
            dogObj2.Name = "dog2";
            dogObj2.Sound = "Woof";         

As you can see objects and structs are similar in structure.

Are structs actually a type of object?

Edited by iConqueror: spelling mistake

2 Years
Discussion Span
Last Post by Ketsuekiame

In C# objects and structs are treated differently by what basic type they are.

An Object (class) in C# is a reference type and so whenever you pass an instance of that class to a method, you're really only passing a reference to that class. This has the benefit of saving memory, but has the disadvantage that any modifications you make inside that method, will also affect the original object you passed in (it's the same one after all).

Structs and primitives (like int, float etc) are value types. This means that when you pass a struct to a method, the method gets a copy of it on the stack (as opposed to the heap where objects are created). Important to note that this is a copy, so this has the disadvantage of being slower and using more memory, however, any work done to this struct is completely isolated.

They can be used pretty much the same way (there are some advanced limitations on structs).

Hope this helps.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.