What is the different between class and structure
Ankit Nandekar
1. Struct are value type and stored on stack while class are reference type and store on heap.
2. Struct do not support inheritance while class supports inheritance, However struct can implements interface.
3. Struct should be used when you want to use a small data structure while class is better choice for complex data structure.
4. The fourth significant difference between class objects and struct objects refers to constructors. Constructors are supported by structs in the C# language, and you can define constructors for structs in exactly the same manner as you would for classes. If you are not familiar with constructors, they are methods with the same name as the struct or class. However, the only exception with struct constructors is that you are not permitted to define a constructor that takes no arguments.
5. By default, Structure data members are public but class data members are private.
6. In Structure we can’t declare any default constructor explicitly because it provides by .net framework. But in class we can declare default constructor explicitly.
More Info
1. Classes are reference types and structs are value types. So in other words class will be allocated on a heap and structs will be allocted on the stack.
2. You cannot have instance Field initializers in structs.But classes can haveexample:class MyClass1{int myVar =10; // no syntax error.public void MyFun( ){// statements}}struct MyStruct1{int myVar = 10; // syntax error.public void MyFun( ){// statements}}3. Classes can have explicit parameterless constructors. But structs cannot have4. Classes must be instantiated using the new operator. But structs can be5. Classes support inheritance.But there is no inheritance for structs.( structs don’t support inheritance polymorphism )6. Since struct does not support inheritance, access modifier of a member of a struct cannot be protected or protected internal.11. A class is permitted to declare a destructor.But a struct is not7. classes are used for complex and large set data. structs are for simple data structures.
See my 21 important .NET interview questions and answers