So firstly we'll start from the definition of each and then we'll go through the similarities and the differences between them.
Q.What is a Class?
A.Classes are blueprints(building block) describing attributes(properties) and behavior(methods) that you use to create objects while programming.
Q.What is a Structure?So, these were the definitions of Classes and Structures.
A.Similarly as of a Class,Structures are also another user defined data type that are available in C# that allows to combine data items of different kinds.
Now, Let's find out the Similarities and Differences between Classes and Structure.
Here are some differences between a Class and a Struct.
Class | Struct |
---|---|
Classes are reference types | Structs are value types. |
Can support inheritance | Cannot support inheritance |
The reference can be null | Cannot have a null reference (unless Nullable is used) |
Have memory overhead per new instance | Do not have a memory overhead per new instance - unless 'boxed' |
Class can have default constructor. | Struct can only have parametrized constructors. |
Class can both implement interfaces and inherit interfaces. | Struct can’t inherit or implement interfaces. |
Class | Struct |
---|---|
Can Implement Interfaces. | Can Implement Interfaces. |
Members are Private by default. | Members are Private by default. |
Can have Main() | Can have Main() |
Can have Parameterized constructor | Can have Parameterized constructor(but with the condition that “constructor must initialize all the member variables.”) |
Can have methods. | Can have methods. |
1 2 3 4 | public interface MyInterface { int foo(); } |
1 2 3 4 | public class MyClass { int a; } |
1 2 3 4 | public class MyClass: MyInterface { int a; } |
1 2 3 4 5 6 7 8 | public class MyClass : MyInterface { int a; public void foo() { return a; } } |
Summary:
So, Guys this is all about the similarities and differences between a class and a struct.
I Hope in this post I have covered all the points about Classes and Structs which will be helpful to you.
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
0 comments:
Post a Comment
If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.