This Tutorial Explains Some of the Important Concepts in C# Programming Such as Constructor, Destructors, Static Class, Structs And Enums:
In one of our previous tutorials on Objects and Classes, we learned what a class and an object are.
An object is similar to a real-world object and a class is a logical collection of similar kinds of objects. It is one of the most fundamental types present in C#. In this tutorial, we will dive deep into the other related C# concepts.
=> Explore Complete C# Training Series Here
In this tutorial, we will be learning about some important aspects of classes and how can we use them in our programs. We will try to create simple C# programs based on the concepts that we learned in our previous tutorials.
Table of Contents:
What Is A Constructor In C#?
The constructor is a special type of method in C# programming language that is called or invoked automatically when an object of the given class is created.
Its main function is to initialize the data members of the newly created object. One of the most distinctive features of the constructor is its name. It has the same name as the class.
The constructors are basically of two types:
- Default
- Parameterized
C# Default Constructor
As the name suggests the default constructor is the basic constructor of a class. It does not have any argument and is directly invoked at the time of object creation.
public class Program { public Program(){ Console.WriteLine("Constructor has been invoked"); } public static void Main(string[] args) { Program p = new Program(); } }
The output of the following program will be:
Constructor has been invoked
Explanation
We have defined a constructor “Program” inside the class “Program”. Now when we initialize the class inside the main method, the constructor is invoked automatically.
Hence, whatever code snippet we have kept inside the constructor will get invoked. Here, we have printed a message “Constructor has been invoked” within the constructor curly braces, so when we initialize the class, the constructor by default will get initialized and the message will be printed as the output.
Parameterized Constructor
As the name suggests parameterized constructors are the constructor with parameters. These constructors are used to pass different values to the objects.
public class Details { public Details(int a, int b){ int c = a+b; Console.WriteLine("The sum is: "+ c); } } public class Program { public static void Main(string[] args) { Details d = new Details(2, 3); } }
The output of the following program will be:
The sum is: 5
Explanation
In our previous example with the default constructor, we have our main method in the same class. In this example, we are having the main method in a different class.
We have one class named “Details” that contains a parameterized constructor accepting two integer values. Inside the constructor, we are printing the summation of the integers. We have another class called “Program” that contains our main method. Inside the main method, we have initialized the “Details” class.
As explained earlier, when a class is initialized, its constructors are called automatically. Thus, in this case, our constructor method “Details” have been invoked and when we passed the parameter during initialization, it prints the output.
Destructors In C#
Destructors are just the opposite of constructors. It is a special method of the class that is invoked when a class object goes out of scope. Similar to a constructor, a destructor name is also exactly the same as that of the class name but with a prefix of “ ~ ” (tilde).
Destructor neither accepts any parameter not does it return any value. Destructor destructs the class objects, hence it is mainly used to release memory after the program is executed. Another important thing to note about destructor is that it can neither be overloaded nor it can be inherited.
Example Of Destructors:
public class Program { public Program(){ Console.WriteLine("Constructor has been invoked"); } ~Program(){ Console.WriteLine("Destructor has been invoked"); } public static void Main(string[] args) { Program p = new Program(); } }
The output of the following program will be:
Constructor has been invoked
Destructor has been invoked
Explanation
We used the same example that we used to learn constructor. We have just added a destructor in the program class (~Program). When we initialize the object of the class the constructor gets invoked and the object of the class is created. This prints the phrase “Constructor has been invoked” to the console.
When the execution has been completed and the class object goes out of scope, the program moves towards destructor. The destructor is then invoked, which in turn destructs the object. Here, we have printed a message inside the destructor, that gets printed to console after the destructor is invoked.
Static Members In A Class
The members of the class can be declared static using the static keyword. When an object is declared as static, irrespective of the number of objects created there will be only one copy of the static object.
Being static implies that there will be a single instance of the member that will exist for a given class. It means that the value of the static function or variables inside the class can be invoked without creating an object for them.
Static variables are used for declaring constants as their values can be obtained directly by invoking the class rather than creating an instance of it.
Example:
public class Details { public static void stat(){ Console.WriteLine("Static method invoked"); } } public class Program { public static void Main(string[] args) { Details.stat(); } }
The output of the following program will be:
Static method invoked
Explanation
In the above example, we have created a class “Details” that contains a static method “stat”. We have another class “Program” that contains the main method. In our previous topics, we saw, how we can initialize a class to access methods. But as we discussed, the static members of the class can be accessed with class object initialization.
Thus, in the main method, we have just invoked the method using the class directly without creating any object. The output of the program executed the code written inside the static method. In this case, we have printed a message to the console.
Static Class In C#
A static class is similar to a normal class in C#. The static class can have only static members and it cannot be instantiated. A static class is used to make sure that the class is not instantiated. A static class is declared by using the keyword static before the keyword class during the declaration.
Example:
public static class Details { public static void multiply(int a, int b){ int c = a*b; Console.WriteLine("Multiplication result is: "+c); } } public class Program { public static void Main(string[] args) { Details.multiply(2,8); } }
The output of the following program will be:
Multiplication result is: 16
Explanation
In the above example, we have created a static class “Details” and inside the static class we have created another static method “multiply”. Inside the method, we have some code snippets that we want to execute. We also have another class “Program” with the main method.
Inside the main method, we have invoked the multiply method present inside the static class. If you look at our main method you will see that we have not initialized or created an object for the static class instead we have directly invoked the class from the main method.
Thus, when we directly invoke the multiply method using the class name and by providing parameters, it executes the code and prints the output.
Structs In C#
Value type entity in the C# is called structure. It helps the user to store related data of several different data types in a single variable. As stated a structure is a value type entity that holds fields, methods, constructors, operators, events, etc. A structure is declared by using the “struct” keyword.
Features of Structs:
- It can include Constants, Methods, Properties, Index, Operators, Constructors, etc.
- It cannot have any default constructor.
- It can implement an interface but cannot inherit with other structs or classes.
- Structs are required to be initialized by using a new keyword for usage.
Difference Between Struct And Class
Struct and Class may feel similar to each other in some way, but they have several differences.
The differences include:
- A struct is a value type whereas a class is a reference type.
- The new keyword is required to initialize structs.
- Structs can have only parameterized constructor and on the other hand, a class can have both default and parameterized constructors.
Struct: Definition
A structure can be defined by using the struct keyword. A struct can define a new data type with several different members for the program.
A struct can be initialized in a way similar to that of an object initialization i.e. by using the new keyword. As a struct is a value type entity it is faster to operate than a class object. Wherever there is a need to store data, we need to use a struct. On the other hand, if you need to transfer data then it is advisable to use class than a struct.
Example:
public struct Cuboid { public int length; public int width; public int height; } public class Program { public static void Main(string[] args) { Cuboid cb = new Cuboid(); cb.length = 10; cb.width = 20; cb.height = 30; Console.WriteLine("The volume of cuboid is: {0}", (cb.length*cb.width*cb.height)); } }
The output of the following program will be:
The volume of the cuboid is: 6000
Explanation
In the above example, we defined a struct cuboid inside which we stored data types for length, width, and height of the cuboid. We have another class program where we have our main method.
In the main method, we initialize the “Cuboid” struct by using the new keyword. Then we used the object to call and assign values to the data types stored in the struct. Then we performed an operation on the variables from the struct and printed the result on the console.
So, if you want to use any property, events or methods, the struct must be initialized using the new keyword or else it will give you a compilation error.
Enums In C#
Enum is a set of integer constants and similar to a struct it is also a value type entity. It is mainly used to declare a list of integers by using the “enum” keyword inside a namespace, class or even struct. In enum, we provide a name to each of the integer constants, so that we can refer them using their respective names.
Enum can have a fixed number of constants. It helps in improving safety and can also be traversed.
Features of Enum
- Enum improves the readability and maintainability of the code by providing meaningful names to the constants.
- Enum cannot be used with the string type constants.
- Enum can include constants such as int, long, short, byte, etc.
- By default, the value of enum constants starts with zero
Declaring an enum
The syntax for declaring enum is given below.
enum <name of enum> { list of integer constants };
All the enum constants have default values. The value starts at 0 and moves its way up one by one.
Example:
public enum Cuboid{ length, width, height } public class Program { public static void Main(string[] args) { int l = (int)Cuboid.length; int w = (int)Cuboid.width; int h = (int)Cuboid.height; Console.WriteLine("The length is :{0}”, l); Console.WriteLine("The width is :{0}”, w); Console.WriteLine("The height is :{0}”, h); } }
The output of the following program will be:
The length is :0
The width is :1
The height is :2
Explanation
We worked with a similar example that we learned during struct. In this example, we have created an enum named Cuboid. This enum contains three members i.e. length, width, and height.
We have another class Program inside which we have our main method. An explicit cast has been used to convert enum type variables into integer type, then we have stored their values in different variables inside the main method and printed them to console.
By default, the value of the first enum will be zero, the second one will have 1 and so on. Hence, when we printed the values we received the aforementioned output.
Changing The Value Of Enum
Enum also allows users to change the default starting index of the members. Once you have changed the starting index of the variable, the subsequent members will have their values updated in the incremental sequence.
Let’s assign a value to the first member of the enum that we defined in our previous example and see what happens:
public enum Cuboid { length = 10, width, height } public class Program { public static void Main(string[] args) { int l = (int)Cuboid.length; int w = (int)Cuboid.width; int h = (int)Cuboid.height; Console.WriteLine("The length is :{0}”, l); Console.WriteLine("The width is :{0}”, w); Console.WriteLine("The height is :{0}”, h); } }
The output of the following program will be:
The length is :10
The width is :11
The height is :12
Explanation
When we assigned the first member of the enum with a value, then all the subsequent members of the enum will get assigned with the increment of that value. As we have defined, the first value as 10, the subsequent value becomes 11 and the next one becomes 12.
The user can assign any value as per their choice and all the members of the enum will get auto-assigned with the increment of the user-defined values.
Properties In C#
Properties in C# are basically the named member of interface, classes, and struct. Properties are an extension of the member variables/method of struct or class. They are used to read, write or change the value of the private fields.
Properties are accessed just like the fields. They have accessors that can be used to get, set and compute the values. We can also put logic while setting values in the properties. It can also be used with the private class which restricts access from outside, but at the same time, it allows the user to use properties for getting or setting values.
What Are Accessors?
Accessors of property constitute the statements that can be used to read, write or compute a given property. The declaration of property can contain get, set or both.
Example:
public class Cube { private int side; //Declare a Side property of type integer public int Side{ get{ return side; } set{ side = value; } } } public class Program { public static void Main(string[] args) { Cube cb = new Cube(); cb.Side = 5; Console.WriteLine("The volume of cube is :{0}", (cb.Side * cb.Side* cb.Side)); } }
When the above code snippet is successfully compiled and executed, the following output is observed.
The volume of cube is :125
Explanation
In the above example, we have a class “Cube” inside which we have declared a “Side” property of type integer. After that, we have get and set property where we have returned and provided the value to the variable side.
We have another class “Program” with the main method inside which we have initialized the Cube class and provided the value for the Side property, and then we have printed the computed result to the console.
Conclusion
In this tutorial, we learned about the member functions of the class. A member function can operate on any object of the class where it is present. We also learned about constructors and destructors.
Constructors are initialized automatically at the time of class object creation whereas destructors destruct the class and are mainly used to remove the memory allocation after completion of execution. Constructors can be of two types i.e. default and parameterized.
The destructor doesn’t accept any parameter nor does it return any value. Both Constructor and Destructors have names that are exactly the same as the class name. We also learned about static variables and static class and how they can be accessed without using any class instances. We came to know that a static class can only have static members.
We also discussed Structs or structures. The Structs are value type entities and need to be initialized for access.
Enum and properties of C# were also discussed. Enum is a set of named integer constant. Similar to the struct, it is also a value type entity. The enum will have its members and each member will have their own default value.
At the end, we discussed properties, that are an extension of the member variables/method of struct or class. They are used to get, set or change the value of the private fields.
=> See Our Complete C# Training Series Here