Showing posts with label Computer Science. Show all posts
Showing posts with label Computer Science. 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

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

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:


Friday, September 14, 2018

Command Line Argument

Command Line Argument:

It is possible to pass some values from the command line to your C# programs when they are executed. The arguments can be used as input for the program. A parameter supplied to the program through the command line is when it invoked is called Command Line Argument. We can pass any number of arguments from the command prompt. The Main() method is entry point method for a program. Command line arguments are passed to the Main() method.
In C# Main() method can be declared with the String[] args parameter. The args parameter accepts command-line arguments which can be used to provide the program some values at the moment of execution. The args argument is array of type String. The program accept arguments in the order of args[0], args[1] and so on. The arguments are separated by white space, i.e. either space or tab.

For Example:
using System;
class Sample
{
            static void Main(string[] args)
            {
                        int SUM         = 0;
                        int X   = 0;
                        int Y   = 0;

                        X = Convert.ToInt32(args[0]);        // Command Line Argument 1
                        Y = Convert.ToInt32(args[1]);        // Command Line Argument 2

                        SUM = X + Y;
                        Console.WriteLine("Sum is: "+SUM);                 
            }
}

To Compile:
csc sample.cs

To Execute: 









                    Here, we are passing 10 and 20 as command line arguments which can be accessed through args. Where 10 will be assigned into args[0] and 20 will be assigned into args[1].

Tuesday, August 21, 2018

JIT Compiler & Its Types

JIT Compiler

In the .NET Framework, all the Microsoft .NET languages use a Common Language Runtime. The language compiler will convert code into MSIL. Before the MSIL can be executed, it must be converted to native code. Native code is CPU specific code which runs on the same machine. JIT compiler converts the MSIL code to CPU native code as it is needed during code execution. It is called just-in-time since it converts the MSIL code to CPU native code; when it is required within code execution otherwise it will not do nothing with that MSIL code.

Role of the JIT compiler:-

The JIT compiler loads MSIL on target machines for execution. The MSIL is stored in .NET assemblies after the developer has compiled the code written in any .NET-compliant programming language, such as Visual Basic and C#. JIT compiler translates the MSIL code of an assembly and uses the CPU architecture of the target machine to execute a .NET application. It also stores the resulting native code so that it is accessible for subsequent calls. If a code executing on a target machine calls a non-native method, the JIT compiler converts the MSIL of that method into native code. JIT compiler also enforces type-safety in runtime environment of .NET Framework. It checks for the values that are passed to parameters of any method.

Types of JIT Compiler:


Pre JIT:

PRE JIT Compiler compiles complete source code into native code in a single compilation cycle. It will convert the compiled .NET code from the platform-independent intermediate state to a platform specific stage. This is done at the time of deployment of the application. The advantage of PRE JIT Compiler is that you don't have the initial compilation delay that the compiler can introduce when an assembly or type is loaded for the first time in code.


Econo JIT: 

Econo JIT Compiler compiles only those methods that are called at runtime. These compiled methods are removed when they are not required. The idea of Econo JIT is to spend less time compiling so that startup latency (the delay before a transfer of data begins following an instruction for its transfer) is lower for interactive applications.



Normal JIT: 

This complies only those methods that are called at runtime. These methods are compiled only first time when they are called, and then they are stored in memory cache. This memory cache is commonly called as JITTED. When the same methods are called again, the complied code from cache is used for execution.




Thursday, August 16, 2018

Metadata


Metadata
Metadata in .Net is binary information which describes the characteristics of a resource . This information include Description of the Assembly , Data Types and members with their declarations and implementations, references to other types and members , Security permissions etc. A module's metadata contains everything that needed to interact with another module. In .NET, metadata includes type definitions, version information, external assembly references, and other standardized information. In order for two systems, components, or objects to interoperate with one another, at least one must know something about the other.
During the compile time Metadata created with Microsoft Intermediate Language (MSIL) and stored in a file called a Manifest . Both Metadata and Microsoft Intermediate Language (MSIL) together wrapped in a Portable Executable (PE) file. During the runtime of a program Just In Time (JIT) compiler of the Common Language Runtime (CLR) uses the Metadata and converts Microsoft Intermediate Language (MSIL) into native code. When code is executed, the runtime loads metadata into memory and references it to discover information about your code's classes, members, inheritance, and so on. Moreover Metadata eliminating the need for Interface Definition Language (IDL) files, header files, or any external method of component reference.
Metadata stores the following information:
  • Description of the assembly
    • Identity (name, version, culture, public key).
    • The types that are exported.
    • Other assemblies that this assembly depends on.
    • Security permissions needed to run.
  • Description of types
    • Name, visibility, base class, and interfaces implemented.
    • Members (methods, fields, properties, events, nested types).
  • Attributes
    • Additional descriptive elements that modify types and members.

Monday, August 13, 2018

Common Language Specification &


Common Language Specification
One of the obvious themes of .NET is unification and interoperability between various programming languages. In order to achieve this; certain rules must be laid and all the languages must follow these rules. CLS is the collection of the rules and constraints that every language (that seeks to achieve .NET compatibility) must follow.
The Common Language Specification is a set of basic language features (constructs and constraints) that serves as a guide for library writers and compiler writers. It allows libraries to be fully usable from any language supporting the CLS, and for those languages to integrate with each other. The Common Language Specification is a subset of the common type system. The CLS is actually a set of restrictions on the CTS. The CLS defines not only the types allowed in external calls, but the rules for using them, depending on the goal of the user.
The Common Language Specification describes a common level of language functionality. The CLS is a set of rules that a language compiler must follow to create .NET applications that run in the CLR. Anyone who wants to write a .NET compliant compiler needs simply to follow these rules and that's it.
Base Class Library
The .NET Framework base class library contains the base classes that provide many of the services and objects you need when writing your applications. The class library is organized into namespaces. The .NET Framework Class Library (FCL) is a set of managed classes that provide access to system services. File input/output, sockets, database access, remoting, and XML are just some of the services available in the FCL. Importantly, all the .NET languages rely on the same managed classes for the same services. This is one of the reasons that, once you have learned any .NET language, you have learned 40 percent of every other managed language. The same classes, methods, parameters, and types are used for system services regardless of the language. This is one of the most important contributions of FCL.


Sunday, August 12, 2018

Managed Code V/S Unmanaged Code

Managed Code & Unmanaged Code
Managed Code:
Managed code is the code that is written to target the services of the managed runtime execution environment such as Common Language Runtime in .Net Technology. This code is directly executed by CLR with help of managed code execution. Any language that is written in .NET Framework is managed code.
In simple terms the code which is executed by CLR (Common Language Runtime) is called Managed Code, any application which is developed in .Net framework is going to work under CLR, the CLR internally uses the Garbage Collector to clear the unused memory and also used the other functionalities like CTS, CAS etc. Managed code uses CLR which in turns looks after your applications by managing memory, handling security, allowing cross - language debugging, and so on.
Unmanaged Code:
Unmanaged code compiles straight to machine code and directly executed by the Operating System. The generated code runs natively on the host processor and the processor directly executes the code generated by the compiler. It is always compiled to target a specific architecture and will only run on the intended platform. All code compiled by traditional C/C++ compilers are Unmanaged Code.
         The managed code is comparatively easier to learn, write and manage. It offer less code writing efforts to the developer. The legacy of library concept is still maintained by the managed category. While writing an unmanaged code, the programmer works closer to the system hardware, thus faces security and memory management issues too. Most of the modern languages under the managed class have been written (directly or indirectly) in the unmanaged C language code. Unlike the newer, the unmanaged code does not need any supporting environment to execute. It’s ready to run just after the source code compilation.

Difference between Managed & Unmanaged Code:


Tuesday, August 7, 2018

Common Type System

Common Type System ( CTS )


The language interoperability, and .NET Class Framework, are not possible without all the language sharing the same data types. What this means is that an "int" should mean the same in VB, VC++, C# and all other .NET compliant languages. The common type system defines how types are declared, used, and managed in the common language runtime, and is also an important part of the runtime's support for cross-language integration. The Common Type System (CTS) standardizes the data types of all programming languages using .NET under the umbrella of .NET to a common data type for easy and smooth communication among these .NET languages.
          For example, when we declare an int type data type in C# and VB.Net then they are converted to int32. In other words, now both will have a common data type that provides flexible communication between these two languages.



The common type system performs the following functions:
  • Establishes a framework that helps enable cross-language integration, type safety, and high-performance code execution.
  • Provides an object-oriented model that supports the complete implementation of many programming languages.
  • Defines rules that languages must follow, which helps ensure that objects written in different languages can interact with each other.
  • Provides a library that contains the primitive data types (such as Boolean, Byte, Char, Int32, and UInt64) used in application development.
-S
     - Prof. Shardul P. Patil

Monday, August 6, 2018

Common Language Runtime

Common Language Runtime


The CLR stands for Common Language Runtime is an Execution Environment. It works as a layer between Operating Systems and the applications written in .Net languages that conforms to the Common Language Specification (CLS).
The common language runtime (CLR) is the core runtime engine for executing applications in the .NET Framework. The CLR allows an instance of a class written in one language to call a method of the class written in another language. At the base level, it is the infrastructure that executes applications, and allows them to interact with the other parts of the Framework. The code which runs under the CLR is called as Managed Code. Programmers need not to worry on managing the memory if the programs are running under the CLR as it provides memory management and thread management. The main function of Common Language Runtime (CLR) is to convert the Managed Code into native code and then execute the Program. It acts as a layer between Operating Systems and the applications written in .Net languages.
Compilers and tools expose the common language runtime's functionality and enable you to write code that benefits from this managed execution environment. Code that you develop with a language compiler that targets the runtime is called managed code; it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services.
CLR handles the execution of code and provides useful services for the implementation of the program. In addition to executing code, CLR provides services such as memory management, thread management, security management, code verification, compilation, and other system services.
The main function of Common Language Runtime (CLR) is to convert the Managed Code into native code and then execute the Program. The Managed Code compiled only when it needed, that is it converts the appropriate instructions when each function is called . The Common Language Runtime (CLR) 's just in time (JIT) compilation converts Intermediate Language (MSIL) to native code on demand at application run time.
Functions of the CLR:
Class Loader:
Used to load all classes at run time.
MSIL to Native code compiler:
The Just In Time (JTI) compiler will convert MSIL code into native code.
Code Manager:
It manages the code at run time.
Garbage Collector:
It manages the memory. Collect all unused objects and deallocate them to reduce memory.
Thread Support:
It supports multi-threading of our application.
Exception Handler:
Exception Manager will handle exceptions thrown by application by executing catch block provided by exception, it there is no catch block , it will terminate application.

- Prof. Shardul P. Patil