Tuesday, December 25, 2018

C# Data Types

C# Data Types:

Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C#, each type of data is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data types.

In C#, data types are categorized based on how they store their value in the memory. 

C# includes following categories of data types:
·       Value type
·       Reference type

Value Type:

Value type variables can be assigned a value directly. They are derived from the class System.ValueType. Value type holds both data and memory on the same location. A Value Type stores its contents in memory allocated on the stack. When you created a Value Type, a single space in memory is allocated to store the value and that variable directly holds a value. If you assign it to another variable, the value is copied directly and both variables work independently. Predefined datatypes, structures, enums are also value types, and work in the same way.

For Example:

Consider integer variable int i = 100;


The system stores 100 in the memory space allocated for the variable 'i'.

In C#, value types are further divided into simple types, enum types, struct types, and nullable value types.
  • Simple Types
    • Signed integral: sbyte, short, int, long
    • Unsigned integral: byte, ushort, uint, ulong
    • Unicode characters: char
    • IEEE floating point: float, double
    • High-precision decimal: decimal
    • Boolean: bool
  • Enum types
    • User-defined types of the form enum E {...}
  • Struct types
    • User-defined types of the form struct S {...}
  • Nullable value types
    • Extensions of all other value types with a null value
Reference Type:

The Reference Data Types will contain a memory address of variable value. It do not contain the actual data stored in a variable, but they contain a reference to the actual data. Reference Type variables are stored in a different area of memory called the heap. Assigning a reference variable to another variable doesn't copy the data. Instead it creates a second copy of the reference, which refers to the same location of the heap as the original value.

For example:


string s = "Hello World!!";


In C# reference types are further divided into class types, interface types, array types, and delegate types.
  • Class types
    • Ultimate base class of all other types: object
  • Interface types
    • User-defined types of the form interface I {...}
  • Array types
    • Single- and multi-dimensional, for example, int[] and int[,]
  • Delegate types
    • User-defined types of the form delegate int D(...)




Prof. Shardul P. Patil

profshardulp.patil@gmail.com

Type Conversion


Type Conversion:

C# is a strongly typed language; therefore every variable and object must have a declare its type. C# allows us to create variables of many types but, it does not allow us to assign the value of one type of variable into another type of variables. For example, the string cannot be implicitly converted to int. Therefore, after you declare i as an int, you cannot assign the string to it. See the code below

String str = “Hello”;

int i = str;  // throws error Cannot implicitly convert type string to int

Sometime it needs to copy a value into a variable of another type. For example, you might have an integer variable that you need to pass to a method whose parameter is typed as double. These kinds of operations are called type conversions.

Type casting or type conversion refers to change of type of variable from one type to another type. Type conversion is possible if both the data types are compatible to each other.

There are two types of conversion in C#:

           1.     Implicit Conversion
           2.     Explicit Conversion

Implicit Conversion:

Implicit conversion is being done automatically by the compiler. An implicit conversion can be made when the value to be stored can fit into the variable without being truncated or rounded off. For example, are conversions from smaller to larger integral types and conversions from derived class to base class. It doesn't require any casting operator or special syntax. The conversion is type safe and no data will be lost.

For Example:

int smallnum = 4500;

long bigNum = smallnum;                                     // Implicit conversion

In the above statements, the conversion of data from int to long is done implicitly.

Following table shows C# supported implicit conversion:



Explicit Conversion:

Explicit conversion is being done by using a cast operator. It includes conversion of larger data type to smaller data type and conversion of base class to derived classes. In this conversion information might be lost or conversion might not be succeed for some reasons. This is an un-safe type conversion.

For Example:

double y = 123;

int x = (int)y;

            In the above statement, we have to specify the type operator (int) when converting from double to int else the compiler will throw an error.




Prof. Shardul P. Patil
profshardulp.patil@gmail.com





Boxing & Unboxing

Boxing & Unboxing:

                  Consider a situation where we are passing value to a method but we don’t know what type of value we are going to pass. In this kind of situation we have to use “object” data type. The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. Object is reference type which can store any kind of value including value type and reference type. Before assigning values, it needs type conversion. Object type can be used to hold the data. Before using it in the expression it needs conversion to its original type.  

For Example:
class Program
    {
        static void Main(string[] args)
        {
            int a = 34;
            double b = 345.56;
            String str = "Hello";
            Boolean flag = true;
            func(a);
            func(b);
            func(str);
            func(flag);
        }

        static void func(object ob)
        {
            Console.WriteLine(ob);       
        }
    }
            In above code the function func has parameter of object type that means we can pass any kind of parameter to the function.  When a variable of a value type is converted to object, it is said to be boxed. When a variable of type object is converted to a value type, it is said to be unboxed. The Object does not allow you to perform any operation such as mathematical operation without doing "boxing and unboxing".

Boxing:

Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. In boxing any type value or reference can be assigned to an object without an explicit conversion. When the CLR boxes a value type, it wraps the value inside a System.Object. In boxing process, a value type is being allocated on the heap rather than the stack.  

For Example:

int stackVar = 12;
object boxedVar = stackVar;                       // Boxing

Unboxing:

Unboxing is simply the opposite of boxing. When value is boxed into an object type, it cannot be used in operations. An unboxing conversion permits an explicit conversion from type object to any value-type. It is explicit conversion of same reference type (which is being created by boxing process); back to a value type. In unboxing process, boxed value type is unboxed from the heap and assigned to a value type which is being allocated on the stack.

For Example:

int stackVar = 12;
object boxedVar = stackVar;                       // Boxing
stackVar = (int)boxedVar;                          // Unboxing 

Sometimes boxing is necessary, but you should avoided it if possible, since it will slow down the performance and increase memory requirements. For example, when a value type is boxed, a new reference type is created and the value is copied from the value type to the newly created reference type. This process takes time and required extra memory (around twice the memory of the original value type). Attempting to unbox a null causes a NullReferenceException.

Difference between Boxing & Unboxing:




Prof. Shardul P. Patil

profshardulp.patil@gmail.com

Passing parameters to a method

Passing parameters to a method:

There are three ways that parameters can be passed to a method:
  • Pass by Value
  • Pass by Reference
  • Out Parameter

Pass by Value:

In .NET Framework, all parameters are by default passed by value. When a variable is passed as the parameter to any method, it is passed as a value. This method copies the actual value of an argument into the formal parameter of the function. If inside the method these values are changed or modified, the change is not reflected in the actual passed variable. Changes made inside the function have no effect on the actual parameter.

Passing variable by value is useful in cases where the actual value of the variable should not be modified by the method and the change is only limited to the called method whereas the value of the variables in the calling method remain unchanged.

For Example:

class PassingValByVal
{
    static void SquareIt(int x)
    // The parameter x is passed by value.
    // Changes to x will not affect the original value of x.
    {
        x *= x;
        System.Console.WriteLine("The value inside the method: {0}", x);
    }
    static void Main()
    {
        int n = 5;
        System.Console.WriteLine("The value before calling the method: {0}", n);

        SquareIt(n);  // Passing the variable by value.
        System.Console.WriteLine("The value after calling the method: {0}", n);
    }
}

Output:

    The value before calling the method: 5
    The value inside the method: 25
    The value after calling the method: 5

Pass by Reference:

            C# provides a ref keyword to pass argument as reference-type. It passes reference of arguments to the function rather than copy of original value. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The method operates on the references of the variables passed in the parameters rather than operating on their values. The changes in passed values are permanent and modify the original variable value.

            Normally, all the objects are passed by reference as parameter to the method. On the 
other hand most of the primitive data types such as integer, double, Boolean etc. are passed by value.

For Example:

class PassingValByRef
{
    static void SquareIt(ref int x)
    // The parameter x is passed by reference.
    // Changes to x will affect the original value of x.
    {
        x *= x;
        System.Console.WriteLine("The value inside the method: {0}", x);
    }
    static void Main()
    {
        int n = 5;
        System.Console.WriteLine("The value before calling the method: {0}", n);
        SquareIt(ref n);  // Passing the variable by reference.
        System.Console.WriteLine("The value after calling the method: {0}", n);
    }
}

Output:
    The value before calling the method: 5
    The value inside the method: 25
    The value after calling the method: 25                                    

           In this example, it is not the value of n that is passed; rather, a reference to n is passed. The parameter x is not an int; it is a reference to an int, in this case, a reference to n. Therefore, when x is squared inside the method, what actually is squared is what x refers to, n.

Out Parameter:

          A return statement can be used for returning only one value from a function. However, using output parameters, you can return multiple values from a function. Output parameters are similar to reference parameters, except that ref requires that the variable be initialized before it is passed. Variables passed as out arguments do not have to be initialized before being passed in a method call. However, the called method is required to assign a value before the method returns.

For Example:

using System; 
namespace OutParameter 
    class Program 
    { 
        // User defined function 
        public void Show(out int a, out int b) // Out parameter 
        { 
            int square = 5; 
            a = square; 
            b = square; 
            // Manipulating value 
            a *= a;  
            b *= b; 
        } 
        // Main function, execution entry point of the program 
        static void Main(string[] args) 
        { 
            int val1 = 50, val2 = 100; 
            Program program = new Program(); // Creating Object 
            Console.WriteLine("Value before passing \n val1 = " + val1+" \n val2 = "+val2); 
            program.Show(out val1, out val2); // Passing out argument 
            Console.WriteLine("Value after passing \n val1 = " + val1 + " \n val2 = " + val2); 
        } 
    } 

Output:

Value before passing
 val1 = 50
 val2 = 100
Value after passing
 val1 = 25
 val2 = 25

Difference between ref & out parameter:




Prof. Shardul P. Patil
profshardulp.patil@gmail.com

Assemblies in .Net


Assemblies in .Net:

Microsoft .Net Assembly is a logical unit of code, that contains code which the Common Language Runtime (CLR) executes. It is the smallest unit of deployment of a .net application and it can be a .dll or an exe . Assembly is really a collection of types and resource information that are built to work together and form a logical unit of functionality. It include both executable application files that you can run directly from Windows without the need for any other programs (.exe files), and libraries (.dll files) for use by other applications.

Assemblies are the building blocks of .NET Framework applications. During the compile time Metadata is created with Microsoft Intermediate Language (MSIL) and stored in a file called Assembly Manifest . Both Metadata and Microsoft Intermediate Language (MSIL) together wrapped in a Portable Executable (PE) file. Assembly Manifest contains information about itself. This information is called Assembly Manifest, it contains information about the members, types, references and all the other data that the runtime needs for execution.

Every Assembly you create contains one or more program files and a Manifest. There are two type program files: Process Assemblies (EXE) and Library Assemblies (DLL). Each Assembly can have only one entry point.

An assembly performs following functions:
-It contains IL code that gets executed by common language runtime.
-It forms a security boundary.
-An assembly is the unit at which permissions are requested and granted.
-It ensures type safety by establishing name scope for types at the runtime.
-It contains version information.
-It allows side-by-side execution of multiple versions of same assembly.

Types of Assembly:

1.     Private Assembly:
 A private Assembly is used only by a single application, and usually it is stored in that application's install directory.

2.     Shared Assembly:
A shared Assembly is one that can be referenced by more than one application. If multiple applications need to access an Assembly, we should add the Assembly to the Global Assembly Cache (GAC).

3.     Satellite Assembly:
A Satellite Assembly contains only static objects like images and other non-executable files required by the application.



Prof. Shardul P. Patil
profshardulp.patil@gmail.com

Difference between DLL & EXE


Difference between DLL & EXE:

EXE File:
The term EXE is a shortened version of the word executable as it identifies the file as a program. An EXE file contains the entry point or the part in the code where the operating system is supposed to begin the execution of the application. The exe files are in-process components which were capable of running on their own. Also they can provide the support for others to execute. An exe file is generated after the compilations of C# projects. It stores Metadata & MSIL code.

DLL Files:

DLL stands for Dynamic Link Library, which commonly contains functions and procedures that can be used by other programs. The dll files are out-process components which were not capable of running on their own. DLL files do not have entry point and thus cannot be executed on their own. They can only execute with the help of other applications. The most major advantage of DLL files is in its reusability. A DLL file can be used in other applications.


DLL V/S EXE:

Dynamic-Link Library (DLL):

1.     Its full meaning is Dynamic Link Library
2.     It cannot execute without the help of EXE file. That means dll files are not independent
3.     It has not main function.
4.     A dll is a library that an exe (or another dll) may call
5.     In one application many dll files may exists
6.     A dll can be shared with others applications. That means dll is reusable
7.     dll is an In-Process Component
8.     A dll can never run in its own memory address space

Executable File (EXE):

1.     It’s full meaning Executable File.
2.     It can execute with the help of OS. That means exe files are independent
3.     It has main function
4.     An exe is a program
5.     In one application only one exe files exists
6.     An exe cannot be shared with others applications. That means exe is not reusable
7.     EXE is an Out-Process Component
8.     An exe always runs in its own memory address space


Prof. Shardul P. Patil
profshardulp.patil@gmail.com