Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

What .NET Represents?

NET stands for Network Enabled Technology. In .NET, dot (.) refers to object-oriented and NET
refers to the internet. So the complete .NET means through object-oriented we can implement
internet-based applications.
What is a Framework?
A framework is a software. Or you can say a framework is a collection of many small technologies
integrated together to develop applications that can be executed anywhere.
What does the DOTNET Framework provide?
The DOTNET Framework provides two things are as follows
1. BCL (Base Class Libraries)
2. CLR (Common Language Runtime)
BCL
Base Class Libraries (BCL) is designed by Microsoft. Without BCL we can’t write any code in .NET.
So, BCL is also known as the Building block of .NET Programs. These are installed into the machine
when we installed the .NET framework. BCL contains pre-defined classes and these classes are used
for the purpose of application development.
The physical location of BCL is C:\Windows\assembly
CLR
CLR stands for Common Language Runtime and it is the core component under the .NET framework
which is responsible for converting the MSIL (Microsoft Intermediate Language) code into native
code. In our next article, we will discuss CLR in detail.

In the .NET framework, the code is compiled twice.


1. In the 1st compilation, the source code is compiled by the respective language compiler and
generates the intermediate code which is known as MSIL (Microsoft Intermediate
Language) or IL (Intermediate language code) Or Managed Code.
2. In the 2nd compilation, MSIL is converted into Native code (native code means code specific
to the Operating system so that the code is executed by the Operating System ) and this is
done by CLR.
Always 1st compilation is slow and 2nd compilation is fast.
What is JIT?
JIT stands for the Just-in-Time compiler. It is the component of CLR that is responsible for
converting MSIL code into Native Code. Native code is the code that is directly understandable by
the operating system.
Different types of DOTNET Framework.
The .net framework is available in three different flavours
1. DOTNET Framework: This is the general version required to run .NET applications on
Windows OS only.
2. .NET mono Framework: This is required if we want to run DOT NET applications on other
OS like Unix, Linux, MAC OS, etc.
3. DOT NET Compact Framework: This is required to run .NET applications on other devices
like mobile phones and smartphones.
There is another company known as “NOVEL” designed a separate framework known as “MONO
Framework”. Using this framework, we can run MSIL on different OS Like Linux, UNIX, Mac,
BSD, OSX, etc.
.NET is platform-dependent using the .NET framework but independent using the MONO framework.
What is not DOT NET?
1. .NET is not an Operating system.
2. It is not an application or package.
3. .NET is not a database
4. It is not an ERP application.
5. .NET is not a Testing Tool.
6. It is not a programming language.
What is exactly DOTNET?
.NET is a framework tool that supports many programming languages and many technologies. .NET
support 60+ programming languages. In 60+ programming languages, 9 are designed by Microsoft
and the remaining are designed by non-Microsoft.
Microsoft designed programming languages are as follows
1. VB.NET
2. C#.NET
3. VC++.NET
4. J#.NET
5. F#.NET
6. Jscript.NET
7. WindowsPowerShell
8. Iron phyton
9. Iron Ruby
Technologies supported by the .NET framework are as follows
1. ASP.NET (Active Server Pages.NET)
2. ADO.NET (Active Data Object.NET)
3. WCF (Windows Communication Foundation)
4. WPF (Windows Presentation Foundation)
5. WWF (Windows Workflow Foundation)
6. AJAX (Asynchronous JavaScript and XML)
7. LINQ (Language Integrated Query)
What is a language and its need?
1. Language acts as the mediator between the programmer and the system.
2. It offers some rules and regulations for writing the program.
3. The language also offers some libraries which are required for writing the program.
What are Technology and its needs?
1. Technology is always designed for a particular purpose.
2. For example development of web-related applications in .NET using a technology ASP.NET.
3. But the technology does not offer any specific rules for writing the programs. That’s why
technology can’t be implemented individually.
4. VB.NET, C#.NET both are programming languages. Using these two languages we can
implement windows/desktop applications individually.
5. Every language is having its own compiler
MSIL
Example: The MSIL is generated by the language specific compiler from the source
code given below. To understand the MSIL in detail, simple C# source code with the
class Demo that prints “GeeksforGeeks  is given as follows:

using System;
  
public class Demo {
    public static void Main()
    {
        Console.WriteLine("GeeksforGeeks");
    }
}

The MSIL that is created by the C# compiler for the code provided above is given as
follows:

In the above MSIL, there are opcodes that are one or two bytes long. The base class
declarations from which all other classes are inherited are contained in the mscorlib.dll.
In the method Main(), the instruction ldstr loads the string “GeeksforGeeks” on the
stack. Then the static System.Console.Writeline function is called and the string is
popped from the stack. Finally, the ret instruction signals the end of the function call.
Then the .ctor() statement implies a default constructor without parameters for the class
Demo. This constructor is automatically created by the compiler for the non-static class
Demo. The call instruction passes the base object constructor and the ret instruction
signals the end of the function call.

Managed code and Unmanaged code


in .NET
The managed code also provides platform independence because when the
managed code compiled into the intermediate language, then the JIT compiler
compiles this intermediate language in the architecture specific instruction.

What are the advantages of using Managed Code?


 It improves the security of the application like when you use runtime
environment, it automatically checks the memory buffers to guard against
buffer overflow.
 It implement the garbage collection automatically.
 It also provides runtime type checking/dynamic type checking.
 It also provides reference checking which means it checks whether the
reference point to the valid object or not and also check they are not
duplicate.
What are the disadvantages of Managed Code?
The main disadvantage of managed language is that you are not allowed to
allocate memory directly, or you cannot get the low-level access of the CPU
architecture.

What is Unmanaged code?


A code which is directly executed by the operating system is known
as Unmanaged code. It always aimed for the processor architecture and
depends upon computer architecture. When this code is compiled it always
tends to get a specific architecture and always run on that platform, in other
words, whenever you want to execute the same code for the different
architecture you have to recompile that code again according to that
architecture. It always compiles to the native code that is specific to the
architecture.
In unmanaged code, the memory allocation, type safety, security, etc are
managed by the developer. Due to this, there are several problems related to
memory occur like buffer overflow, memory leak, pointer override, etc. The
executable files of unmanaged code are generally in binary images, x86 code
which is directly loaded into memory. The application written in VB 6.0, C, C++,
etc are always in unmanaged code. 
What are the advantages of using Unmanaged Code?
 It provides the low-level access to the programmer.
 It also provides direct access to the hardware.
 It allows the programmer to bypass some parameters and restriction that are
used by the managed code framework.
What are the disadvantages of Unmanaged Code?
 It does not provide security to the application.
 Due to the access to memory allocation the issues related to memory occur
like memory buffer overflow, etc.
 Error and exceptions are also handled by the programmer.
 It does not focus on garbage collection.

C# Command Line Arguments


Arguments that are passed by command line known as command line arguments.
We can send arguments to the Main method while executing the code. The
string args variable contains all the values passed from the command line.

In the following example, we are passing command line arguments during execution
of program.

C# Command Line Arguments Example

1. using System;  
2. namespace CSharpProgram  
3. {  
4.     class Program  
5.     {  
6.         // Main function, execution entry point of the program  
7.         static void Main(string[] args) // string type parameters  
8.         {  
9.             // Command line arguments  
10.             Console.WriteLine("Argument length: "+args.Length);  
11.             Console.WriteLine("Supplied Arguments are:");  
12.             foreach (Object obj in args)  
13.             {  
14.                 Console.WriteLine(obj);       
15.             }  
16.         }  
17.     }  
18. }  

Compile and execute this program by using following commands.

Compile: csc Program.cs

Execute: Program.exe Hi there, how are you?

After executing the code, it produces the following output to the console.

Output:

Stack Vs Heap Memory - C#


Difference between Stack and Heap Memory in C#
 
Category Stack Memory Heap Memory
It is an array of memory.

It is an area of memory where


It is a LIFO (Last In chunks are allocated to store
First Out) data certain kinds of data
What is Stack &
structure. objects.
Heap?
In it data can be stored and
In it data can be added removed in any order.
to and deleted only from
the top of it.
How Memory is
Manages?

 
 
   

Practical Scenario

Value of variable storing Value of variable storing in


in stack  heap 
"Things" declared with
"Things" declared with
the following list of
following list of type
type declarations are
declarations are Reference
Value Types
Types
(because they are from
What goes on Stack & (and inherit from
System.ValueType):
Heap?  System.Object... except, of
bool, byte, char, course, for object which is
decimal, double, enum, the System.Object object):
float, int, long, sbyte,
class, interface, delegate,
short, struct, uint,
object, string
ulong, ushort
Memory allocation is
Memory Allocation Memory allocation is Dynamic
Static
How is it Stored?  It is stored Directly It is stored indirectly
Is Variable Variables can’t be
Variables can be Resized
Resized?  Resized
Access Speed  Its access is fast Its access is Slow
Its block allocation is
reserved in LIFO.
How is Block Its block allocation is free
Allocated? Most recently reserved and done at any time
block is always the next
block to be freed.
It can be
Visibility or It can be visible/accessible
visible/accessible only
Accessibility to all the threads
to the Owner Thread
In recursion calls memory In recursion calls memory
In Recursion Calls?
filled up quickly filled up slowly
It can be used by one It can be used by all the
Used By?
thread of execution parts of the application
.NET Runtime throws
exception
StackOverflowExcepti
“StackOverflowException -
on
” when stack space is
exhausted
Local variables get wiped
When wiped off? off once they lose the -
scope
It contains values for
Integral Types, Primitive
Contains -
Types and References to
the Objects
It is a special thread
created by .NET runtime to
monitor allocations of heap
Garbage Collector  - space.
It only collects heap memory
since objects are only
created in heap

Summary
 
Now, I believe you will be able to know the key difference between Stack and
Heap Memory in C#.
 

Reference Type and Value Type


C# Concepts - Value Type And Reference
Type
Value type
Value types are generally (not always) stored on the stack and are passed by
copying.

The way in which a variable assignment works differs between reference and value
types.

If we have something like:


class Program{

static void Main(string[] args )

{
A obj1 = new A(12);

int v1 = 12;

int v2 = 22;

v2 = v1 ;

Console .WriteLine( v2 );

Console .ReadLine();

}}

Reference Type
A value type is basically stored on the heap and passed by creating a reference.

using System;

class A {

public int value {

get; set;

public A(int passbyref)

{ this.value = passbyref; }

class Program {

static void Main(string[] args) {

A v1 = new A(12); A v2 = new A(22); //Breakpoint v2 = v1;


Console.WriteLine(v1.value);

Console.WriteLine(v2.value); Console.ReadLine();

Implementation

v1 and v2 will be on the heap as two entities until a breakpoint.


And after the breakpoint, they both point to one entity.

Conclusion
Once you pass a value type, you pass a copy to the other method.

But what if we want to change it? Use the “ref” keyword for that.

C# | Boxing And Unboxing


Boxing and unboxing are important concepts in C#. The C# Type System
contains three data types : Value Types (int, char, etc), Reference Types
(object) and Pointer Types. Basically, Boxing converts a Value Type variable
into a Reference Type variable, and Unboxing achieves the vice-versa. Boxing
and Unboxing enable a unified view of the type system in which a value of any
type can be treated as an object.

Boxing In C#
 The process of converting a Value Type variable (char, int etc.) to
a Reference Type variable (object) is called Boxing.
 Boxing is an implicit conversion process in which object type (super type) is
used.
 Value Type variables are always stored in Stack memory, while Reference
Type variables are stored in Heap memory.
 Example :
int num = 23; // 23 will assigned to num
Object Obj = num; // Boxing
 Description : First, we declare a Value Type variable num of the
type int and initialise it with value 23. Now, we create a Reference Type
variable obj of the type Object and assign num to it. This assignment
implicitly results in the Value Type variable num to be copied and stored in
Reference Type variable obj as shown in below figure :
below figure :

Boxing
Unboxing In C#
 The process of converting a Reference Type variable into a Value
Type variable is known as Unboxing.
 It is an explicit conversion process.
 Example :
int num = 23; // value type is int and assigned value 23
Object Obj = num; // Boxing
int i = (int)Obj; // Unboxing
 Description : We declare a Value Type variable num, which is of the
type int and assign it with integer value 23. Now, we create a Reference
Type variable obj of the type Object,  in which we box the
variable num. Now, we create a Value Type integer i to unbox the value
from obj. This is done using the casting method, in which we explicitly
specify that obj must be cast as an int value. Thus, the Reference Type
variable residing in the heap memory is copied to stack 
 in below figure :

Unboxing

Collections
In many applications we need to create and manage groups of related objects. There
are two ways to do it, either by creating an array of objects or by creating a collection
of objects.

Arrays are most useful for creating a fixed number of strongly typed objects.

Collections provide a more flexible way to work with groups of objects and the group
of objects you work with can grow and shrink dynamically as the needs of the
application change. It also allows access to a list of items using an index. C#
collections classes are defined as part of the System.Collections.

Various Collections Classes and Their Usage


The following are the various commonly used classes of the System.Collections
namespace.
ArrayList
ArrayList represents an ordered collection of a specified object that can be indexed
individually. It allows dynamic memory allocation, adding, searching and sorting
items in the list.

The following are the properties of the ArrayList class:


1. Capacity: Gets or sets the number of elements that the ArrayList can contain.
2. Count: Returns the number of elements present in the ArrayList.
3. IsFixedSize: Returns a value indicating whether the ArrayList has a fixed size.
4. IsReadOnly: Returns a value indicating whether the ArrayList is read-only.
5. Item: Gets or sets the element at the specified index position.
The following are the methods of the ArrayList class,
1. public virtual int add(object value); Inserts the object at the end of the ArrayList.
2. public virtual void AddRange(Icollection c); Adds the elements of a collection to
the end of the ArrayList.
3. public virtual void Clear(); Removes all the elements from the ArrayList. Does
not affect the capacity of the ArrayList.
4. public virtual bool Contains(object item); Determines whether an element is
present or not in the ArrayList.
5. public virtual ArrayList GetRange( int index, int count ); Returns an ArrayList
that represents a subset of the elements in the source ArrayList.
6. public virtual int IndexOf(object); Returns the index of the first occurrence of a
value in the ArrayList or in a portion of it.
7. public virtual void Insert(int index, object value); Inserts an element into the
ArrayList at the specified index.
8. public virtual void InsertRange(int index, ICollection c); Inserts the element of a
collection into the ArrayList at the specified index.
9. Public virtual void Remove(object obj); Removes the first occurrence of a
specified object from the ArrayList.
10. public virtual void RemoveAt(int index); Removes the element at the given
specified index of the ArrayList.
11. public virtual void RemoveRange(int index,int count); Removes a range of
elements from the ArrayList.
12. public virtual void Reverse(); Reverses the order of the elements in the
ArrayList.
13. public virtual void Sort(); Sorts all the elements in the ArrayList.
14. public virtual void TrimToSize(); Sets the capacity to the actual number of
elements present in the ArrayList. Basically the capacity is not increased one by
one. Capacity is just doubled each time whenever the size reaches the
threshold. So the TrimToSize() method sets the capacity to the exact the size of
the ArrayList.

The following is the example,


1. using System;  
2. using System.Collections;  
3.   
4. namespace Collection_Example  
5. {  
6.     class Program  
7.     {  
8.         static void Main(string[] args)  
9.         {  
10.             ArrayList al = new ArrayList();  
11.             ArrayList al1 = new ArrayList();  
12.             // Adding object into the ArrayList  
13.             al1.Add('a');  
14.             al1.Add('b');  
15.             al.Add('k');  
16.             al.Add('l');  
17.             al.Add('j');  
18.             // Adding Arraylist at specific position into the ArrayL
ist  
19.             al.InsertRange(2,al1);              
20.             //Get the Capacity and number of element present in the 
ArrayList  
21.             // Note that Capacity and Count are not equal  
22.             Console.WriteLine("Count: {0}", al.Count);  
23.             Console.WriteLine("Capacity before TrimToSize: {0} ", al
.Capacity);  
24.             al.TrimToSize();  
25.             Console.WriteLine("Capacity after TrimToSize: {0} ", al.
Capacity);  
26.             Console.WriteLine(al.Contains('b'));  
27.             Console.Write("Element befor sort: ");  
28.             foreach (object obj in al)  
29.                 Console.Write(obj + " ");  
30.             Console.Write("\nElement after sort: ");  
31.             al.Sort();  
32.             foreach (object obj in al)  
33.                 Console.Write(obj + " ");  
34.             al.Reverse();  
35.             Console.Write("\nElement after reverse: ");  
36.             foreach (object obj in al)  
37.                 Console.Write(obj + " ");  
38.             Console.WriteLine("\nIndex of char 'k' is : {0}", al.Ind
exOf('k'));  
39.             // clear the ArrayList  
40.             al.Clear();  
41.             Console.WriteLine("\nCount: {0}", al.Count);  
42.             Console.ReadKey();  
43.         }  
44.     }  
45. }  

Output

HashTable
The Hashtable class represents a collection of key-and-value pairs organized based
on the hash code of the key. It uses the key to access the elements in the collection.
Hash table is used when you need to access elements using a key. Each item in the
hash table has a key/value pair. The key is used to access the items in the
collection.

The following are the properties of HashTable class,


1. Count: Returns the number of elements present in the Hashtable.
2. IsFixedSize: Returns a value indicating whether the Hashtable has a fixed size.
3. IsReadOnly: Returns a value indicating whether the Hashtable is read-only.
4. Item: Gets or sets the value with the specific key.
5. Keys: Returns an ICollection containing the keys in the HashTable.
6. Values: Returns an ICollection containing the values in the HashTable.
7.
The following are the methods of the HashTable Class:-
1. public virtual void add(object key,object value); Adds a value with the specified
key into the HashTable.
2. public virtual void Clear(); Clears the HashTable.
3. public virtual bool ContainsKey(object key); Determines whether the HashTable
contains a specific key, if Yes then returns true otherwise it returns false.
4. public virtual bool ContainsValue(object key); Determines whether the
HashTable contains a specific value, if Yes then returns true otherwise it returns
false.
5. public virtual void Remove(object key); Removes an element with the specific
key from the HashTable.
6.
The following is the example:
1. using System;  
2. using System.Collections;  
3.   
4. namespace Collection_Example  
5. {  
6.     class Program  
7.     {  
8.         static void Main(string[] args)  
9.         {  
10.             Hashtable ht = new Hashtable();  
11.             //Adding item into HashTable  
12.             ht.Add(1, "Alwar");  
13.             ht.Add(12, "Ajmer");  
14.             ht.Add(8, "Jaipur");  
15.             ht.Add(4, "Kota");  
16.             Console.WriteLine("Count : {0}", ht.Count);  
17.             if (ht.ContainsValue("Sikar"))  
18.                 Console.WriteLine("Sikar is already exist in the Has
hTable");  
19.             else  
20.                 ht.Add(5, "Sikar");  
21.   
22.             //Get a collection of values  
23.             Console.WriteLine("Values are :");  
24.             ICollection values = ht.Values;  
25.             foreach (string str in values)  
26.                 Console.WriteLine(str);  
27.             //Get a collection of Keys  
28.             Console.WriteLine("Keys are :");  
29.             ICollection keys = ht.Keys;  
30.             foreach (int i in keys)  
31.                 Console.WriteLine(i);  
32.             ht.Remove(3);  
33.             ht.Clear();  
34.             Console.ReadKey();  
35.         }  
36.     }  
37. }  
Output

C# Generic & Non-generic


Collections
C# includes specialized classes that store series of values or objects are called
collections.
There are two types of collections available in C#: non-generic collections and
generic collections.
The System.Collections namespace contains the non-generic collection types
and System.Collections.Generic namespace includes generic collection types.
In most cases, it is recommended to use the generic collections because they
perform faster than non-generic collections and also minimize exceptions by giving
compile-time errors.
Generic Collections
Generic collection in C# is defined in System.Collection.Generic  namespace. It
provides a generic implementation of standard data structure like linked lists,
stacks, queues, and dictionaries. These collections are type-safe because they
are generic means only those items that are type-compatible with the type of the
collection can be stored in a generic collection, it eliminates accidental type
mismatches. Generic collections are defined by the set of interfaces and
classes.

C# includes the following generic collection classes in


the System.Collections.Generic namespace.

Generic Collections Description

List<T> Generic List<T> contains elements of specified type. It grows


automatically as you add elements in it.

Dictionary<TKey,TValue> Dictionary<TKey,TValue> contains key-value pairs.

SortedList<TKey,TValue> SortedList stores key and value pairs. It automatically adds the
elements in ascending order of key by default.

Queue<T> Queue<T> stores the values in FIFO style (First In First Out). It
keeps the order in which the values were added. It provides an
Enqueue() method to add values and a Dequeue() method to
retrieve values from the collection.

Stack<T> Stack<T> stores the values as LIFO (Last In First Out). It


provides a Push() method to add a value and Pop() & Peek()
methods to retrieve values.

Hashset<T> Hashset<T> contains non-duplicate elements. It eliminates


duplicate elements.

Example:

// C# program to illustrate the concept 


// of generic collection using List<T>
using System;
using System.Collections.Generic;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating a List of integers
        List<int> mylist = new List<int>();
  
        // adding items in mylist
        for (int j = 5; j < 10; j++) {
            mylist.Add(j * 3);
        }
  
        // Displaying items of mylist
        // by using foreach loop
        foreach(int items in mylist)
        {
            Console.WriteLine(items);
        }
    }
}

Output:
15
18
21
24
27

Non-generic Collections
Non-Generic collection in C# is defined in System.Collections namespace. It is
a general-purpose data structure that works on object references, so it can
handle any type of object, but not in a safe-type manner. Non-generic
collections are defined by the set of interfaces and classes. Below table
contains the frequently used classes of the System.Collections namespace:

Non-generic
Collections Usage

ArrayList ArrayList stores objects of any type like an array. However, there is no
need to specify the size of the ArrayList like with an array as it grows
automatically.

SortedList SortedList stores key and value pairs. It automatically arranges elements in
ascending order of key by default. C# includes both, generic and non-
generic SortedList collection.

Stack Stack stores the values in LIFO style (Last In First Out). It provides a
Push() method to add a value and Pop() & Peek() methods to retrieve
values. C# includes both, generic and non-generic Stack.
Non-generic
Collections Usage

Queue Queue stores the values in FIFO style (First In First Out). It keeps the order
in which the values were added. It provides an Enqueue() method to add
values and a Dequeue() method to retrieve values from the collection. C#
includes generic and non-generic Queue.

Hashtable Hashtable stores key and value pairs. It retrieves the values by comparing
the hash value of the keys.

BitArray BitArray manages a compact array of bit values, which are represented as
Booleans, where true indicates that the bit is on (1) and false indicates the
bit is off (0).

Example:

// C# to illustrate the concept


// of non-generic collection using Queue
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Queue
        Queue myQueue = new Queue();
  
        // Inserting the elements into the Queue
        myQueue.Enqueue("C#");
        myQueue.Enqueue("PHP");
        myQueue.Enqueue("Perl");
        myQueue.Enqueue("Java");
        myQueue.Enqueue("C");
  
        // Displaying the count of elements
        // contained in the Queue
        Console.Write("Total number of elements present in the Queue are:
");
  
        Console.WriteLine(myQueue.Count);
  
        // Displaying the beginning element of Queue
        Console.WriteLine("Beginning Item is: " + myQueue.Peek());
    }
}

Output:
Total number of elements present in the Queue are: 5
Beginning Item is: C#

Assemblies in .NET
Assemblies are the fundamental units of deployment, version control, reuse,
activation scoping, and security permissions for .NET-based applications. An
assembly is a collection of types and resources that are built to work together and
form a logical unit of functionality. Assemblies take the form of executable (.exe) or
dynamic link library (.dll) files, and are the building blocks of .NET applications. They
provide the common language runtime with the information it needs to be aware of
type implementations.

In .NET and .NET Framework, you can build an assembly from one or more source
code files. In .NET Framework, assemblies can contain one or more modules. This
way, larger projects can be planned so that several developers can work on separate
source code files or modules, which are combined to create a single assembly.

Assemblies have the following properties:

 Assemblies are implemented as .exe or .dll files.

 For libraries that target .NET Framework, you can share assemblies between
applications by putting them in the global assembly cache (GAC). You must
strong-name assemblies before you can include them in the GAC. For more
information, see Strong-named assemblies.

 Assemblies are only loaded into memory if they're required. If they aren't used,
they aren't loaded. Therefore, assemblies can be an efficient way to manage
resources in larger projects.
 You can programmatically obtain information about an assembly by using
reflection. For more information, see Reflection (C#) or Reflection (Visual Basic).

 You can load an assembly just to inspect it by using


the MetadataLoadContext class on .NET and .NET
Framework. MetadataLoadContext replaces
the Assembly.ReflectionOnlyLoad methods.

What is a .Net Assembly?


 
The .NET assembly is the standard for components developed with the
Microsoft.NET. Dot NET assemblies may or may not be executable, i.e., they might
exist as the executable (.exe) file or dynamic link library (DLL) file. All the .NET
assemblies contain the definition of types, versioning information for the type, meta-
data, and manifest. The designers of .NET have worked a lot on the component
(assembly) resolution.
 
An assembly can be a single file or it may consist of the multiple files. In the case of
multi-file, there is one master module containing the manifest while other assemblies
exist as non-manifest modules. A module in .NET is a subpart of a multi-file .NET
assembly. Assembly is one of the most interesting and extremely useful areas
of .NET architecture along with reflections and attributes. 
 
.NET supports three kinds of assemblies:
1. private
2. shared
3. satellite
Private Assembly
 
Private assembly requires us to copy separately in all application folders where we
want to use that assembly’s functionalities; without copying, we cannot access the
private assembly features and power. Private assembly means every time we have
one, we exclusively copy into the BIN folder of each application folder.
 
Public Assembly
 
Public assembly is not required to copy separately into all application folders. Public
assembly is also called Shared Assembly. Only one copy is required in system level,
there is no need to copy the assembly into the application folder.
 
Public assembly should install in GAC.
 
Shared assemblies (also called strong named assemblies) are copied to a single
location (usually the Global assembly cache). For all calling assemblies within the
same application, the same copy of the shared assembly is used from its original
location. Hence, shared assemblies are not copied in the private folders of each
calling assembly. Each shared assembly has a four-part name including its face
name, version, public key token, and culture information. The public key token and
version information makes it almost impossible for two different assemblies with the
same name or for two similar assemblies with a different version to mix with each
other.
 
Learn How to Create and Use a Shared Assembly 
 
GAC (Global Assembly Cache)
 
When the assembly is required for more than one project or application, we need to
make the assembly with a strong name and keep it in GAC or in the Assembly folder
by installing the assembly with the GACUtil command.
 
Satellite Assembly
 
Satellite assemblies are used for deploying language and culture-specific resources
for an application.
C# - Properties
Properties are named members of classes, structures, and interfaces. Member
variables or methods in a class or structures are called Fields. Properties are an
extension of fields and are accessed using the same syntax. They
use accessors through which the values of the private fields can be read, written or
manipulated.
Properties do not name the storage locations. Instead, they have accessors that
read, write, or compute their values.
For example, let us have a class named Student, with private fields for age, name,
and code. We cannot directly access these fields from outside the class scope, but
we can have properties for accessing these private fields.

C# - Indexers
An indexer allows an object to be indexed such as an array. When you define
an indexer for a class, this class behaves similar to a virtual array. You can
then access the instance of this class using the array access operator
([ ]).Syntax

A one dimensional indexer has the following syntax −


element-type this[int index] {
// The get accessor.
get {
// return the value specified by index
}

// The set accessor.


set {
// set the value specified by index
}
}

Use of Indexers
Declaration of behavior of an indexer is to some extent similar to a property. similar
to the properties, you use get and set accessors for defining an indexer. However,
properties return or set a specific data member, whereas indexers returns or sets a
particular value from the object instance. In other words, it breaks the instance data
into smaller parts and indexes each part, gets or sets each part.
Defining a property involves providing a property name. Indexers are not defined
with names, but with the this keyword, which refers to the object instance. The
following example demonstrates the concept −
using System;
namespace IndexerApplication {

class IndexedNames {
private string[] namelist = new string[size];
static public int size = 10;

public IndexedNames() {
for (int i = 0; i < size; i++)
namelist[i] = "N. A.";
}
public string this[int index] {
get {
string tmp;
if( index >= 0 && index <= size-1 ) {
tmp = namelist[index];
} else {
tmp = "";
}

return ( tmp );
}
set {
if( index >= 0 && index <= size-1 ) {
namelist[index] = value;
}
}
}
static void Main(string[] args) {
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";

for ( int i = 0; i < IndexedNames.size; i++ ) {


Console.WriteLine(names[i]);
}
Console.ReadKey();
}
}}

When the above code is compiled and executed, it produces the following result −
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.

Basics of File Handling in C#


Generally, the file is used to store the data. The term File Handling refers to the
various operations like creating the file, reading from the file, writing to the file,
appending the file, etc. There are two basic operation which is mostly used in
file handling is reading and writing of the file. The file becomes stream when we
open the file for writing and reading. A stream is a sequence of bytes which is
used for communication. Two stream can be formed from file one is input
stream which is used to read the file and another is output stream is used to
write in the file. In C#, System.IO namespace contains classes which handle
input and output streams and provide information about file and directory
structure.

File-Handling-Class-Hierarchy

Here we are going to discuss about two classes which are useful for writing in
and reading from the text file.
StreamWriter Class
The StreamWriter class implements TextWriter for writing character to stream in
a particular format. The class contains the following method which are mostly
used.

Method Description

Close() Closes the current StreamWriter object and stream associate


with it.

Flush() Clears all the data from the buffer and write it in the stream
associate with it.
Method Description

Write() Write data to the stream. It has different overloads for different
data types to write in stream.

WriteLine() It is same as Write() but it adds the newline character at the


end of the data.

Example:-
// C# program to write user input 
// to a file using StreamWriter Class
using System;
using System.IO;
  
namespace GeeksforGeeks {
      
class GFG {
      
    class WriteToFile {
          
        public void Data()
        {
            // This will create a file named sample.txt
            // at the specified location 
            StreamWriter sw = new StreamWriter("H://geeksforgeeks.txt");
              
            // To write on the console screen
            Console.WriteLine("Enter the Text that you want to write on
File"); 
              
            // To read the input from the user
            string str = Console.ReadLine(); 
              
            // To write a line in buffer
            sw.WriteLine(str); 
              
            // To write in output stream
            sw.Flush(); 
              
            // To close the stream
            sw.Close(); 
        }
    }
      
    // Main Method
    static void Main(string[] args)
    {
        WriteToFile wr = new WriteToFile();
        wr.Data();
        Console.ReadKey();
    }
}
}

StreamReader Class
The StreamReader class implements TextReader for reading character from the
stream in a particular format. The class contains the following method which are
mostly used.

Method Description

Close() Closes the current StreamReader object and stream associate


with it.

Peek() Returns the next available character but does not consume it.

Read() Reads the next character in input stream and increment


characters position by one in the stream

ReadLine() Reads a line from the input stream and return the data in form
of string

Seek() It is use to read/write at the specific location from a file

Example:

// C# program to read from a file


// using StreamReader Class
using System;
using System.IO;
  
namespace GeeksforGeeks {
      
class GFG {
      
    class ReadFile {
          
        public void DataReading()
        {
            // Takinga a new input stream i.e. 
            // geeksforgeeks.txt and opens it
            StreamReader sr = new StreamReader("H://geeksforgeeks.txt");
              
            Console.WriteLine("Content of the File"); 
              
            // This is use to specify from where 
            // to start reading input stream
            sr.BaseStream.Seek(0, SeekOrigin.Begin);
              
            // To read line from input stream
            string str = sr.ReadLine(); 
              
            // To read the whole file line by line
            while (str != null) 
            {
                Console.WriteLine(str);
                str = sr.ReadLine();
            }
            Console.ReadLine(); 
              
            // to close the stream
            sr.Close(); 
        }
    }
      
    // Main Method
    static void Main(string[] args)
    {
        ReadFile wr = new ReadFile();
        wr.DataReading();
    }
}
}

HOW TO USE FILESTREAM CLASS IN C#?


In order to use FileStream class you need to include System.IO namespace and then
create FileStream Object to create a new file or open an existing file.

. FileStream <object_name> = new FileStream( <file_name>, <FileMode


Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>);

FileMode – It specifies how to operation system should open the file. It has following
members  
1. Append - Open the file if exist or create a new file. If file exists then place cursor at
the end of the file.
2. Create - It specifies operating system to create a new file. If file already exists then
previous file will be overwritten.
3. CreateNew - It create a new file and If file already exists then
throw IOException.
4. Open – Open existing file.
5. Open or Create – Open existing file and if file not found then create new file.
6. Truncate – Open an existing file and cut all the stored data. So the file size becomes
0.

FileAccess – It gives permission to file whether it will


open Read, ReadWrite or Write mode. FileShare – It opens file with following share
permission.

1. Delete – Allows subsequent deleting of a file.


2. Inheritable – It passes inheritance to child process.
3. None – It declines sharing of the current files.
4. Read- It allows subsequent opening of the file for reading.
5. ReadWrite – It allows subsequent opening of the file for reading or writing.
6. Write – Allows subsequent opening of the file for writing.

You might also like