Structs are value types and classes are reference types. That's the major difference
Look at this:
public struct MyStruct
{
public string Name { get; set; }
}
....
MyStruct s = new MyStruct();
s.Name = "Foo";
MyStruct s2 = s;
s2.Name = "Bah";
Console.Write("Name of MyStruct s: " + s.Name); // Foo not Bah
When you assign a struct to another variable a copy is created, so you have two instances of the struct. With classes you would modify both variables because both reference the same instance.
So that's the major difference. Apart from that structs and classes are similar. You can have methods, properties, events, etc. in both. There's nothing wrong with having methods in structs.
But since structs should not be mutable (should have readonly properties) most methods that "modify" it will return a new instance of the struct(like f.e. DateTime.AddDays
).
You have these members in both:
- Fields
- Constants
- Properties
- Methods
- Constructors
- Events
- Indexers
- Operators
- Nested Types