Wednesday 24 December 2014

What is class?

What is class?

Ans:- The class is collection of several thoughts in a single place. According to user we defined everything in class, so some persons speak class is user defined data type. Yes they are right. Class is a design time technique. Some persons also speak class is blue print but this sentence use only fresher’s not experience.
Syntax of class:-
Class class_name
{
// User defined place
[variable declaration;]
[method declaration;]
}
Ø By default class is internal in the same App_Domain.
Ø The class has two specifies- public or internal.
Ø By class we achieved proper encapsulation and abstraction.
Ø In C# Dot Net variable is declare class level not global variable in C# Dot Net.
Ø The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties to external interfaces.
Ø The class run on heap memory. (In detail see study stack and heap topic)

Example:- (1)
using System;
classclass_Demo
{
staticvoid Main(string[] args)
    {
Console.WriteLine("Hello Dear I Am Class Demo Example!");
Console.ReadLine();
    }
}

Example:- (2) Variable declaration
using System;
classclass_Demo
{
int X=10;  // int type variable
stringstr = "Bhagat Singh";\\ string type variable

staticvoid Main(string[] args)
    {
Console.WriteLine("X variable="+X);
Console.WriteLine("str variable="+str);
Console.ReadLine();
    }
}

Example:- (3)
using System;

class classdemo
{
    public void Disp()  //Method
    {
        Console.WriteLine("Hello Dear I Am Method");
    }
    static void Main(string[] args)
    {
        Console.WriteLine("Hello Dear I Am Class Demo Example!");
        Console.ReadLine();
    }
}

Note: C# classes don’t end semicolon (;) as C++.

Once a class is defined, you can add class members to it. Class members can include constants, fields, methods, properties, indexers, events, operators, instance constructors, static constructors, destructors, and nested type declarations. Each class member has an associated accessibility, which controls the scope of the member and defines whether these members are accessible outside the class.

Class Members


Table 9 describes allowable class member elements.

Table 9. A class members

CLASS MEMBER
INHERITANCE
Methods
Similar to C++ functions. Methods implement some action that can be performed by an object.
Properties
Provide access to a class attribute (a field). Useful for exposing fields in components.
Events
Used to provide notification.
Constants
Represents a constant value.
Fields
Represents a variable of the class
Operators
Used to define an expression (+, *,->, ++,[], and so on ).
Instance Constructors
Methods called during initialization of an object.
Static Constructors
Called automatically.
Destructors
Called when an object is being destroyed.
Indexers
A new concept in C#. An indexer provider indexing on an object. It allows you to treat a class as an array.
Types
All local types used in a class.



Before examining these members in detail, you’ll look at the accessibility of these members. Table 10 describes class member accessibility type and their scopes.

Table 10. Class member accessibility types and scopes

ACCESSIBLITY TYPE
SCOPE
Public
Member is accessible from other programs.
Protected
Member is accessible by the containing and its derived classes and types.
Internal
Member is accessible only the current program.
Protected internal
Member is accessible by the current program and the class derived from the containing class.



Now you’ll look at class members in more detail.

Fields


field member Represent a variable of a class. In this example, strClassName is a string type public variable that can be accessed by the class instance:

class myClass
{
      public static string strClassName;

      public void SetClassName(string strName)
      {
            strClassName = strName;
      }
}

As noted earlier; you can define field members as read-only. This means the field can only be assigned in the declaration or in the constructor of the class. See the following code:

class myClass
{
      public static readonly string strClassName = "myClass";

      public void SetClassName(string strName)
      {
            strClassName = strName; // illegal assignment
      }
}

Note that the complier will throw an error because of an illegal assignment.

If the field is not static, you have to access fields from the class instance. It’s the same idea as accessing a public variable in the C++ or structure in C. for example:

myClass cls = new MyClass();
string clsName = cls.strClassName;

Constants


constant Member represents a constant value throughout the program. For example the clsNodes is constant that has integer value 12. See the following code:

class myClass
{
      public const int clsNodes = 12;
}
The value of clsNodes will be 12 throughout the program and can’t be reassigned.

 

Constructor types with example programs in C#.NET





A special method of the class that will be automatically invoked when an instance of the class is created is called as constructor. 

Constructors can be classified into 5 types
1.     Default Constructor
2.     Parameterized Constructor
3.     Copy Constructor
4.     Static Constructor
5.     Private Constructor
Default Constructor : A constructor without any parameters is called as default constructor. Drawback of default constructor is every instance of the class will be initialized to same values and it is not possible to initialize each instance of the class to different values.


Parameterized Constructor : A constructor with at least one parameter is called as parameterized constructor. Advantage of parameterized constructor is you can initialize each instance of the class to different values.


Example for Parameterized Constructor
using System;namespace ProgramCall
{
    
class Test1
    {
        
//Private fields of class
        
int A, B;

        
//default Constructor
        
public Test1()
        {
            A = 10;
            B = 20;
        }

        
//Paremetrized Constructor
        
public Test1(int X, int Y)
        {
            A = X;
            B = Y;
        }



        
//Method to print
        
public void Print()
        {

            
Console.WriteLine("A  =  {0}\tB  =  {1}", A, B);
        }
        
                
    }


    
class MainClass
    {

        
static void Main()
        {

            
Test1 T1 = new Test1();  //Default Constructor is called
            
Test1 T2 = new Test1(80, 40); //Parameterized Constructor is called
          
            T1.Print();
            T2.Print();

            
Console.Read();
          
        }
    }

}

Output

A  =  10        B  =  20
A  =  80        B  =  40

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.

Example for Copy Constructor
using System;namespace ProgramCall
{

    
class Test2
    {

        
int A, B;

        
public Test2(int X, int Y)
        {
            A = X;
            B = Y;
        }

        
//Copy Constructor
        
public Test2(Test2 T)
        {
            A = T.A;

            B = T.B;
        }


       
        
public void Print()
        {

            
Console.WriteLine("A  =  {0}\tB  =  {1}", A, B);
        }
     

    }


    
class CopyConstructor
    {
        
static void Main()
        {
           

            
Test2 T2 = new Test2(80, 90);

            
//Invoking copy constructor
            
Test2 T3 = new Test2(T2); 
            
            T2.Print();
            T3.Print();

            
Console.Read();
        }
    }
}


Output

A  =  80        B  =  90
A  =  80        B  =  90

Static Constructor : You can create a constructor as static and when a constructor is created as static, it will be invoked only once for any number of instances of the class and it is 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.

Example for Static Constructor
using System;namespace ProgramCall
{
    
class Test3
    {

        
public Test3()
        {

            
Console.WriteLine("Instance  Constructor");
        }

        
static Test3()
        {
            
Console.WriteLine("Static  Constructor");
        }
    }
    
class StaticConstructor
    {
        
static void Main()
        {
            
//Static Constructor and instance constructor, both are invoked for first instance.
            
Test3 T1 = new Test3(); 

            
//Only instance constructor is invoked.
            
Test3 T2 = new Test3(); 
     

            
Console.Read();
        }
    }
}


Output

Static  Constructor
Instance  Constructor
Instance  Constructor
Private Constructor You can also create a constructor as private. When a class contains at least one private constructor, then it is not possible to create an instance for the class. Private constructor is used to restrict the class from being instantiated when it contains every member as static. 

Some unique points related to constructors are as follows
  • A class can have any number of constructors.
  • A constructor doesn’t have any return type even void.
  • A static constructor can not be a parameterized constructor.
  • Within a class you can create only one static constructor.
Destructor in C#.NET
A destructor is a special method of the class that is automatically invoked while an instance of the class is destroyed. Destructor is used to write the code that needs to be executed while an instance is destroyed. To create a destructor, create a method in the class with same name as class preceded with ~ symbol.
Syntax : 
~ClassName()
{
}


Example :
 The following example creates a class with one constructor and one destructor. An instance is created for the class within a function and that function is called from main. As the instance is created within the function, it will be local to the function and its life time will be expired immediately after execution of the function was completed.

using System;namespace ProgramCall
{
    
class myclass
    {

        
public myclass()
        {

            
Console.WriteLine("An  Instance  Created");
        }

        
//destructor
        ~myclass()
        {
            
Console.WriteLine("An  Instance  Destroyed");
        }
    }


    
class Destructor
    {
        
public static void Create()
        {
            
myclass T = new myclass();
        }


        
static void Main()
        {
            
            Create();
            
GC.Collect();

            
Console.Read();
        }
    }
}

Output

An  Instance  Created
An  Instance  Destroyed

Constructor Chaining
When a constructor calls another constructor in the same or base class(by using base and this keyword),called constructor chaining.
--By using base keyword a constructor can call constructor of another class.
--By using this keyword a constructor can call constructor of it's own class.
Example: -
using System;
abstract class college
{
    string name = "Santosh Kumar Singh";
    public college(int roll_no)
    {
        Console.WriteLine(name);
    }
}
class student : college
{
    public student(int r):base(r)
    {
        Console.WriteLine("Bye Bye Chandan Kumar");
    }
    public static void Main()
    {
        student s = new student(3033);
        Console.ReadLine();
    }
}

Out Put

Santosh Kumar Singh 
Bye Bye Chadan Kumar 

Methods

method is a member that implements some functionality. It’s similar in appearance to the methods found in C++ and java. A method can return a value have, a list of parameters, and can be accessed through the class, whereas non - static. Static methods are accessed through the class, whereas non-static methods are accessed through the instance of the class. For example, listing 28 adds a method sum to the class myClass and called this method from the Main method.
  Class method example:-
using System;
class myClass
{
public int Sum(int a, int b)
{
int res = a + b;
return res;
}
}
class TestmyClass
{
static void Main()
{
myClass cls = new myClass();
int total = cls.Sum(5, 8);
Console.WriteLine(total.ToString());
}
}
Methods in C# support function overloading in a similar way as C++. If you have programmed in C++, you’ll notice that C# methods are similar to C++ functions (and almost mirror those methods found in java). So it’s not a bad idea to call function overloading in C# method overloading. In listing 29, I over- overload the Sum method by passing in different types of values and call each of the overloaded Sum methods from the Main method.
  Method overloading example
                                                                                                                                                                                          
using System;
class myClass
{
      public int Sum(int a, int b)
      {
            int res = a + b;
            return res;
      }
      public float Sum(float a, float b)
      {
            float res = a + b;
            return res;
      }

      public long Sum(long a, long b)
      {
            long res = a + b;
            return res;
      }
      public long sum(long a, long b, long c)
      {
            long res = a + b + c;
            return res;
      }
      public long Sum(int[] a)
      {
            int res = 0;
            for (int i=0; i < a.Length; i++)
            {
                  res += a[i];
            }
            return res;
      }

      public void Sum()
      {
            //return nothing
      }
}
class TestmyClass
{
      static void Main()
      {
            myClass cls = new myClass();
            int intTot = cls.Sum(5,8);
            Console.WriteLine("Return integer sum:"+ intTot.ToString());
            cls.Sum();
            long longTot = cls.Sum(Int64.MaxValue - 30, 8);
            Console.WriteLine("Return long sum:" + longTot.ToString());
            float floatTot = cls.Sum(Single.MaxValue-50, 8);
            Console.WriteLine("Return float sum:" + floatTot.ToString());
            int[] myArray = new int[] {1,3,5,7,9};
            Console.WriteLine("Return sum of array = {0}",
                  cls.Sum(myArray).ToString());
      }
}

The ref and out Parameters

Did you ever need your method to return more than one value? You may need to do this occasionally, or you may need to use the same variables that you pass as an argument of the method. When you pass a reference type, such as a class instance, you don’t have to worry about getting a value in a separate variable because the type is already being passed as a reference and will maintain the changes when it returns. A problem occurs when you want the value to be returned in the value type. The ref and out parameters help to do this with value types.
The out keyword defines an out type parameter. You Use the out keyword to pass a parameter to a method. This example is passing an integer type variable as an out parameter. You define a function with the out keyword as an argument with the variable type:
myMethod(out int iVal1)
The out parameter can be used to return the values in the same variable passed as a parameter of the method. Any changes made to the parameter will be reflected in the variable. Listing 30 shows an example of the parameter.
  Using the out parameter
using System;
public class myClass
{
      public static void ReturnData(out int iVal1, out int iVal2)
             {
                   iVal1 = 2;
                   iVal2 = 5;
             }
      public static void Main()
      {
            int iV1, iV2; // variable need not be initialized
            ReturnData(out iV1, out iV2);
            Console.WriteLine(iV1);
            Console.WriteLine(iV2);
      }
}
The ref keyword defines a ref type parameter. You pass a parameter to a method with this keyword, as in listing 31. This example passes an integer type variable as a ref parameter. This is a method definition:
myMethod(ref int iVal1)
You can use the ref parameter as a method input parameter and an output parameter. Any changes made to the parameter will be reflected in the variable. See listing 31
  A ref parameter example:-
using System;
public class myClass
{
public static void ReturnData(ref int iVal1, ref int iVal2, ref int iVal3)
{
iVal1 +=2;
iVal2 = iVal2*iVal2;
iVal3 = iVal2 + iVal1;
}
public static void Main()
{
int iV1, iV2, iV3; // variable need not be initialized
iV1 = 3;
iV2 = 10;
iV3 = 1;
ReturnData(ref iV1, ref iV2, ref iV3);
Console.WriteLine(iV1);
Console.WriteLine(iV2);
Console.WriteLine(iV3);
}
}
In this method, ReturnData takes three values as input parameters, operates on the passed data returns the result in the same variable.

Properties:-

Other than methods, another important set of members of a class is variables. A variable is a type that stores some value. The property member of a class provides access to variables. Some examples of Properties are font type, color, and visible properties. Basically, Properties are fields. A field member can be accessed directly, but a property member is always accessed through accessor and modifier methods called get and set, respectively. If you have ever created active X controls in C++ or visual basic, or created JavaBeans in java, you understand.

Note: Visual Basic programmers will note that Let is not available in C#
This is because all types are objects, so only the set access or is necessary.

In Listing 32 you create two properties of myClass:Age and MaleGender. Age is an integer property, and MaleGender is a Boolean type property. As you can see in the example, the get and set keywords are used to get and set property values. You’re reading and writing property values from the Main method. Note that leaving out the set method in a property makes the property read-only.

Listing 32. Class property member example
using System;
class myClass
{
      private bool bGender;
      private int intAge;

      // Gender property.
      public bool MaleGender
      {
            get
            {
                  return bGender;
            }
            set
            {
                  bGender = value;
            }
      }
      // Age property
      public int Age
      {
            get
            {
                  return intAge;
            }
            set
            {
                  intAge = value;
            }
      }
}
class TestmyClass
{
      static void Main()
      {
            myClass cls = new myClass();
            // set properties values
            cls.MaleGender = true;
            cls.Age = 25;
            if (cls.MaleGender)
            {
                  Console.WriteLine("The Gender is Male");
                  Console.WriteLine("Age is" + cls. Age.ToString() );
            }
      }
}
Why use properties if you already have the field available? First of all, properties expose fields in classes being used in components. They also provide a means for doing necessary computation before or after accessing or modifying the private fields they’re representing. For example, if you’re changing the color of a control in the set method, you may also want to execute an invalidate method inside the set to repaint the screen.

1 comment: