Wednesday, 29 March 2017

Constructors and Its Types in C#

  • Constructor is a special method of a class which will invoke automatically whenever instance or object of class is created. Constructors are responsible for object initialization and memory allocation of its class. If we create any class without constructor, the compiler will automatically create one default constructor for that class. There is always at least one constructor in every class.
  • Here you need to remember that a class can have any number of constructors and constructors don’t have any return type, not even void and within a class we can create only one static constructor.
  • Generally constructor name should be same as class name. If we want to create constructor in a class we need to create a constructor method name same as class name check below sample method for constructor


class SampleA
{
public SampleA()
{
Console.WriteLine("Sample A Test Method");
}
}

Types of Constructors

Basically constructors are 5 types those are

      1.    Default Constructor
      2.    Parameterized Constructor
      3.    Copy Constructor
      4.    Static Constructor
      5.    Private Constructor

Default Constructor

A constructor without having any parameters called default constructor. In this constructor every instance of the class will be initialized without any parameter values like as shown below


using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample()     // Default Constructor
{
param1 = "Welcome";
param2 = "Aspdotnet";
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample();   // Once object of class created automatically constructor will be called
Console.WriteLine(obj.param1);
Console.WriteLine(obj.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below

Output


Welcome
Aspdotnet

Parameterized Constructors

A constructor with at least one parameter is called as parameterized constructor. In parameterized constructor we can initialize each instance of the class to different values like as shown below


using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y)     // Declaring Parameterized constructor with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample("Welcome","Aspdotnet");   // Parameterized Constructor Called
Console.WriteLine(obj.param1 +" to "+ obj.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below

Output


Welcome to Aspdotnet

Constructor Overloading

In c# we can overload constructor by creating another constructor with same method name and different parameters like as shown below


using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;

public Sample()     // Default Constructor
{
param1 = "Hi";
param2 = "I am Default Constructor";
}
public Sample(string x, string y)     // Declaring Parameterized constructor with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample();   // Default Constructor will Called
Sample obj1=new Sample("Welcome","Aspdotnet");   // Parameterized Constructor will Called
Console.WriteLine(obj.param1 + ", "+obj.param2);
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
When we run above program it will show output like as shown below


 

Output


Hi, I am Default Constructor
Welcome to Aspdotnet

Copy Constructor

A parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance. Check below example for this


using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y)
{
param1 = x;
param2 = y;
}
public Sample(Sample obj)     // Copy Constructor
{
param1 = obj.param1;
param2 = obj.param2;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample("Welcome", "Aspdotnet");  // Create instance to class Sample
Sample obj1=new Sample(obj); // Here obj details will copied to obj1
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below

Output


Welcome to Aspdotnet

Static Constructor

When we declared constructor as static it will be invoked only once for any number of instances of the class and it’s during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.


using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
static Sample()
{
Console.WriteLine("Static Constructor");
}
public Sample()
{
param1 = "Sample";
param2 = "Instance Constructor";
}
}
class Program
{
static void Main(string[] args)
{
// Here Both Static and instance constructors are invoked for first instance
Sample obj=new Sample();
Console.WriteLine(obj.param1 + " " + obj.param2);
// Here only instance constructor will be invoked
Sample obj1 = new Sample();
Console.WriteLine(obj1.param1 +" " + obj1.param2);
Console.ReadLine();
}
}
}
When we run above program we will get output like as shown below

Output


Static Constructor
Sample Instance Constructor
Sample Instance Constructor
Importance points of static constructor

-      Static constructor will not accept any parameters because it is automatically called by CLR.
-      Static constructor will not have any access modifiers.
-      Static constructor will execute automatically whenever we create first instance of class
-      Only one static constructor will allowed.

Private Constructor

Private constructor is a special instance constructor used in a class that contains static member only. If a class has one or more private constructor and no public constructor then other classes is not allowed to create instance of this class this mean we can neither create the object of the class nor it can be inherit by other class. The main purpose of creating private constructor is used to restrict the class from being instantiated when it contains every member as static.


using System;
namespace ConsoleApplication3
{
public class Sample
{
public string param1, param2;
public Sample(string a,string b)
{
param1 = a;
param2 = b;
}
private Sample()  // Private Constructor Declaration
{
Console.WriteLine("Private Constructor with no prameters");
}
}
class Program
{
static void Main(string[] args)
{
// Here we don't have chance to create instace for private constructor
Sample obj = new Sample("Welcome","to Aspdotnet");
Console.WriteLine(obj.param1 +" " + obj.param2);
Console.ReadLine();
}
}
}

Output


Welcome to Aspdotnet

In above method we can create object of class with parameters will work fine. If create object of class without parameters it will not allow us create.


// it will works fine
Sample obj = new Sample("Welcome","to Aspdotnet");
// it will not work because of inaccessability
Sample obj=new Sample();
Important points of private constructor

-      One use of private construct is when we have only static member.
-      Once we provide a constructor that is either private or public or any, the compiler will not allow us to add public constructor without parameters to the class.
-      If we want to create object of class even if we have private constructors then we need to have public constructor along with private constructor

Passing Data [View-to-Controller, Controller-to-View & Controller-to-Controller in ASP.NET MVC

View-to-Controller

Let us first discuss how to pass data from a ASP.NET MVC View to Controller. There are four ways to pass the data from View to Controller which are explained below:
  1. Traditional Approach: In this approach, we can use the request object of the HttpRequestBase class. This object contains the input field name and values as name-value pairs in case of the form submit. So we can easily get the values of the controls by their names using as indexer from the request object in the controller.
    For example: Let's say you are having an input in the form with name 'txtName', then its values can be retrieved in controller from request object like below:
    string strName = Request["txtName"].ToString();
  2. Through FormCollection: We can also get post requested data by the FormCollection object. This object also has requested data as the name/value collection as the Request object.
    For example:
    [HttpPost]
    public ActionResult Calculate(FormCollection form) 
    {
            string strName = form["txtName"].ToString();
            . . . . . . . . . . . . . . . . . . . . 
    }
  3. Through Parameters: We can also pass the input field names as parameters to the post action method by keeping the names same as the input field names. These parameters will have the values for those fields and the parameter types should be string. Also, there is no need to define the parameters in any specific sequence.
    For example:
    [HttpPost]
    public ActionResult Calculate(string txtName)
    {
        string strName = Convert.ToString(txtName);
        . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 
    }
    In all of the above approaches, we need to even convert the non-string type to string type due to which if any parsing fails, then the entire action may fail here. Here we have to convert each value to avoid any exceptions but, in the below 4th approach of passing data from view to controller, it reduces the amount of code.
  4. Strongly typed model binding to view: Here, we need to create a strongly typed view which will bind directly the model data to the various fields of the page.
    For example:
    1. Create a model with the required member variables.
      Let's say we have a model named 'Person' with member variable named as 'Name'
    2. Now pass the empty model to the view as parameter in the controller action.
      For example:
      public ActionResult GetName()
      {
          Person person = new Person();
          return View(person);
      }
    3. Prepare the strongly typed view to display the model property values through html elements as below:
      For example:
      <div><%= Html.Encode(person.Name) %></div>
    4. Create the action method that handles the POST request & processes the data.
      For example:
      [HttpPost]
      public ActionResult GetPersonName(Person person)
      {    
          return Content(person.Name.ToString());
      }

Controller-to-View

There are three options to pass information from controller to view. They are mentioned below:
  1. ViewData: The ViewData is a Dictionary of objects that are derived from the 'ViewDataDictionary' class and its having keys as string type and a value for respective keys. It contains a null value on each redirection and it needs typecasting for complex data types.
    For example: Assign value in controller action like:
    ViewData["PersonName"] = "Test Name";
    Fetch this ViewData value in View like this:
    <h1><%= ViewData["PersonName"]  %></h1>
  2. ViewBagViewBag is just a dynamic wrapper around ViewData and exists only in ASP.NET MVC 3. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. It doesn't require typecasting for complex data types. It also contains a null value when redirection occurs.
    For example: Assign value in controller action like:
    ViewBag.PersonName= "Test Name";
    Fetch this ViewData value in View like this:
    <h1><%= ViewBag.PersonName  %></h1>
  3. TempDataTempData by default uses the session to store data, so it is nearly same to session only, but it gets cleared out at the end of the next request. It should only be used when the data needs only to persist between two requests. If the data needs to persist longer than that, we should either repopulate the TempData or use the Session directly.
    For example:
    In Controller : TempData["PersonName"] = "Test Name";
    In View:
    <h1><%= TempData["PersonName"]  %></h1>

Controller-to-Controller

If it's not private, just pass it as JSON object on the URL using the third parameter in the redirect as given in the below example:
return RedirectToAction("ActionName", "ControllerName", new { userId = id });
If it is private data, we can use TempData - which will be removed at the end of the request after the next request reads it.