Introduction to ASP.NET MVC using C#

Getting Started
Start by running Visual Studio 2010  and select New Project from the Start page.



Visual Studio 2010 - Start Page
Visual Studio 2010 – Start Page
Creating Your First Application
You can create ASP.NET MVC Web applications using either Visual Basic or Visual C# as the programming language. Select Visual C# on the left and then select ASP.NET MVC 2 Web Application. Name your project “MvcBook” and then click OK.
ASP.NET MVC 2 Web Application
ASP.NET MVC 2 Web Application

This creates a simple “Hello World!” MVC project

MVC Home Controller Page
MVC Home Controller Page

Click Debug menu, select Start Debugging or Press F5

Visual Studio launches a browser and opens the application’s home page.
MVC 2 Application Home Page
MVC 2 Application Home Page

 

What is Construction Overloading in C#

Constructor Overloading
Constructor oveloading enables to have constructors with different sets of parameters.

Example below:

public class Employee
{
    public Employee()
    {
        // This is the no parameter constructor method.
        // First Constructor
    }
    public Employee(int Age)
    {
        // This is the constructor with one parameter i.e. Age.
        // Second Constructor
    }
    public Employee(int Age, string Name)
    {
        // This is the constructor with two parameters i.e. Age and Name.
        // Third Constructor
    }
   
}
Call to the constructor now depends on the way you instantiate the object.

For example:

Employee objEmp = new Employee()
// At this time the code of no parameter 
// constructor (First Constructor)will be executed
Employee objEmp = new Employee(12)
// At this time the code of one parameter 
// constructor(Second Constructor)will be
// executed.
 

Naming Conventions -C# Coding Guidelines

C#.NET Coding Guidelines

Naming Conventions

1. Prefix member variables with the underscore ‘_’.
2. Do not prefix member variables with “this”.
3. Use camelCasing for member variables.
4. Use camelCasing for parameters
5. Use camelCasing for local variables
6. Use PascalCasing for function, property, event, and class names.
7. Prefix interfaces names with “I”

Platform Invoke – C#

Platform Invoke – C#

A platform invoke call to an unmanaged DLL function

When platform invoke calls an unmanaged function, it performs the following sequence of actions:

  1. Locates the DLL containing the function.
  2. Loads the DLL into memory.
  3. Locates the address of the function in memory and pushes its arguments onto the stack, marshaling data as required.

    Note   Locating and loading the DLL, and locating the address of the function in memory occur only on the first call to the function.

  4. Transfers control to the unmanaged function.

Platform Invoke example below :

using System.Runtime.InteropServices;

public class Win32 {
     [DllImport(“user32.dll”, CharSet=CharSet.Auto)]
     public static extern int MessageBox(int hWnd, String text,
                     String caption, uint type);
}

public class HelloWorld {
    public static void Main() {
       Win32.MessageBox(0, “Hello World”, “Platform Invoke Sample”, 0);
    }
}     

Why C# does not support multiple class inheritance ?

Why C# does not support multiple class inheritance ?

Multiple inheritances are not supported in C#.

Consider the below example.

public class Class1
    {
        public string GetClass()
        {
            return "This is Class1";
        }
    }
    public class Parent2
    {
        public string GetClass()
        {
            return "This is Class2";
        }
    }

    public class SubClass: Class1, Class2
    {
        public string GetCorrectClass()
        {
            return this.GetClass();
        }
    }

Here there are two Parent class Class1 and Class2. This is inherited by Child class SubClass.

In GetCorrectClass method, child class calls the parent class method GetClass(). In such case which method will be executed?

It is very difficult for CLR to identify which method to call. It shows that multiple inheritance will create ambiguity to oops concept. In order to avoid this ambiguity we do not have multiple class inheritance and we have  multiple interface implementations in C#.

What is params keyword in C# ?

The params keyword lets you specify a method parameter that takes a variable number of arguments.

No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

You can send a comma-separated list of arguments of the type specified in the parameter declaration, or an array of arguments of the specified type. You also can send no arguments

Example :
public static void UseParams(params int[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + ” “);
}
Console.WriteLine();
}
We can call above method

Way 1 :
// You can send a comma-separated list of arguments of the specified type.
UseParams(1, 2, 3, 4);

Way 2 :
// An array argument can be passed, as long as the array
// type matches the parameter type of the method being called.

int[] myIntArray = { 5, 6, 7, 8, 9 };
UseParams(myIntArray);

Way 3:
UseParams();

C# FAQS : Class Modifiers , Static constructors , Destructors , Indexers

C# FAQS : Class Modifiers , Static constructors , Destructors , Indexers

Class

Various class modifiers are listed below :

  1. new

  2. public

  3. protected

  4. internal

  5. private

  6. abstract

  7. sealed

  8. static

Class – new modifier

The new modifier is permitted on nested classes. It specifies that the class hides an inherited member by the same name. It is a compile-time error for the new modifier to appear on a class declaration that is not a nested class declaration.

Class – Abstract modifier

An abstract class cannot be sealed.

Class – sealed modifier

A sealed class cannot also be an abstract class.

Class – static modifier

A static class declaration is subject to the following restrictions:
·         A static class may not include a sealed or abstract modifier. Note, however, that since a static class cannot be instantiated or derived from, it behaves as if it was both sealed and abstract.
·         A static class may not include a class-base specification  and cannot explicitly specify a base class or a list of implemented interfaces. A static class implicitly inherits from type object.
·         A static class can only contain static member. Note that constants and nested types are classified as static members.
·         A static class cannot have members with protected or protected internal declared accessibility.

Static constructors

Static constructors have the following properties:
  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.

Destructors

  • Destructors cannot be defined in structs. They are only used with classes.
  • A class can only have one destructor.
  • Destructors cannot be inherited or overloaded.
  • Destructors cannot be called. They are invoked automatically.
  • A destructor does not take modifiers or have parameters.
  • Indexers Overview


    • Indexers enable objects to be indexed in a similar way to arrays.
    • A get accessor returns a value. A set accessor assigns a value.
    • The this keyword is used to define the indexers.
    • The value keyword is used to define the value being assigned by the set indexer.
    • Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.
    • Indexers can be overloaded.
    • Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array.

    Singleton Design Pattern in C#

    Singleton Design Pattern in C#

    Singleton Design pattern ensures a class has only one instance and provide a global point of access to it.

    Simple Singleton Design Pattern – Not thread safe

    Code Snippet showing a simple Singleton Design pattern :
    ///

    /// The ‘Singleton’ Design Pattern
    ///

    public class Singleton
    {
    // Define a static class variable
    private static Singleton _instance;
    // Have a private Constructor
    private Singleton()
    {
    }
    public static Singleton Instance()
    {
    // Uses lazy initialization.
    // Note: this is not thread safe.
    if (_instance == null)
    {
    _instance = new Singleton();
    }
    return _instance;
    }
    }
    Above implementation has below advantages:

    • Singleton provides lazy instantiation i.e the instantiation is not performed until an object asks for an instance. Lazy instantiation avoids instantiating unnecessary singletons when the application starts.

    Above implementation has below disadvantages:

    •Above implementation of Singleton class is not safe for multithreaded environments. If separate threads of execution enter the Instance property method at the same time, more that one instance of the Singleton object may be created.
    Below are two approaches solve this problem.

    1. One approach is to use Double-Check Locking .
    2. Second approach is to use static initialization approach.

    Singleton Design Pattern – Static Initialization

    public sealed class Singleton

    {
        private static readonly Singleton instance = new Singleton();
        private Singleton(){}
        public static Singleton Instance
       {
           get { return instance; }
        }
    }
    The class is marked sealed to prevent derivation, which could add instances. The variable is marked readonly, which means that it can be assigned only during static initialization (which is shown here) or in a class constructor.

    Singleton Design Pattern – Thread safe

    Code Snippet showing a Thread Safe Singleton Design pattern :
    ///

    /// The ‘Singleton’ Design Pattern
    ///

    public class Singleton
    {
    // Define a static class variable
    private static Singleton _instance;
    private static object syncRoot = new Object();
    // Have a private Constructor
    private Singleton()
    {
    }
    public static Singleton Instance()
    {
    // Uses lazy initialization.
    // Note: this is thread safe.
    lock (syncRoot)
    {
    if (_instance == null)
    _instance = new Singleton();
    }
    return _instance;
    }
    }