1.

What is difference between Class and Struct?

Answer»
  • Class

A class is a user-defined blueprint or PROTOTYPE from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit.

Example:

public class Author { // Data members of class public string name; public string language; public int article_no; public int improv_no; // Method of class public void Details(string name, string language, int article_no, int improv_no) { this.name = name; this.language = language; this.article_no = article_no; this.improv_no = improv_no; Console.WriteLine("The name of the author is : " + name + "\nThe name of language is : " + language + "\nTotal number of article published " + article_no + "\nTotal number of Improvements:" +" done by author is : " + improv_no); } }
  • Structure

A structure is a collection of variables of different data TYPES under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types.

// Defining structure public struct Car { // Declaring different data types public string BRAND; public string Model; public string Color; }

Difference between Class and Structure

ClassStructure
Classes are of reference types.Structs are of value types
All the reference types are allocated on heap memory.All the value types are allocated on STACK memory.
Allocation of LARGE reference type is cheaper than allocation of large value type.Allocation and de-allocation is cheaper in value type as compare to reference type.
Class has limitless features.Struct has limited features.
Classes can contain constructor or destructor.Structure does not contain constructor or destructor.
Classes used new keyword for creating instances.Struct can create an instance, without new keyword
A Class can inherit from another classA Struct is not allowed to inherit from another struct or class
Function member of the class can be virtual or abstract.Function member of the struct cannot be virtual or abstract.
Two variable of class can contain the reference of the same object and any operation on one variable can affect another variable.Each variable in struct contains its own copy of data(except in ref and out parameter variable) and any operation on one variable can not effect another variable.


Discussion

No Comment Found