Tuesday, 19 April 2016

Interviews Questions

 What is OOP?
OOP (Object Oriented Programming) is a programming technique in which programs are written on the bases of the object.

 What is a Class?
Class is a type. A class is a collection of objects of a similar type. Once a class is defined, any number of objects can be created which belong to that class. A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind. Class can also called the specifications of the objects.

 What is Object?
Object is an encapsulation of fields and related behaviors of a particular type (class).

 Pillars of OOP
i)Inheritance ii)Polymorphism iii)Encapsulation iv)Abstraction

 What is Inheritance? Real time Example?
Inheritance is an important concept of OOP in which one (child) class inherited all the members of the other (base, parent) class and may have also its own, e.g. Vehicle and Car relation, is a relationship defines the inheritance like car is a vehicle. Major benefit of inheritance is reuse.

Real time Example:
It is very simple. We ourselves are an example of this. Technically, we are derived from our parents and they are derived from grandparents and so on. But there is a difference. The derived class is always bigger than the base class but in our case, the child is always smaller than parents.

 What is Polymorphism? Real Time Example?
Polymorphism means many forms. For example one method of parent class with same name is use in different child or inherited classes with different functionality with slightly changing in method. There are mainly two types of polymorphism i)Overloading, ii)Overriding

Real time Example:
Let’s take the example of some words which can be used in different situations with different meaning. 'Watch' - watch can be used as a verb as well as a noun. "He is wearing a watch." In this it is used as a noun. "Watch your actions." In this it is used as a verb. Thus we see that the same word can be used in different situations differently. Likewise same operators or function names are used with various meanings in various situations.

• What is Encapsulation? Real Time Example?
Packing in one unit like capsule of a medicine. Remember Encapsulation is not a Data Hiding but leads to Data Hiding. Example include the object of the particular class can only use the data members of the class, any other object of different class cannot use it directly.

Real time Example:
How do u think a car runs? Is there only steering, brake and whatever you are able to see directly?? NO. There is many more parts inside to make it run. Engine, wires, tank etc. but we don't see it. Thus we can say that car is basically a collective unit of many parts which help it to run. Same way, in classes, we have functions and data members wrapped up together.

 What is Abstraction? Real Time Example?
Hide the detail from the user, e.g. the console class having multiple methods. The user use it only and not seen the code of the console class. Private Fields is an example of abstraction. Real life object have many type of data members, Capture only relevant details that are relevant to current perspective. In interview, the interviewer only focusing your abilities that he or she needed indeed. Abstraction can be very useful in Analysis and Design.

Real time Example:
Let’s continue with the above example for encapsulation. Suppose you start going for driving classes. Does the instructor teach you about the functioning of the engine?? NO. Why?? Because he knows that for driving, you don't need to know about the functioning of engine. All those are kept hidden from you.

 What is Overloading?
Overloading means that same name of method used with different parameters, sequence of parameters, number of parameters, types of parameters.

 What is Overriding?
Providing a different implementation for functionality of an inherited method is called method overriding.
Following are some basic rules for method overriding in .NET
♦Method must be inherited.
♦Signature (Name + Parameters of a method (type, kind (out, ref))) prams parameter is not included, return type and access modifier of inherited method and overridden method must be same/match.
♦Inherited method must be declared with the virtual or abstract keyword.
♦Override method must be declared with the override keyword.

 What is IL?
IL/MSIL/CIL- IL code is a CPU independent partially compiled code. It's partially compiled because we do not know in what kind of environment .Net code will run and on runtime IL Code will compile to machine code using the environmental properties (CPU, OS, machine configuration etc).

• What Type of Code that Language Compiler generates, then What JIT Compiler Generate?
MSIL (IL) is generated by .NET Complier from source code of any .NET language. Then this IL is compiled under JIT compiler that generate Machine Native code that is understand by underlying Operation System.

• Difference between Destructor and Garbage Collector
a. The garbage collector is a part of the .NET environment that keeps track of objects and makes sure that objects are removed from memory when they are no longer needed.

b. A destructor is a part of a class design. It's the opposite of a constructor. When you declare it the GC will call it when it destroys an object.

c. The destruct or is a special member function which is invoked when an object is destroyed. It is the last method run by a class. The garbage collector is part of the framework, automatically manages memory, and non-deterministically collects unreferenced objects to avoid memory leaks.

d. Both are used to destroy unallocated object in the memory.

e. Destroy are called CLR (Common Language Run time) and Garbage Collection called by .net Framework



(Practice Makes a Man Perfect)

CLR (Common Language Runtime)

CLR is the heart of the .Net framework and it does 4 primary important things:

I. Garbage collection
II. CAS (Code Access Security)
III. CV (Code Verification)
IV. IL (Intermediate Language) to Native translation.

As part of Microsoft's .NET Framework, the Common Language Runtime (CLR) is a .NET thread, which runs on the background that manages the execution of programs written in any of several supported languages, allowing them to share common object-oriented classes written in any of the languages. The Common Language Runtime is somewhat comparable to the JVM (Java Virtual Machine) that is provide by Sun Microsystems for running programs compiled from the Javalanguage. Microsoft refers to its Common Language Runtime as a "Managed Execution Environment." A program compiled for the CLR does not need a language-specific execution environment and can easily be moved to and run on any System with Windows 2000 or Windows XP or later.

Programmes writing in any of Visual C++, Visual Basic, C#, F# or J# compile their programs into an intermediate form of code called Common Intermediate Language ( CIL ) in a portable execution ( PE ) file that can then be managed and executed by the Common Language Runtime. The programmer and the environment specify descriptive information about the program when it is compiled and the information is stored with the compiled program as metadata . Metadata, stored in the compiled program, tells the CLR what language was used, its version, and what class libraries will be needed by the program. The Common Language Runtime allows an instance of a class written in one language to call a method of a class written in another language. It also provides garbage collecting (returning unneeded memory to the computer), exception handling, and debugging services etc.

I. CAS (Code Access Security)
CAS is a security model in .NET that restricts what managed code can do based on its origin (e.g., from the internet, local machine, etc.).

It enforces permissions like file access, network access, etc.

Example: Code from a web download may be denied file system access.

Note: CAS is deprecated in .NET Core and .NET 5+. It was used in .NET Framework only.

II. CV (Code Verification)
Code Verification ensures managed code is type-safe and memory-safe before execution.

The CLR checks IL code for valid types, stack usage, and access boundaries.

Prevents unsafe operations like buffer overflows or pointer misuse.

Following snapshot explain's actual working of CLR in .NET environment.

Actual Woking of CLR in Dot Net Environment


(Practice Makes a Man Perfect)

Monday, 18 April 2016

Constructors and Its types in C#

Constructor is a special method of a class that will be automatically invoked when an object of a class is created. Compiler will automatically create a default constructor in the class, if no constructor is created in the class. The default constructor initializes all numeric fields in the class to zero and all string and object fields to null. The main use of constructors is to initialize private fields of the class while creating an instance for the class.

A constructor doesn't have any return type, not even void. A class can have any number of constructors. A static constructor cannot be a parametrized constructor. Within a class you can create only one static constructor.

Following are types of Constructors:

1) Default Constructor:

Parameter less constructor is called a default constructor, means this type of constructor does not take parameters. The drawback of a default constructor is that every object of the class will be initialized to the same values and it is not possible to initialize each object of the class to different values. The default constructor initializes 1) All numeric fields in the class to zero 2) All string and object fields to null.

Example:

using System;

    namespace DefaultConstractorDemo
    {
        class DefaultConstractorDemoClass
        {
            public int firstNumber, secondNumber;
            public DefaultConstractorDemoClass()   //default contructor
            {
                firstNumber = 200;
                secondNumber = 450;
            }
            public static void Main()
            {
                DefaultConstractorDemoClass obj = new DefaultConstractorDemoClass(); //When an object is created , constructor is called
                Console.WriteLine(obj.firstNumber);
                Console.WriteLine(obj.secondNumber);
                Console.Read();
            }
        }
    }
When you run the application, the output will be as following:
200
450

2) Parameterized Constructor:

A constructor with at least one or more than one parameter is called a parametrized constructor. The main advantage of a parametrized constructor is that you can initialize each object of the class to different values.

Example:


using System;
    namespace DefaultConstractorDemo
    {
        class ParameterizedConstractorDemoClass
        {
            public int firstNumber, secondNumber;
            public ParameterizedConstractorDemoClass(int a, int b)  // Decalaring Paremetrized Constructor with int a,b parameter
            {
                firstNumber = a;
                secondNumber = b;
            }
        }
        class MainClass
        {
            static void Main()
            {
                ParameterizedConstractorDemoClass obj = new ParameterizedConstractorDemoClass(500, 800);   // Creating object of Parameterized Constructor and give values to it

                Console.WriteLine("Value of a = " + obj.firstNumber);
                Console.WriteLine("Value of b = " + obj.secondNumber);

                Console.Read();
            }
        }
    }
When you run the application, the output will be as in the following:
Value of a = 500
Value of b = 800

3) Copy Constructor:

The constructor which creates an object by copying attributes (variables) from another object is called a copy constructor. The purpose of a copy constructor is to initialize a new object to the values of an existing object.

Example:

using System;
    namespace CopyConstractorDemo
    {
        class Student
        {
            private string fullName;
            private int age;
            public Student(Student student)   // Declaring a Copy constructor.
            {
                fullName = student.fullName;
                age = student.age;
            }
            public Student(string name, int age)  // Instance constructor.
            {
                this.fullName = name;
                this.age = age;
            }
            public string DetailsOfStudent     // Get deatils of Student
            {
                get
                {
                    return " The age of " + fullName + " is " + age.ToString();
                }
            }
        }

        class StudentDetail
        {
            static void Main()
            {
                Student objStudent1 = new Student("Ghazi", 25);  // Create a new Student object.
                Student objStudent2 = new Student(objStudent1);  // Here is objStudent1 details is copied to objStudent2.
                Console.WriteLine(objStudent2.DetailsOfStudent);
                Console.ReadLine();
            }
        }
    }

Now run the program, the output will be as follows:

The age of Ghazi is 25

4) Static Constructor:

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. A static constructor does not take access modifiers or have parameters. The user has no control on when the static constructor is executed in the program. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file. When a constructor is created as static, it will be invoked only once for all of instances of the class and it is invoked during the creation of the first instance of the class or the first reference to a static member in the class. A static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.

Example:

using System;
    namespace StaticConstractorDemo
    {

        public class Teacher
        {
            static Teacher()// Static Constructor Declaration
            {
            }
            public static void Salary()
            {
                Console.WriteLine("This is from static void Salary() Method");
            }
        }
        class TeacherDetails
        {
            static void Main()
            {
                Teacher.Salary();
                Console.ReadLine();
            }
        }
    }
Now run the program, the output will be as follows:
This is from static void Salary() Method

5) Private Constructor:

It is not possible for other classes to derive from a class, if the constructor of this class is declare as private. Neither is it possible to create an object of this class. They are usually used in classes that contain static members only. It provides an implementation of a singleton class pattern. One use of a private constructor is when we have only static members.

Example:

using System;
    namespace ConstrcutorsDemo
    {
        public class MyCounter
        {
            private MyCounter()   //Decleration of Private
            {
            }
            public static int CurrentOnlineUsers;
            public static int TotalUsersVisited()
            {
                return ++CurrentOnlineUsers;
            }
        }
        class ViewOfVisitedUsers
        {
            static void Main()
            {
                //MyCounter aCounter = new MyCounter();   // Error : 'ConstrcutorsDemo.MyCounter.MyCounter()' is inaccessible due to its protection level

                MyCounter.CurrentOnlineUsers = 1300;
                MyCounter.TotalUsersVisited();
                Console.WriteLine("Now the count is: {0}", MyCounter.CurrentOnlineUsers);
                Console.ReadLine();
            }
        }
    }

Now run the program, the output will be as follows:

Now the count is : 1301



(Practice Makes a Man Perfect)