Thursday, October 1, 2015

Difference Between Structure and class in c#

This blog defines the difference between  Structure and class
Structure
  1. Structure is a value type that is why its object is created on the stack memory.
     
  2. Structure does not support the inheritance.
     
  3. Structure can only have the parametrized constructor. it means a structure can not have the non-parametrized constructor,default constructor and destructor also.
     
  4. The member variable of structure can not be initialized directly.
     
  5. Structure object can be created without using the new keyword.(optional)

    Demo obj;
Class
  1. Class is a reference type and its object is created on the heap memory.
     
  2. Class can inherit the another class.
     
  3. Class can have the all types of constructor and destructor.
     
  4. The member variable of class can be initialized directly.
     
  5. class object can not be created without using the new keyword, it means we have to use it.

    Demo obj=new Demo();
A short summary of each:
Classes Only:
  • Can support inheritance
  • Are reference (pointer) types
  • The reference can be null
  • Have memory overhead per new instance
Structs Only:
  • Cannot support inheritance
  • Are value types
  • Are passed by value (like integers)
  • Cannot have a null reference (unless Nullable is used)
  • Do not have a memory overhead per new instance - unless 'boxed'
Both Classes and Structs:
  • Are compound data types typically used to contain a few variables that have some logical relationship
  • Can contain methods and events
  • Can support interfaces
When to Use Structure and Class?

In general, classes can be used when you have more complex behavior or data. And if you think that these behaviour or data to be modified after creating an instance of class, then classes are absolute methods.
Structures can be used for small data structures. If developer feels that data members of structure cannot to be modified after creating structure, then having structure will suit.

  1. Classes are Reference types and Structures are Values types.When I say Classes are reference types, basically they will contain the address of an instance variables. For example:
    Class MyClass
    {
    Public Int DataMember;  //By default, accessibility of class data members 
       //will be private. So I am making it as Public which 
       //can be accessed out side of the class.
    }
    In main method, I can create an instance of this class using new operator that allocates memory for this class and stores the base address of that into MyClass type variable.
    Static Public void Main (string [] arg)
    {
     MyClass _myClassObject1 =new MyClass ();
     _ myClassObject1.DataMember=10;
     MyClass _myClassObject2 =_myClassObject1;
     _ myClassObject2.DataMember=20;
    }
    In the above program, “MyClass _myClassObject2 =_myClassObject1” instruction indicates that both variables of type MyClass myClassObject1 and myClassObject2 will point to the same memory location. It basically assigns the same memory location into another variable of same type.
    So if any changes that we make in any one of the objects type MyClass will have an effect on another since both are pointing to the same memory location.
    _ myClassObject1.DataMember=10” at this line both the object’s data members will contain the value of 10_ myClassObject2.DataMember=20 at this line both the object’s data member will contains the value of 20. Eventually, we are accessing datamembers of an object through pointers.
    Unlike classes, structures are value types. For example:
    Structure MyStructure
    {
    Public Int DataMember;  //By default, accessibility of Structure data 
       //members will be private. So I am making it as 
       //Public which can be accessed out side of the structure.
    }
    
    Static Public void Main (string [] arg)
     {
     MyStructure _myStructObject1 =new MyStructure ();
     _ myStructObject1.DataMember=10;
     MyStructure _ myStructObject2 =_ myStructObject1;
     _ myStructObject2.DataMember=20;
    }
    In the above program, instantiating the object of MyStructure type using new operator and storing address into _myStructObject variable of type MyStructure and assigning value 10 to data member of the structure using “_ myStructObject1.DataMember=10”. In the next line, I am declaring anothervariable_myStructObject2 of type MyStructure and assigning _myStructObject1 into that. Here .NET C# compiler creates another copy of _myStructureObject1 object and assigns that memory location into MyStructure variable _myStructObject2.
    So whatever change we make on _myStructObject1 will never have an effect on another variable_myStructObject2 of type MyStructrue. So that’s why we are saying Structures are value types.
    So the immediate Base class for class is Object and immediate Base class for Structure is ValueTypewhich inherits from Object.
  2. Classes will support an Inheritance whereas Structures won’t.



Some important questions that people ask in forums is "what's the difference between a structure and a class?" and "what could be the value of a structure since we already have classes that can do the job perfectly?". Those questions could particularly be posed by a Java programmer that wants to migrate from Java to .Net. For this reason I will list in this article some of those differences to make the issue clear.
  1. Structures are value types and the classes are reference types. Before proceeding to the next point, let explain the difference between the two types. Imagine this is the memory within the machine:


    structure

    Figure 1

    The value types are stored in the stack but the reference types are not. In fact, what could be really stored in the stack for the reference types is a pointer that targets an address at the heap level.

    Then the type of structure objects are stored in the stack exactly like any value type, say an integer, a double or a float. Meanwhile, memory locations could be reserved for reference types in the heap. Defining the heap and stack and the difference between them is beyond the scope of this article but nevertheless I propose this excellent Matthew article to understand the memory mechanisms.

    http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx?ArticleID=9adb0e3c-b3f6-40b5-98b5-413b6d348b91
     
  2. Classes are usually used for large amounts of data, whereas structs are usually used for smaller amounts of data.
  3. Classes can be inherited whereas structures not.
  4. A structure couldn't be null like a class.
  5. A structure couldn't have a destructor such as a class.
  6. A structure can't be abstract, a class can.
  7. You cannot override any methods within a structure except the following belonging to the type object:
     
    • Equals()
    • GetHashCode()
    • GetType()
    • ToString()

    And the other polymorphism technique used for structures is implementing interfaces.
     
  8. Declared events within a class are automatically locked and then they are thread safe, in contrast to the structure type where events can't be locked.
  9. A structure must always have the default parameter less constructor defined as public but a class might have one, so you can't define a private parameter-less constructor as in the following:

    struct Me    {
            private Me()// compile-time error        {
            }
        }
         
    class
     Me         {
                private Me()// runs Ok{
             }

     
  10. A static constructor is triggered in the case of a class but not in the case of a structure as in the following:

    struct myStructure    {
            static myStructure() 
            {
                Console.WriteLine("This is me a structure");
            }
        }
        class myClass
        {
            static myClass()
            {
                Console.WriteLine("This is me a class");
            }
        }
        class Program    {
            static void Main(string[] args)
            {
               myStructure s =new myStructure();//Nothing happen           myClass c =new myClass();//Will out put This is me a class           Console.Read();
            }
        }
     
  11. The strucutre can't conatain a volatile field whereas the class can
  12. You can't use sizeof with classes but you can with structures
  13. Fields are automatically initialized with classes to 0/false/null wheatheras strucutres are not
  14. Fields can't be directley instantiated within structures but classes allow such operations as in the following:

    struct myStructure    {
            publicstring x = 2;//Not allowed     }
        class myClass    {
            publicstring x = 2;//Allowed    }
     
  15. Structures and classes don't adopt the same aproach for the System.Object.Equals() method.

    Assume the following strucutre and class:

    struct StructurePerson    {
            publicstring FirstName;
            publicstring LastName;
        }
        class ClassPerson    {
            publicstring FirstName;
            publicstring LastName;
        }
    Now, try this code:

    class Program    {
            static void Main(string[] args)
            {
                StructurePerson strX =new StructurePerson();
                strX.LastName = "Bejaoui";
                strX.FirstName = "Bechir";
                StructurePerson strY =new StructurePerson();
                strY.LastName = "Bejaoui";
                strY.FirstName = "Bechir";
                if (strX.Equals(strY))
                {
                    Console.WriteLine("strX = strY");
                }
                else            {
                    Console.WriteLine("strX != strY");
                }//This code displays strX = strY
                ClassPerson clsX =new ClassPerson();
                clsX.LastName = "Bejaoui";
                clsX.FirstName = "Bechir";
                ClassPerson clsY =new ClassPerson();
                clsY.LastName = "Bejaoui";
                clsY.FirstName = "Bechir";
                if (clsX.Equals(clsY))
                {
                    Console.WriteLine("clsX = clsY");
                }
                else            {
                    Console.WriteLine("clsX != clsY");
                }//This code displays clsX != clsY            Console.Read();
            }
        }

    In the first strucutre the two objects are value types, they are compared depending on their values like int I = 5 and int J = 5 so I=J because they have the same value. In the contrast, in the class case of two different and distinct references, to make clsX = clsY you should use the following code:

                ClassPerson clsX =new ClassPerson();
                clsX.LastName = "Bejaoui";
                clsX.FirstName = "Bechir";
                ClassPerson clsY = clsX;
                if (clsX.Equals(clsY))
                {
                    Console.WriteLine("clsX = clsY");
                }
                else            {
                    Console.WriteLine("clsX != clsY");
                }//This code displays clsX = clsY


That's it.

Different Types of SQL Server Functions

Types of Function

  1. System Defined Function

    These functions are defined by Sql Server for different purpose. We have two types of system defined function in Sql Server
    1. Scalar Function

      Scalar functions operates on a single value and returns a single value. Below is the list of some useful Sql Server Scalar functions.
      System Scalar Function
      Scalar Function
      Description
      abs(-10.67)
      This returns absolute number of the given number means 10.67.
      rand(10)
      This will generate random number of 10 characters.
      round(17.56719,3)
      This will round off the given number to 3 places of decimal means 17.567
      upper('dotnet')
      This will returns upper case of given string means 'DOTNET'
      lower('DOTNET')
      This will returns lower case of given string means 'dotnet'
      ltrim(' dotnet')
      This will remove the spaces from left hand side of 'dotnet' string.
      convert(int, 15.56)
      This will convert the given float value to integer means 15.
    2. Aggregate Function

      Aggregate functions operates on a collection of values and returns a single value. Below is the list of some useful Sql Server Aggregate functions.
      System Aggregate Function
      Aggregate Function
      Description
      max()
      This returns maximum value from a collection of values.
      min()
      This returns minimum value from a collection of values.
      avg()
      This returns average of all values in a collection.
      count()
      This returns no of counts from a collection of values.
  2. User Defined Function

    These functions are created by user in system database or in user defined database. We three types of user defined functions.
    1. Scalar Function

      User defined scalar function also returns single value as a result of actions perform by function. We return any datatype value from function.
      1. --Create a table
      2. CREATE TABLE Employee
      3. (
      4. EmpID int PRIMARY KEY,
      5. FirstName varchar(50) NULL,
      6. LastName varchar(50) NULL,
      7. Salary int NULL,
      8. Address varchar(100) NULL,
      9. )
      10. --Insert Data
      11. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(1,'Mohan','Chauahn',22000,'Delhi');
      12. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(2,'Asif','Khan',15000,'Delhi');
      13. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(3,'Bhuvnesh','Shakya',19000,'Noida');
      14. Insert into Employee(EmpID,FirstName,LastName,Salary,Address) Values(4,'Deepak','Kumar',19000,'Noida');
      15. --See created table
      16. Select * from Employee
      1. --Create function to get emp full name
      2. Create function fnGetEmpFullName
      3. (
      4. @FirstName varchar(50),
      5. @LastName varchar(50)
      6. )
      7. returns varchar(101)
      8. As
      9. Begin return (Select @FirstName + ' '+ @LastName);
      10. end
      1. --Calling the above created function
      2. Select dbo.fnGetEmpFullName(FirstName,LastName) as Name, Salary from Employee
    2. Inline Table-Valued Function

      User defined inline table-valued function returns a table variable as a result of actions perform by function. The value of table variable should be derived from a single SELECT statement.
      1. --Create function to get employees
      2. Create function fnGetEmployee()
      3. returns Table
      4. As
      5. return (Select * from Employee)
      1. --Now call the above created function
      2. Select * from fnGetEmployee()
    3. Multi-Statement Table-Valued Function

      User defined multi-statement table-valued function returns a table variable as a result of actions perform by function. In this a table variable must be explicitly declared and defined whose value can be derived from a multiple sql statements.
      1. --Create function for EmpID,FirstName and Salary of Employee
      2. Create function fnGetMulEmployee()
      3. returns @Emp Table
      4. (
      5. EmpID int,
      6. FirstName varchar(50),
      7. Salary int
      8. )
      9. As
      10. begin
      11. Insert into @Emp Select e.EmpID,e.FirstName,e.Salary from Employee e;
      12. --Now update salary of first employee
      13. update @Emp set Salary=25000 where EmpID=1;
      14. --It will update only in @Emp table not in Original Employee table
      15. return
      16. end
      1. --Now call the above created function
      2. Select * from fnGetMulEmployee()
      1. --Now see the original table. This is not affected by above function update command
      2. Select * from Employee

Note

  1. Unlike Stored Procedure, Function returns only single value.
  2. Unlike Stored Procedure, Function accepts only input parameters.
  3. Unlike Stored Procedure, Function is not used to Insert, Update, Delete data in database table(s).
  4. Like Stored Procedure, Function can be nested up to 32 level.
  5. User Defined Function can have upto 1023 input parameters while a Stored Procedure can have upto 2100 input parameters.
  6. User Defined Function can't returns XML Data Type.
  7. User Defined Function doesn't support Exception handling.
  8. User Defined Function can call only Extended Stored Procedure.
  9. User Defined Function doesn't support set options like set ROWCOUNT etc.