Showing posts with label Shivaji University. Show all posts
Showing posts with label Shivaji University. Show all posts

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

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

Monday, October 22, 2018

Localization and Globalization in ASP.Net

Most websites on the internet are designed and developed to support a single language and culture, but making a website or web application to support different languages and cultures is not difficult and easy to implement in ASP.Net.

Globalization is the process of designing and developing applications that function for multiple cultures. Localization is the process of customizing your application for a given culture and locale. 

ASP.Net localizes an application through the use of resource files. Resource files are xml files with .resx extension. Resources can either be a global resource, in which it is accessible throughout the site and placed in App_GlobalResources folder in a website or a local resource which is specific to a page only and is placed in App_LocalResources folder. 
        
        In Visual Studio right click the website in solution explorer and select Add ASP.Net Folder then select App_GlobalResources. After that, right click the App_GlobalResources and select Add New Item in the list of items displayed in the dialog box then select Resource File and give it any name. The next thing is to create our language specific resource files. Each language requires different resource file. A resource file takes a key name & value pair, so all the resource files will contain the same key but the different values as the language translation.

We need to override the page's InitializeCulture() method and set the page UICulture & Culture property, this property determines which global or local resource to be loaded for the page. ASP.Net checks the languageid and cultureid combination on the browser to determine the resource file to be used in rendering contents to that browser. to see the detailed list of languages and cultures identification click here. CLICK HERE

         To watch the demonstration click here: WATCH VIDEO

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

Tuesday, October 9, 2018

Partial Class

Partial Class:

            There are many situations when you might need to split a class definition, such as when working on a large scale projects, multiple developers and programmers might need to work on the same class at the same time. In this case we can use a feature called Partial Class.

            C# provides the ability to have a single class implementation in multiple .cs files using the partial modifier keyword. Each source files contains a section of the definition of class. When partial code is compiled on CLR, multiple classes or interfaces or struct with partial keyword will be compiled into single unit or it is considered as single class, interface and struct. All classes should be declared under one namespace scope only.
                 
                Suppose you have a "Student" class. That definition is divided into the two source files "Student1.cs" and "Student 2.cs". Then these two files have a class that is a partial class. You compile the source code then create a single class.


Advantages of Partial Class:
  • Separate UI design code and business logic code for ease of working and understanding.
  • Multiple developers can also work simultaneously like one creating logic and other working on designer part.
  • It is also helpful to embed our custom logic code under framework auto generated code.
  • Larger classes can be split into smaller classes for easy to understand and maintain.
  • Interfaces can also split into multiple code to share it with multiple developers which further help in fast application development.

There are some points that you should be when you are developing a partial class in your application:
  • You need to use partial keyword in each part of partial class.
  • The name of each part of partial class should be the same but source file name for each part of partial class can be different.
  • All parts of a partial class should be in the same namespace.
  • Each part of a partial class should be in the same assembly or DLL, in other words you can't create a partial class in source files of a different class library project.
  • Each part of a partial class has the same accessibility.
  • If you inherit a class or interface on a partial class then it is inherited on all parts of a partial class.
  • If a part of a partial class is sealed then the entire class will be sealed.
  • If a part of partial class is abstract then the entire class will be an abstract class.

Example:

PartialClassFile1.cs:

public partial class MyPartialClass
{
    public MyPartialClass()
    {
    }

    public void Method1(int val)
    {
        Console.WriteLine(val);
    }
}

PartialClassFile2.cs:

public partial class MyPartialClass
{
    public void Method2(int val)
    {
        Console.WriteLine(val);
    }
}

MyPartialClass in PartialClassFile1.cs defines the constructor and one public method, Method1, whereas PartialClassFile2 has only one public method, Method2.  



Prof. Shardul P. Patil

profshardulp.patil@gmail.com

Monday, September 17, 2018

Stack & Heap Memory

Stack & Heap Memory:

           When we declare a variable in a .NET application, it allocates some space of memory in the RAM. This memory has three things: the name of the variable, the data type of the variable, and the value of the variable.
That was a simple explanation of what happens in the memory, but depending on the data type, your variable is allocated that type of memory. The Common Language Runtime (CLR) automatically handles Memory Management with the help of its components. The Garbage Collector plays an important role in Memory Management. Objects are automatically freed when they are no longer needed by the application by Garbage Collector.

There are two types of memory allocation: stack memory and heap memory.

Stack Memory:

            The stack is used for static memory allocation. It is an array of memory. Think of the stack as a series of boxes stacked one on top of the next. It is a Last-in, First-out (LIFO) data structure. Data can be added to and deleted only from the top of the stack. Placing a data item at the top of the stack is called pushing the item onto the stack. Deleting an item from the top of the stack is called popping the item from the stack. Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is done when the program is compiled. The stack is responsible for keeping track of the running memory needed in your application. The stack contains value type data. Mostly stack contains local variables which visible only to owner thread & gets cleared once they lost the scope.

Heap Memory:

The Heap is used for dynamic memory allocation. Unlike the stack, data can be stored and removed from the heap in any order. Your program can store items in the heap, it cannot explicitly delete them.  Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory. The heap contains reference types. The heap memory is used by all part of application thus objects created on heap visible to all threads. Allocation & de allocation of heap memory is done by Garbage Collector.

For Example:

public void Method1()
{
    // Line 1
    int i=6;

    // Line 2
    int y=8;

    //Line 3
    class1 cls1 = new class1();
}

It’s a three line code, let’s understand line by line:

Line 1:  When line 1 is executed, the compiler allocates a small amount of memory in the stack. The stack is responsible for keeping track of the running memory needed in your application.

Line 2: At line 2 memory allocates on top of the first memory allocation. You can think about stack as a series of compartments or boxes put on top of each other. Memory is allocated and de-allocated at only one end of the memory, i.e., top of the stack.

Line 3: In line 3, we have created an object. When this line is executed it creates a pointer on the stack and the actual object is stored in a different type of memory location called ‘Heap’. ‘Heap’ does not track running memory, it’s just a pile of objects which can be reached at any moment of time. Heap is used for dynamic memory allocation.

Difference between Stack and Heap Memory: