Every time I read even basic things about technology, I find something interesting to share with you, here is some more difference between Struct and Classes. Actually when I searched on google I found lot many articles but here are two articles which has good content.
But still they do not include difference I found out, so go ahead and read then. Also download source code to get better understanding.
1. Constructors
- You are not allowed to implement default constructor inside a struct but it is allowed in class.
- Incase of structs, every construct overload must call default construct otherwise you will get compile time error "Backing field for automatically implemented property 'StructPractice.PersonStruct.Age' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer".
public PersonStruct(string fname, string lname, int age):this(){..}
2. Object creation
- new keyword does NOT DO special thing for struct as it does for reference types "memory allocation on heap".
- Both statement written below is proper in case of struct but second declaration will give compilation error for reference types when used before initialization.
PersonStruct objPersonStruct = new PersonStruct();
PersonStruct objPersonStructNew;
3. Struct as argument
- When struct is passed as args to a methods it behaves like a value type and a copy is created on the stack, as it is done for any other value type, which invloves more overhead than passing a reference of a class object.
- You can pass same object of struct as method argument by using ref keyword but it involves the risk of object update inside function, which is persist even after method is gone out of scope. Same as update to a classs object.
4. Struct comparision
- Structs are value type but '==' operator is not defined for them, and allowed to use. We get compile time error "Operator '==' cannot be applied to operands of type 'StructPractice.PersonStruct' and 'StructPractice.PersonStruct'"
- Equals method compares values of data members, If all the entities are of value type then you will get proper output, but if there is any reference type entity (most likely string) then you will not get proper output, because struct will store referenfce of that entity name exact value.
objPersonStruct = new PersonStruct("Pradeep",
"Tiwari", 21);
objPersonStructNewOne = new PersonStruct("Pradeep",
"Tiwari", 21);
but still both objects are not same. Best way to make it work like value type, use refelection and compare value of any reference type entity in overwridden Equals method.