Tuesday, 23 September 2014

Performance of Arrays vs. Lists

In a small number of tight-loop processing code where I know the length is fixed I use arrays for that extra tiny bit of micro-optimisation; arrays can be marginally faster if you use the indexer / for form - but IIRC believe it depends on the type of data in the array. But unless you need to micro-optimise, keep it simple and use List<T> etc.
Of course, this only applies if you are reading all of the data; a dictionary would be quicker for key-based lookups.
Here's my results using "int" (the second number is a checksum to verify they all did the same work):
(edited to fix bug)
List/for: 1971ms (589725196)
Array/for: 1864ms (589725196)
List/foreach: 3054ms (589725196)
Array/foreach: 1860ms (589725196)
based on the test rig:
using System;
using System.Collections.Generic;
using System.Diagnostics;
static class Program
{
    static void Main()
    {
        List<int> list = new List<int>(6000000);
        Random rand = new Random(12345);
        for (int i = 0; i < 6000000; i++)
        {
            list.Add(rand.Next(5000));
        }
        int[] arr = list.ToArray();

        int chk = 0;
        Stopwatch watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            int len = list.Count;
            for (int i = 0; i < len; i++)
            {
                chk += list[i];
            }
        }
        watch.Stop();
        Console.WriteLine("List/for: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        chk = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                chk += arr[i];
            }
        }
        watch.Stop();
        Console.WriteLine("Array/for: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        chk = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            foreach (int i in list)
            {
                chk += i;
            }
        }
        watch.Stop();
        Console.WriteLine("List/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        chk = 0;
        watch = Stopwatch.StartNew();
        for (int rpt = 0; rpt < 100; rpt++)
        {
            foreach (int i in arr)
            {
                chk += i;
            }
        }
        watch.Stop();
        Console.WriteLine("Array/foreach: {0}ms ({1})", watch.ElapsedMilliseconds, chk);

        Console.ReadLine();
    }

Indexers In C#

C# introduces a new concept known as Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C# community. Defining a C# indexer is much like defining properties. We can say that an indexer is a member that enables an object to be indexed in the same way as an array.
this [argument list] 
{ 
    get 
    { 
        // Get codes goes here 
    } 
    set 
    { 
        // Set codes goes here 
    } 
} 
Where the modifier can be private, public, protected or internal. The return type can be any valid C# types. The 'this' is a special keyword in C# to indicate the object of the current class. The formal-argument-list specifies the parameters of the indexer. The formal parameter list of an indexer corresponds to that of a method, except that at least one parameter must be specified, and that the ref and out parameter modifiers are not permitted. Remember that indexers in C# must have at least one parameter. Other wise the compiler will generate a compilation error.

The following program shows a C# indexer in action
// C#: INDEXER 
using System; 
using System.Collections; 

class MyClass 
{ 
    private string []data = new string[5]; 
    public string this [int index] 
    { 
       get 
       { 
           return data[index]; 
       } 
       set 
       { 
           data[index] = value; 
       } 
    } 
}

class MyClient 
{ 
   public static void Main() 
   { 
      MyClass mc = new MyClass(); 
      mc[0] = "Rajesh"; 
      mc[1] = "A3-126"; 
      mc[2] = "Snehadara"; 
      mc[3] = "Irla"; 
      mc[4] = "Mumbai"; 
      Console.WriteLine("{0},{1},{2},{3},{4}",mc[0],mc[1],mc[2],mc[3],mc[4]); 
   } 
} 

Oops InterView

1.) What is object oriented programming (oops) Language?                                       
oops is is a methodology to write the program where we specify the code in form of classes and objects .oops supports   three important features which are given below:
  • Encapsulation 
  • Inheritance
  • Polymorphism
Note:- Abstraction is also basic oops concepts feature.But mainly three important feature of oops.

2.) What is object based Language?                                                                                 
Object based language supports all features of oops except two features which are given below:
  • Inheritance
  • Late binding
3.) What are three principle of  an object oriented language?                                    
  • Encapsulation 
  • Inheritance
  • Polymorphism
4.) Which property of  an object oriented programming is known as data hiding or information hiding? 
Encapsulation

5.) What is Class in c#?                                                                                                        
A Class is a user-defined data type with a template that servers to define its properties.

6.) How does declare the  Class in c#?                                                                              
Syntax:
                       Class classname
                        {
        
                         }
                             
OR


                      Class classname
                        {
                              Variable declaration;
                              Method declaration;
                         }

7.) Which types of properties includes in c# class ?                                                  
  • Indexers
  • Operators
  • Constructors
  • Destructors

8.) What is instance variables  in c# ?                                                                             
Data is encapsulated in a class by placing data fields inside the body of the class .These variables are called instance variables.We can create the instance variables exactly the same way as we create local variable.
Ex. 
        Class student
            {
                   string name;           //instance variables
                   int age      ;               //instance variables
                   money   salary;     //instance variables
          
           }

9.) What is an object  in c# ?                                                                                            
An object is Run time entity of any class,structure or union.
EX.
           Class student
               {
                        int x=10;
                        int y = 20;
                        public void display()
                            {
                                  console.WriteLne(+x);
                                  console.WriteLne(+y);
                               }
                   student st = new student()         //object "st" created
                     st.display();               // Here "st" object is calling the display method of student class
                 }

10.) What is difference between object and instance ?                                                 
An instance is a declaration time entity but an object is a Run time entity in class,structure or union.

11.) What is Method and how to declare it in class ?                                               
An method is used for manipulating the data contained in the class.Methods are used always declared inside the body of the class.
EX.
         class student
           {
              string name ;
              int age ;
            public void GetData (string s,int x)
                    {
                          name = s;
                          age = x ;
                          console.WriteLine(+s);
                          console.WriteLine(+x);
                     }
            }
12.) Can we placed method definition before instance variable in c# ?                   
Yes.

13.) Can we access the variable declared in other method within  same class ?     
NO.

14.) What is access-specifier or modifier in c# ?                                                            
More Details....

15.) How can create an object of class in c# ?                                                                 
C# uses New operator to create the object of the class.
Syntax:
classname objectname = new classname();
                            OR
classname objectname;
objectname=new classname();
EX.
student st = new student();
                            OR
student st;
st = new student();

16.) Can we create more than one object of a class  in c# ?                                         
Yes, all object are independent to each other ,means each have your copy of instance variable. 

17.) What is the syntax for accessing the class member in the class ?                    
Syntax:
objectname . variable name ;
objectname.methodname(parameter-list);

18.) What is constructor in c# ?                                                                                         
A constructor is like a method,It is used to initialization of data member of the class member , when it is created.
There are some properties of constructor in c#.
  • The name of constructor should be same as class name.
  • Constructors can be public,private or protected in the class.
  • Constructor are automatically called when object of class is created.
19.) Is constructor overloading is possible in c# ?                                                       
Yes.

20.) What is partial class in c# ?                                                                                        
More Details...

21.) What is use of 'this' keyword in c# ?                                                                        
There are some reason to use this keyword in c#.which are given below:
  • If we want to refer the current member of the current class then we can use 'this ' keyword to refer that member.
  • If we want to call a specific constructor of class through another constructor of same class the we can specify 'this' keyword without constructor.
  • We can use 'this' keyword when variable name and object name is same.

22.) What is Destructor in c# ?                                                                                         
Destructor is a method that is called when a object is no more required.The name of destructor is same as the class name.It is use prefix '~' .It is used ,to deallocate the memory used by resources within the class.
More Details...

23.) Can we use Nested classes,structs,interfaces and enums  in c# ?                      
Yes.

24.) What is Constant members in class and its use in c# ?                                        
It is used to declared the data fields of class as constant
EX.
           public const int size  =200;
In above Example,member size is assigned by 200 at compile time and can not be changed later.
Constant members are implicitly static often,we can not declare them explicitly using static.
EX.
public static const int size =200;
it is wrong ,it will give compile time error.

25.) What is Readonly members in c# ?                                       
Readonly are basically used to set the constant value at run time.Once value is assigned at run time then you can not change later. 
EX.
class student
{
public readonly int x;
public static readonly int y;
public student (int a)
{
m=x;
}
static student()
{
y=50;
}
}
26) What is properties in c# ?                                                                                           
More Details..

27) What is Indexer in c# ?                                                                                                
More Details..
Note:- Indexers are sometimes referred to as 'smart arrays'.

28) What is difference between property and Indexer in c# ?                                   
  • Indexer is always an instance member whereas property can be static member.
  • A Get accessor of a property corresponds to a method with no parameters whereas a Get accessor of an indexer's method the same formal parameter as the indexer.
  • A Set accessor of a property corresponds to a method method with the same formal parameter named value,whereas a set accessor of an indexer corresponds to a method with the same formal parameter list as the indexer and the parameter named value.
  • In Indexer,If we declare a local variable with same name as an indexer parameter then it will give error.

29) What is difference between static and Non static member in c# ?                     
More Details..

30) What is Inheritance in c# ?                                                                                       
In  Inheritance, reusability is achieved by designing new classes.Means Derived class inherits the properties of parents class.
More Details..

31) What is Encapsulation in c# ?                                                                                   
More Details..

32) What is Polymorphism in c# ?                                                                                   
Polymorphism,permits the same method name to be used for different operations in different classes.
More Details..

33) What is different form of inheritance in c# ?                                                         
  • Classical inheritance
  • Containment inheritance

34) What is Classical inheritance ?                                                                                   
A classical inheritance supports the "is relationship" between two classes. In this we can create a class hierarchy such that derived class B form , from the parent class A as shown below:
35) What are  the types of Classical inheritance ?                                                       
  • Single Inheritance
  • Multiple Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance
36) What is Containment inheritance in c# ?                                                                
A containment Inheritance supports the "has relationship" between two classes.
EX.
class Teacher
{
..........................
}
class student
{
Teacher T; //Teacher is contained in student.
student s;
.................................................................
}

In this ,object of Teacher(T) is contained in the object of student(s).Means when we create the object of student class then we can easily access the Teacher class member without creating the object of Teacher class.

37) How can we define the subclass in c# ?                                                               
When we define any sub class then we use : (colon operators).
Syntax:
class  subclass-name : Base classname
{
variables declaration;
Method declaration;
.........................................
}

Ex.
class student :Teacher
{

.....//includes the Teacher all fields here.
.....//include your own class features.

}
Description:In above Example,if we create the object of student class then we can easily access both class member data.

38) Is inheritance is transitive in nature ?                                                                      
No.

39) Is this is valid or invalid which are given below ?                                                  
class x : y
{
....................
}
class y : z
{
....................
}
class z : x
{
....................
}
Ans.It is invalid because classes circularly depend on themselves.

40) Is this is valid or invalid which are given below ?                                                 
class x
{
class y:x
{
..........................
}
..........................
}
Ans.It is valid because class does not dependent on the classes that are enclosed.

41) What are  the properties of inheritance in c#?                                                       
  • A derived class extends its direct base class.
  • Derived class can not change or remove the definition of an inherited member.
  • Constructors and destructors are not inherited.
  • Private member of base class can not inherited in child class(derived class).
  • An instance of a class contains a copy of all instance fields declared in the class and its base class.
  • A derived class can override an inherited member.
  • An declared class can hide an inherited members.

42) What do you mean by visibility control in c#?                                                       
In c# ,four types of accessibility modifier,which may be applied to classes and members to specify their level of visibility.
  • public
  • private
  • protected
  • Internal
43) What is "By default" mode of visibility  in c#?                                                       
If we do not explicitly set any modifier with the class then it will be By default"Internal"
Internal classes are accessible within the same program assembly and not accessible from outside the assembly.
More Details...

44) Can we access the all member of base class from derived class?                        
Yes  --> if base class member are public.
No ---> if base class member are private.

45) Can we access the class member if class is private?                                               
No.

46) Can we access the class from outside if class is public and data members are public?
No.

47) What is the accessibility constraints  in c#?                                                           
  • An  accessibility domain of a member is never larger than of the class.
Ex.
class x
{
private class y
{
public int a;
}
}

we can not  access the public data 'a' from the outside the class y.
  • All base class accessibility must be at least accessible as derived class itself.
Ex.

class x
{
.....................
}
class y :x
{
......................
}
It is illegal because x is internal ,we can not access the internal class from the derived class.
  • The return type of method must be at least as accessible as method itself.
EX.
class x
{
......................
}
public class y
{
     x method()
{
.....................//accessible
}
internal x method()
{
..................//accessible
}
public A method ()
{
.....................//not accessible because public is higher than internal

}
Note:- A Method can not have an accessibility level higher than that of its return type.

48) How can access the base class constructor from the derived class                     constructor?
We can access the base class constructor using base keyword from the derived class constructor.
Ex.
using system;
class student
{
public int a;

public int b;
public student (int p,int q)  //base constructor
{
a=p;
b=q;
}
public int calculate()
{
return(a*b);
}
}
class Teacher:student //inheriting student
{
public teacher(int x,int y,int z):base(p,q)
{
int m=z;
}
public int display()
{
return(m*a*b);
}
}
public static void main()
{
Teacher t =new Teacher(15,10,5);
int area = student.show();             //base class method call
int volume = student.display(); //derived class method call
console.WriteLine("Area="+area);
console.WriteLine("Volume="+volume);
console.ReadLine();
}

49) Can we use base keyword instead of constructor logic?                                        
Yes,We use base keyword constructor as well as any sub class to access a public or protected member defined in a parent class.
Ex.
In above example ,we can access the member of base class in child class as:
base a = 20;
base b = 30;
int area = base.show()

50) What is order of execution of constructor in below example?                            
A()  class A         Base class
B()   class B         Derived class
c()  class c            derived class

51) What is method overloading in c#?                                                                           
More Details....

52) What is method Hiding in c#?                                                                                    
More Details....

53) What is abstract class and abstract method in c#?                                                
More Details....

54) What is sealed class in c#?                                                                                           
A class that can not be subclassed ,is called sealed class.

55) Can we inherit the sealed class in c#?                                                                       
No.

56) What is the use of sealed class  in c#?                                                                       
  • Sealed class is used to prevent any unwanted extensions to the class.led class allows the compiler to perform some 
  • Sealed class allows the compiler to perform some optimizations when a method of a sealed class is  invoked.
57) What is sealed methods  in c#?                                                                                   
A sealed Method is used to override an inherited virtual method with the same signature.
Ex.
class student 
{
public virtual void show()
{
console.WriteLine("Hello");
}
}
class teacher :student
(
     public sealed override void show()
{
console.writeLine("Bye");
}
}

Note:- Any derived class of 'teacher' can not further override the method show().

58) What are the types of polymorphism  in c#?                                                           
  • Operation polymorphism
  • Inclusion Polymorphism
59) What is operation polymorphism ?                                                                           
Operation polymorphism is implemented  with the help of overloaded methods and operators.
  • Method overloading
  • Operator overloading
Method overloading and operator overloading is known as  compiler binding or early binding or static binding.This also called compiler time polymorphism.

60) What is Inclusion polymorphism ?                                                                          
Inclusion polymorphism is implemented in the concept of method overriding.In method overriding we use virtual keyword.In method overriding object of class bind at run time,so it is called run time binding or late binding.It is also known as run time polymorphism.

61) What is an Identifier ?                                                                                                 
More Details........

62) What is Ad -hoc -polymorphism in c# ?                                                                    
Ad-hoc-polymorphism is another name of overloading.

63) What are benefits and goals of objected-oriented programming ?                     
  • Reliable
  • Maintainable
  • Extendable
  • Natural
  • Reusable
  • Time saving

Group by clause and Having clause In Sql Server

group by clause:-                                                                                                                                    
When we run aggregated function in select query,we get the output on the basis of all the records but if we want to use aggregated function,then we should give us output on the basis of group and column and we can used 'group by clause' before  grouping the records.If we want to keep some conditions,we can specify 'where' clause and after grouping the records if we want to some conditions then we can use 'having' clause.
There are some commands to explain the group by clause. which are given below:
1. ) First create a students table as shown below:




2. )  Use group by command as given below:
 
   select deptName,count(*) from students where salary>1000
   group by deptName
Output:-

3. ) Use group by and Having clause as given below:-

     select deptName,count(*) from students 
    group by deptName
    having COUNT(*)>1
 Output:-

4. ) Use group by , where clause and having clause as given below:-

      select deptName,count(*)as Total from students where salary >=300
      group by deptName
      having COUNT(*)>1
Output:-

ViewState, Session vs ViewState

You may save a lot of coding by maintaining the ViewState of the objects in your Web Form.

What is ViewState?
ViewState is used to maintain the state of controls during page postback and if we save any control values or anything in viewstate we can access those values throughout the page whenever it required for that check below simple example

Maintaining the ViewState

When a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted a form with a lot of information and the server comes back with an error. You will have to go back to the form and correct the information. You click the back button, and what happens.......ALL form values are CLEARED, and you will have to start all over again! The site did not maintain your ViewState.
When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. How come? This is because ASP .NET maintains your ViewState. The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a <form runat="server"> control. The source could look something like this:
<form name="_ctl0" method="post" action="page.aspx" id="_ctl0">
<input type="hidden" name="__VIEWSTATE"
value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" />

.....some code

</form>
Maintaining the ViewState is the default setting for ASP.NET Web Forms. If you want to NOT maintain the ViewState, include the directive <%@ Page EnableViewState="false" %> at the top of an .aspx page or add the attribute EnableViewState="false" to any control.
Look at the following .aspx file. It demonstrates the "old" way to do it. When you click on the submit button, the form value will disappear:

Example

<html>
<body>

<form action="demo_classicasp.aspx" method="post">
Your name: <input type="text" name="fname" size="20">
<input type="submit" value="Submit">
</form>
<%
dim fname
fname=Request.Form("fname")
If fname<>"" Then
Response.Write("Hello " & fname & "!")
End If
%>

</body>
</html>


Here is the new ASP .NET way. When you click on the submit button, the form value will NOT disappear:

Example

Click view source in the right frame of the example to see that ASP .NET has added a hidden field in the form to maintain the ViewState
<script runat="server">
Sub submit(sender As Object, e As EventArgs)
lbl1.Text="Hello " & txt1.Text & "!"
End Sub
</script>

<html>
<body>

<form runat="server">
Your name: <asp:TextBox id="txt1" runat="server" />
<asp:Button OnClick="submit" Text="Submit" runat="server" />
<p><asp:Label id="lbl1" runat="server" /></p>
</form>

</body>
</html>


View State

- View state is maintained in page level only.
- View state of one page is not visible in another page.
- View state information stored in client only.
- View state persist the values of particular page in the client (browser) when post back operation done.
- View state used to persist page-instance-specific data.

      Session State

- Session state is maintained in session level.
- Session state value is available in all pages within a user session.
- Session state information stored in server.
- Session state persist the data of particular user in the server. This data available till user close the browser or session time completes.
- Session state used to persist the user-specific data on the server side.

      Usage

- If you want to access the information on different web pages, you can use SessionState
- If you want to access from the same page, then you can use Viewstate

     Security

     Session state provides more security when compared with view state as the data value is stored in server side