Differences between Class and Structure
- Classes are Reference types and Structures are Values types.
When I say Classes are reference types, basically they will contain the address of an instance variables. For example:
Class MyClass { Public Int DataMember; //By default, accessibility of class data members //will be private. So I am making it as Public which //can be accessed out side of the class. }Inmainmethod, I can create an instance of this class usingnewoperator that allocates memory for this class and stores the base address of that intoMyClasstype variable.
Static Public void Main (string [] arg) { MyClass _myClassObject1 =new MyClass (); _ myClassObject1.DataMember=10; MyClass _myClassObject2 =_myClassObject1; _ myClassObject2.DataMember=20; }
In the above program, “MyClass _myClassObject2 =_myClassObject1” instruction indicates that both variables of typeMyClass myClassObject1andmyClassObject2will point to the same memory location. It basically assigns the same memory location into another variable of same type.
So if any changes that we make in any one of the objects typeMyClasswill have an effect on another since both are pointing to the same memory location.
“_ myClassObject1.DataMember=10” at this line both the object’s data members will contain the value of10._ myClassObject2.DataMember=20at this line both the object’s data member will contains the value of20. Eventually, we are accessingdatamembers of an object through pointers.
Unlike classes, structures are value types. For example:
Structure MyStructure { Public Int DataMember; //By default, accessibility of Structure data //members will be private. So I am making it as //Public which can be accessed out side of the structure. } Static Public void Main (string [] arg) { MyStructure _myStructObject1 =new MyStructure (); _ myStructObject1.DataMember=10; MyStructure _ myStructObject2 =_ myStructObject1; _ myStructObject2.DataMember=20; }In the above program, instantiating the object ofMyStructuretype usingnewoperator and storing address into_myStructObjectvariable of typeMyStructureand assigning value10to data member of the structure using “_ myStructObject1.DataMember=10”. In the next line, I am declaring anothervariable_myStructObject2of typeMyStructureand assigning_myStructObject1into that. Here .NET C# compiler creates another copy of_myStructureObject1object and assigns that memory location intoMyStructurevariable_myStructObject2.
So whatever change we make on_myStructObject1will never have an effect on another variable_myStructObject2of typeMyStructrue. So that’s why we are saying Structures are value types.
So the immediate Base class for class isObjectand immediate Base class for Structure isValueTypewhich inherits fromObject.
- Classes will support an Inheritance whereas Structures won’t.
How are we saying that? And what is the reason behind that? The answer is Classes.
It can beabstract,sealed,static, andpartialand can’t bePrivate,Protectedandprotected internal.
Why do we want to have class as Abstract?
Abstract–Abstractclasses are incomplete classes, i.e., they will have combination of implemented and unimplemented methods along with data members, properties, events, delegates and indexers.
The main idea to have class asabstractis to have onlyBaseclass that can be derivable and that will have basic functionality. As I mentioned above, we can have unimplemented method inabstractclass that gives flexibility to derived classes to implement as required along with basic functionality. And also, we can’t instantiate object ofabstractclass.Abstractclass can be with/withoutabstractmethods. But if methods are declared asabstractin a class, that class also should be declared asabstract.
Sealed–Sealedclasses are classes that are not inheritable. Methods also can besealed, that is, those methods declared assealedcan’t be overridable, i.e., derived classed can’t override those methods. And normal classes can’t havesealedmethod.Sealedkeyword should be declared withoverridekeyword in the derived class' method for whichbaseclass will havevirtualmethod.
Why do we want to have class and method as Sealed?
The reason to have class and method as sealed is to stop the inheritance at one level.
Where to use sealed?
If you think that class is not to be inherited in your design, you can use class assealed. Butsealedclass can inherit from interface and class. If you thinkvirtualmethod cannot to be inherited in derived class at one stage, we can declare a method with sealed+override combination.
By default structures aresealed, that is the reason structures are not supporting inheritance.
Why do we want to have class and methods as static?
In your design, if you feel that a class should have a set of methods which operate only on arguments that we pass without initiating object of that class, then we can make that class asstaticclass (Example:System.Math). Merely call those instance methods by class name.
How this class will be loaded without creating an object?
If your code accesses any ofstaticclass’s methods, then this is the responsibility of CLR (Common Language Runtime) to load this class into memory once which is the lifetime of your application.
Object ofstaticclass can’t be instantiated. Why? Sincestaticclass can’t have instance constructor.Staticclass supports inheritance but other classes can’t inherit fromstaticclass, i.e.,staticclasses are sealed. Classes can havestaticmethods butstaticclasses can’t have instance member and instance methods.if, should be declared withstatickeyword.
Staticclass is useful when you implement Singleton Design pattern.
What does partial modifier indicate?
Partial key word is to declare the class as partial meant to say it splits the classes into multiple parts under the same class name in a single namespace.
Why? So that developers can implement the functionally for the same class parallely.
But all combined will give one class. Each split class can have instance variable, instance methods, properties, indexers, events and delegates.
Structures can’t have modifiers likeabstract,sealed, andstaticwhereas classes can have.
Both structure and class can have partial modifiers.
As I mentioned earlier, structures can have method declaration but notvirtualandsealedmethods. Why? Since those two are essential for inheritance. Anyhow, the structure won’t support inheritance and declaring methods using those two keywords will throw compile time errors.
- Classes can have explicitly parameterless constructors whereas structures can’t.
- Member variable initialization is possible in class whereas in Structures, it is not.
- It is not possible to declare destructor in structure but in class it is possible.
- Process of converting structure type into object type is called
boxing and process of converting object type into structure type is
called unboxing.
Example:
int a=10;
Object ob = (object) a; //Boxing a= (int) obj; //Unboxing
- The “
this” keyword gives different meaning in structure and class. How?- In class, “
this” keyword is classified as value type of class type within which it is used like inside instance constructor or instance method. - In structure, “
this” keyword is classified as variable type of structure type within which it is used.
- In class, “
When to Use Structure and Class?
In general, classes can be used when you have more complex behavior or data. And if you think that these behaviour or data to be modified after creating an instance of class, then classes are absolute methods.Structures can be used for small data structures. If developer feels that data members of structure cannot to be modified after creating structure, then having structure will suit.
Difference between class and struct in C# .Net
1. Classes are reference types and structs are value types.Since classes are reference type, a class variable can be assigned null.But we cannot assign null to
a struct variable, since structs are value type.
2. When you instantiate a class, it will be allocated on the heap.When you instantiate a struct, it gets created on the stack.
3. You will always be dealing with reference to an object ( instance ) of a class. But you will not be dealing with references to an instance of a struct ( but dealing directly with them ).
4. When passing a class to a method, it is passed by reference. When passing a struct to a method, it’s passed by value instead of as a reference.
5. You cannot have instance Field initializers in structs.But classes can have
example:
class MyClass
{
int myVar =10; // no syntax error.
public void MyFun( )
{
// statements
}
}
struct MyStruct
{
int myVar = 10; // syntax error.
public void MyFun( )
{
// statements
}
}
6. Classes can have explicit parameterless constructors. But structs cannot have
7. Classes must be instantiated using the new operator. But structs can be
8. Classes support inheritance.But there is no inheritance for structs.
( structs don’t support inheritance polymorphism )
9. 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 not
12. classes are used for complex and large set data. structs are simple to use.
No comments:
Post a Comment