user155776
0
Q:

default constructor in c#

/*
Default Constructor

A constructor with no parameters is called a default constructor. 
A default constructor has every instance of the class to be initialized 
to the same values. The default constructor initializes all numeric fields 
to zero and all string and object fields to null inside a class.
*/
// C# Program to illustrate calling 
// a Default constructor 
using System; 
namespace DefaultConstructorExample { 

class Geek { 

	int num; 
	string name; 

	// this would be invoked while the 
	// object of that class created. 
	Geek() 
	{ 
		Console.WriteLine("Constructor Called"); 
	} 

	// Main Method 
	public static void Main() 
	{ 

		// this would invoke default 
		// constructor. 
		Geek geek1 = new Geek(); 

		// Default constructor provides 
		// the default values to the 
		// int and object as 0, null 
		// Note: 
		// It Give Warning because 
		// Fields are not assign 
		Console.WriteLine(geek1.name); 
		Console.WriteLine(geek1.num); 
	} 
} 
} 

//Output:
Constructor Called

0
2
//The Class
public class MyClass
{
  	//Some Variables
	public readonly int var1;
  	public readonly string var2;
  	//readonly only lets you set it ina constructor	
  
  	//The Constructor (public [class name](parameters))
  	public MyClass(int param1, string param2)
    {
      	//Setting the earlier variables
     	var1 = param1;
      	var2 = param2;
    }
}

//Creating an object using that class
MyClass Class1 = new MyClass(10, "Hello, World!");
MyClass Class2 = new MyClass(9999, "This is the second object!");

Console.WriteLine(Class1.var1);
Console.WriteLine(Class2.var2);

//Output
//10
//This is the second object!
2

New to Communities?

Join the community