Here, we will learn what is class in c#, uses of class, what is structure (struct) in c#, how to use structure in c#, and the differences between class and structure (struct) in c# with examples.
To define a class in c#, we need to use the
class keyword. Following is the syntax of defining the class in c#.
In this class syntax, we used the class keyword to define the class in c# with public access modifier. Based on our requirements, we can use any access modifier along with the class. In c#, the access modifiers are useful to restrict the access of our class in applications.
The following is an example of creating the class with various data members in c#.
To learn more about classes, visit Classes in C# with Examples.
In c#, structure or struct is same as a class and it will contain various data members such as properties, constructors, methods, events, etc. The only difference between class and structure is class is a reference type and the structure is a value type. To learn about value type and reference type in c#, visit C# Value Type and References with Examples.
To define a structure, you need to use the
struct keyword. Following is the syntax of defining the structure in c#.
In this structure syntax, we defined a structure using the
struct keyword along with the
public access modifier. To learn about access modifiers, visit Access Modifiers in C# with Examples.
The following is an example of defining the structure using the
struct keyword in c#.
To learn more about structures, visit Structures in C# with Examples.
As discussed, both the class and structure are useful to combine various data members into a single unit. The following table lists the main differences between class and structure in c#.
|The class can be defined by using the
||The structure can be defined by using the
|In c#, classes are reference types.||Structures are the value types.|
|In c#, we can instantiate the class using a
||The structure can be instantiated with or without using a
|In c#, a class can inherit from other classes.||The structure won't support inheriting from other structures or classes.|
|In c#, we can create a class with parameterless constructors.||The structure will allow only constructors with parameters.|
|A class can implement one or more interfaces.||The structure can implement only interfaces that contain no members.|
To learn more about classes and structures in c#, visit our C# Tutorial.