C# Constructor –Learn with Programming Example

Constructors
In this chapter you will learn:

  • What is Constructor?
  • How to initialize Constructor?
  • Programming Example of C# Constructor?

What is Constructor?

A constructor is a special method which is used to initialize object when it is created. To understand its definition we take an example.
You are creating a class in which you are required a temperature value in centigrade and in then use that value in entire class. A constructor is used here for initialize object with value.

Output

36 degree centigrade into fahrenheit = 96.8
I am second constructorDestructor Initializes, Cleanup Process Complete
__
  • Explanation

    Constructor Creating
    In this program, we have created two constructors and both need a parameter passed to it while initialize object. One constructor is for getting integer value and another one is for displaying message on screen. Notice that both constructors have same name as class but have different parameter. You may create as much constructor as you need with different parameter or number of parameter.

     

    Object Initialization
    In the Main method we have initialized object and while initialization of object we passed parameter in it.

     

    Destructor
    We have also used Destructor in this program to free up system resources and cleanup memory. It is good habits to use destructors to avoid security breaches.

     

    Summary

    In this chapter we have learned how to use constructor and destructor in c sharp programming. In the next chapter you will learn Destructor (~)


    Leave a Reply

    Your email address will not be published. Required fields are marked *