Monday 25 February 2013

CONSTRUCTORS IN C# .NET


What is constructor?
  • It is a special type of method and name of the class and constructor is same
  • Constructor pass his all function to the new keyword because than new keyword will allocate memory for them
  • Constructor allow only the non static variable for memory allocation for them
  • It never be return type or also not void type
  • We cann’t used inheritance also
  • Constructor is used to initialize an object (instance) of a class.
  • Constructor is a like a method without any return type.

Constructors generally following types :
  • Default Constructor
  • Parameterized constructor
  • Copy Constructor
  • Static constructor
  • Private constructor
The constructor goes out of scope after initializing objects.

Default Constructor

A constructor that takes no parameters is called a default constructor.
When a class is initiated default constructor is called which provides default values to different data members of the class.

You need not to define default constructor it is implicitly defined.

Practical: Default Constructor
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace default_constructor
{

class c1
{
int a, b;

public c1()
{
this.a = 10;
this.b = 20;
}

public void display()
{

            MessageBox.Show(a.ToString());
        MessageBox.Show(b.ToString());

  }

  }

  

  static void Main(string[] args)

  {

  // Here when you create instance of the class default constructor will be called.

  c1 ob1 = new c1();

  ob1.display();

  Console.ReadLine();

  }

  }

  }
//Write in Class Library 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace constrrec
{
    class employee
    {
        public employee()
        {
            MessageBox.Show("Hello manish.......!");
        }
    }
}
 
 
//Write in Window or console Application
 
 
        employee emp;
 
        private void button3_Click(object sender, EventArgs e)
        {
            emp = new employee();
 
            // that is Intilization of the emp , and when you Initilize the
            //class without parameter  then default constructor will be call
        }
 





Parameterized constructor


Constructor that accepts arguments is known as parameterized constructor. There may be situations, where it is necessary to initialize various data members of different objects with different values when they are created. Parameterized constructors help in doing that task.

Practical: Parameterized Constructor
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication12
{
    class Class1
    {

        int a,b;
       string h;
        public Class1()
        {
            this.a = 343;
            this.b = 234;
        }
        public Class1(int x, int z)
        {
            this.a = x + z;
            this.b = x - z;
        }
        public Class1(int s, int y, int r, int t)
        {
            s = y + r + t;
            this.a = s;
        }
        public Class1(string s, string b)
        {
            this.h = s + b;
        }
           
           
        public void display()
        {
            MessageBox.Show(a.ToString());
            MessageBox.Show(b.ToString());
            MessageBox.Show(h.ToString());
        }
 
    }
}
s}
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication12
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Class1 ob = new Class1();
            ob.display();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //Class1 ob = new Class1(2, 4,4,9);
            //ob.display();
            Class1 ob = new Class1("welcome", "ducat");
            ob.display();
        }
    }
}
 




Static Constructors


C# supports two types of constructor, a class constructor static constructor and an instance constructor (non-static constructor).

Point to be remembered while creating static constructor:
1. There can be only one static constructor in the class.
2. The static constructor should be without parameters.
3. It can only access the static members of the class.
4. There should be no access modifier in static constructor definition.



Static members are preloaded in the memory. While instance members are post loaded into memory.
Static methods can only use static data members.




Practical: Static Constructor

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class test
{
static string name;
static int age;

static test()
{
    System.Windows.Forms.MessageBox.Show("welcome to static constructor");
name = "John Sena";
age = 23;
}

public static void display()
{
    System.Windows.Forms.MessageBox.Show("using static constructor");
    System.Windows.Forms.MessageBox.Show(name.ToString());
    System.Windows.Forms.MessageBox.Show(age.ToString());

}

    }
}

namespace constructor
{
       


Copy Constructor

If you create a new object and want to copy the values from an existing object, you use copy constructor.
This constructor takes a single argument: a reference to the object to be copied.

Practical: Copy Constructor
using System;

  using System.Collections.Generic;

  using System.Linq;

  using System.Text;

  

  namespace copy_constructor

  {

  

  class Program

  {

  

  class c1

  {

  int a, b;

  

  public c1(int x, int y)

  {

  this.a = x;

  this.b = y;

  }

  

  
 
 


  // Copy construtor 

  public c1(c1 a)

  {

  this.a = a.a;

  this.b = a.b;

  }

  

  public void display()

  {

  int z = a + b;

  Console.WriteLine(z);

  }

  }

  

  


  static void Main(string[] args)

  {

  c1 ob1 = new c1(10, 20);

  ob1.display();

  // Here we are using copy constructor. Copy constructor is using the values already defined with ob1

  c1 ob2 = new c1(ob1);

  ob2.display();

  Console.ReadLine();

  }

  }

  }

Copy constructor sets behavior during runtime. It is shallow copying.
 
Private constructors
Example
Private constructors are used to restrict the instantiation of object using "new" operator.  A private constructor is a special instance constructor. It
is commonly used in classes that contain static members only.

This type of constructors is mainly used for creating singleton object.
If you do not want the class to be inherited we declare its constructor
private.
We can not initialize the class outside the class or the instance of class
can not be created outside if its constructor is declared private.
We have to take help of nested class (Inner Class) or static method to
initialize a class having private constructor.

Note:- Private constructor should be parameter less

//In class library 
 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace constrrec
{
    public class employee
    {  
       private employee()
        {
         }      
    } 
       
}
 
// when you will create the object of the employee class and compile the or execute the program  
// then you will find an error .
 
// LIKE
 
------------------------------------------------------------------------------
 
employee obj =new employee();



CONSTRUCTOR CHAINING

constructor chaining is the chain of the constructor which is executed sequencely. It depends of the overload of the constructor , actually it is 
part of the Inheritance This concept makes sure that the matching base class 
constructor must be called based on the parameter passed to the child class 
constructor.

EXAMPLE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace WindowsFormsApplication1
{
    class abc
    {
        public abc()
        {
            System.Windows.Forms.MessageBox.Show("welcome");
        }
        public abc(int a)
            : this()
        {
            System.Windows.Forms.MessageBox.Show("a=="+a);
        }
 
        public abc(int a,int b):this(a)
        {
            int c = a + b;
            System.Windows.Forms.MessageBox.Show("a+b=="+c);
 
        }
    }
}
 
//write in window application
 
 
      abc obj;      //class object
        private void button1_Click(object sender, EventArgs e)
        {
            obj = new abc(1,9);
        }
 
 // I  just  passed these value to call only one constructor but it will return three answer ...........
 // these are the following .






ARRAY IN C# .NET



as we have seen earlier, an array is a sequential collection of elements of similar data types. In c# , an array is an object and thus a reference type, and therefore they are  stored in heap.
Single dimensional  array
// int[] num = new int[5]{1,2,3,4,5};

            int[] num = new int[5];

            num[0] = 12;
            num[1] = 34;
            num[2] = 31;
            num[3] = 64;
            num[4] = 87;
            foreach (int j in num)
            {
                listBox1.Items.Add(j);
            }
        }

Multidimensional array and jagged array
A muntidimensional array is one in which each element of the array is an array itself.
Rectangular array( one in which each row contains an equal of columns)
Jagged array(one in which each row does not necessarily contain an equal number of element

int[,] mytable = new int[2, 3];

//int[,] numbers = {{0, 2}, {4, 6}, {8, 10}, {12, 17}, {16, 18}};
Or

            mytable[0, 0] = 23;
            mytable[0, 1] = 21;
            mytable[0, 2] = 53;
            mytable[1, 0] = 65;
            mytable[1, 1] = 12;
            mytable[1, 2] = 25;
            foreach (int i in mytable)
            {
                listBox1.Items.Add(i);
            }


Instantiating and accessing jagged array
 A jagged aray is one in which the length of each row is not the same. For example we may wish to create a table with 3 rows where the length of first row is 3, second row is 5 and  third row is 2, we can instantiate this jagged array like this:
int[][] mytable = new int[3][];
            mytable[0] = new int[3];
            mytable[1] = new int[5];
            mytable[2] = new int[2];

            mytable[0][0] = 3;
            mytable[0][1] = 23;
            mytable[0][2] = 32;

            mytable[1][0] = 1;
            mytable[1][1] = 35;
            mytable[1][2] = 36;
            mytable[1][3] = 13;
            mytable[1][4] = 64;

            mytable[2][0] = 98;
            mytable[2][1] = 76;

            foreach (int[] row in mytable)
            {
                foreach (int col in row)
                {
                    listBox1.Items.Add(col);
                }

            }





Friday 22 February 2013

OPERATORS IN C# .NET


                    OPERATORS IN C# .NET




The Assignment Operator

variable_name = expression;

int  i=45;






The ? Operator

C/C++ contains a very powerful and convenient operator that replaces certain
statements of the if-then-else form. The ternary operator ? takes the general form

Exp1 ? Exp2 : Exp3;

where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The ? operator works like this: Exp1 is evaluated. If it is true, Exp2 is evaluated
and becomes the value of the expression. If Exp1 is false, Exp3 is evaluated and its
value becomes the value of the expression. For example, in
x = 10;
y = x>9 ? 100 : 200;
y is assigned the value 100. If x had been less than 9, y would have received the value
200.





The if Statement

if(condition)
{
statement sequence
}
else
{
statement sequence
}



The if-else-if Ladder

A common programming construct that is based upon the nested if is the if-else-if ladder. It
looks like this:

if(condition)
{
statement;
}
else if(condition)
{
statement;
}
else if(condition)
{
statement;
}
...
else
{
statement;
}
The switch Statement

switch()
 {
case 1:
{
statement sequence;
break;
}
case 2:
{
statement sequence;
break;
}
case 3:
{
statement sequence
break;
}
.
.
.
default:
statement sequence
}


// Use goto with a switch.
using System;
class SwitchGoto {
static void Main() {
for(int i=1; i < 5; i++) {
switch(i) {
case 1:
Console.WriteLine("In case 1");
goto case 3;
case 2:
Console.WriteLine("In case 2");
goto case 1;
case 3:
Console.WriteLine("In case 3");
goto default;
default:
Console.WriteLine("In default");
break;
}
Console.WriteLine();
}


One good use for the goto is to exit from a deeply nested routine. Here is a simple
example:
// Demonstrate the goto.
using System;
class Use_goto {
static void Main() {
int i=0, j=0, k=0;
for(i=0; i < 10; i++) {
for(j=0; j < 10; j++ ) {
for(k=0; k < 10; k++) {
Console.WriteLine("i, j, k: " + i + " " + j + " " + k);
if(k == 3) goto stop;
}
}
}
stop:
Console.WriteLine("Stopped! i, j, k: " + i + ", " + j + " " + k);
}
}


Increment and Decrement
x = x + 1;
is the same as
x++;
x +=1;

++x; // prefix form
or as
x++; // postfix form


and
x = x - 1;
is the same as
x--;
x =-1;

can be written as
- -x; // prefix form
or as
x- -; // postfix form

x = 10;
y = ++x;
In this case, y will be set to .

x = 10;
y = x++;
then y will be set to .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 1;
            Console.WriteLine("Series generated using y = x + ++x;");
            for (int i = 0; i < 10; i++)
            {
                int y = x + x++; // prefix ++
                Console.WriteLine(y + " ");
            }
        }

The output is shown here:
Series generated using y = x + x++;
2
4
6
8
10
12
14
16
18
20
Series generated using y = x + ++x;
3
5
7
9
11
13
15
17
19
21






















// Compute the sum and product of the numbers from 1 to 10.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int prod;
            int sum;
            int i;
            sum = 0;
            prod = 1;
            for (i = 1; i <= 10; i++)
            {
                sum = sum + i;
                prod = prod * i;
            }
            Console.WriteLine("Sum is " + sum);
            Console.WriteLine("Product is " + prod);
        }
    }
}

The output is shown here:
Sum is 55
Product is 3628800



// Demonstrate Math.Sin(), Math.Cos(), and Math.Tan().
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Double theta; // angle in radians
            for (theta = 0.1; theta <= 1.0; theta = theta + 0.1)
            {
                Console.WriteLine("Sine of " + theta + " is " +
                Math.Sin(theta));
                Console.WriteLine("Cosine of " + theta + " is " +
                Math.Cos(theta));
                Console.WriteLine("Tangent of " + theta + " is " +
                Math.Tan(theta));
                Console.WriteLine();

            }
        }
    }
}

Here is a portion of the program’s output:
Sine of 0.1 is 0.0998334166468282
Cosine of 0.1 is 0.995004165278026
Tangent of 0.1 is 0.100334672085451
Sine of 0.2 is 0.198669330795061
Cosine of 0.2 is 0.980066577841242
Tangent of 0.2 is 0.202710035508673
Sine of 0.3 is 0.29552020666134
Cosine of 0.3 is 0.955336489125606
Tangent of 0.3 is 0.309336249609623




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
          int i;
Console.WriteLine("Value\tSquared\tCubed");
for(i = 1; i < 10; i++)
Console.WriteLine("{0}\t{1}\t{2}", i, i*i, i*i*i);

           
        }
    }
}



Value Squared Cubed
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729


// Determine if a number is prime. If it is not, then
// display its largest factor.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            int num;
            int i;
            int factor;
            bool isprime;
            for (num = 2; num < 20; num++)
            {
                isprime = true;
                factor = 0;

                for (i = 2; i <= num / 2; i++)
                {
                    if ((num % i) == 0)
                    {
                        isprime = false;
                        factor = i;
                    }


                    if (isprime)
                        Console.WriteLine(num + " is prime.");
                    else
                        Console.WriteLine("Largest factor of " + num +
                        " is " + factor);
                }
            }
            }
        }
    }

   
   

The output from the program is shown here:
2 is prime.
3 is prime.
Largest factor of 4 is 2
5 is prime.
Largest factor of 6 is 3
7 is prime.
Largest factor of 8 is 4
Largest factor of 9 is 3
Largest factor of 10 is 5
11 is prime.
Largest factor of 12 is 6
13 is prime.
Largest factor of 14 is 7
Largest factor of 15 is 5
Largest factor of 16 is 8
17 is prime.
Largest factor of 18 is 9



// to get the reverse no.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
     {
        static void Main(string[] args)
        {
            int num;
            int nextdigit;
            num = 123;
            Console.WriteLine("Number: " + num);
            Console.Write("Number in reverse order: ");
            do
            {
                nextdigit = num % 10;
                Console.Write(nextdigit);
                num = num / 10;
            } while (num > 0);
            Console.WriteLine();


        }
    }
}