What Are CTS And CLS In .NET
CTS and CLS are parts of .NET CLR and are responsible for type safety within the code. Both allow cross-language communication and type safety. In this article, I would like to expose the relationship between these two.
CLS stands for Common Language Specification and it is a subset of CTS. It defines a set of rules and restrictions that every language must follow which runs under the .NET framework. The languages which follow these set of rules are said to be CLS Compliant. In simple words, CLS enables cross-language integration or Interoperability.
So these syntax rules which you have to follow from language to language differ but CLR can understand all the language Syntax because in .NET each language is converted into MSIL code after compilation and the MSIL code is language specification of CLR.
Common Type System (CTS) describes the datatypes that can be used by managed code. CTS defines how these types are declared, used and managed in the runtime. It facilitates cross-language integration, type safety, and high-performance code execution. The rules defined in CTS can be used to define your own classes and values.
OR we can also understand like,
CTS deals with the data type. So here we have several languages and each and every language has its own data type and one language data type cannot be understandable by other languages but .NET Framework language can understand all the data types.
C# has an int data type and VB.NET has Integer data type. Hence a variable declared as an int in C# and Integer in VB.NET, finally after compilation, uses the same structure Int32 from CTS.
Note
All the structures and classes available in CTS are common for all .NET Languages and the purpose of these is to support language independence in .NET. Hence it is called CTS.
Hello everybody, good afternoon! Today I am gonna shed some light over old concepts. Although these are old but you will get questions about these every time in every interview. Full stack developer always face questions over these topics. Either you have 1-5 or 5-10 years of exposer in MS technologies. although you are working with angular or .NET core. However, interviewer will definitely ask these questions. I know some candidate always says why these old things they ask. These are part of theory then why why!
Actually there is a reason to ask queries over these topics. 1) How much you are aware about the framework internal work process. Do you about which datatype and why they introduced casting. Are you aware about memory management technique in .NET or just declaring and defining variables or classes without understanding. Why Microsoft did categorization of class libraries and namespaces. It happen people learn always how to fight with guns but they do not know how to fight with normal knife or a blade or without weapon.
You will get so many tutorials and blogs, articles over these topics. However, here I will try to make you understand from my personal experience.
First we will talk about .NET architecture which is very important to understand then only we can come to know where all these components exist. This architecture can change as per framework version. But here I am sharing with you basic architecture which is common in all frameworks. Last .NET framework version is 4.7.1 after this Microsoft did not introduced any new version. Due to hard competition in the market and lot of open source cross platform technologies, they also introduced .NET core with cross platform functionality. So these days its prevailing in market. Every .NET framework had new features. So now we will discuss about CLS ,CTS and BCL,FCL.
.NET framework is a platform which provides tools and technologies to build WEB, Desktop, Mobile or Logistics, Enterprise , Ecommerce applications. It has mainly two components.
1) .NET Framework or Base Class Library (FCL or BCL)
2) CLR - common language runtime
First of all we will discuss about FCL. What's this and what type of role it has in .NET Framework.
FCL is a common class library for all applications which can be developed through .NET Framework. i.e. the way we access the Library Classes and Methods in VB.NET will be the same in C#, and it is common for all other languages in .NET. Class library is the collection of reusable types that are closely integrated with CLR.
Following are different types of applications that can make use of .NET class library.
- Windows, Console, Web Application, XML Web Services, Windows Services.
In shorts, developer simply have to import or add libraries, classes and he will be able to use methods, properties or implement common or complex functionalities such read files, xml connectivity, data connection, read, update, delete.
FCL is superset of BCL. BCL is a core class library and FCL having some advance class libraries. The Framework Class Library (FCL) is the wider library that contains the totality: ASP.NET, WinForms, the XML stack, ADO.NET and more. You could say that the FCL includes the BCL. BCL from mscorlib and System.dll.
Hope friends you got till now What's FCL and use of its in our daily development.
So we have some more terms and components which we will discuss. such CTS and CLS.
CTS : means common type system. This is a standard which specifies how types are declared, used and managed in CLR. CLS and CTS both are part of CLR and allow in .NET language cross language communication and type safety. It defines rules that every language must follow which runs under .NET framework. It ensures that objects written in different .NET languages like C#, VB.NET, F# etc. can interact with each other. The common type system supports two general categories of types:
Value types: These types directly contain their data, and instances of value types are either allocated on the stack or allocated inline in a structure. Value types can be built-in (implemented by the runtime), user-defined, or enumerations.
Reference types: These types store a reference to the value's memory address, and are allocated on the heap. Reference types can be self-describing types, pointer types, or interface types. The type of a reference type can be determined from values of self-describing types. Self-describing types are further split into arrays and class types. The class types are user-defined classes, boxed value types, and delegates
For example, C# has int Data Type and VB.Net has Integer Data Type. Hence a variable declared as int in C# or Integer in vb.net, finally after compilation, use the same structure Int32 from CTS.
Type safety in .NET has been introduced to prevent the objects of one type from peeking into the memory assigned for the other object. Other words C# would not allow one object can not sneak into other objects memory.
public class CostItems{ public int Prop{ get; set;} } public class AccountCode { public int Prop{get;set;} public int Prop1{get;set;} }
Here If I will cast it then a compile time error will arise because of the Type Safe feature in C#.
CLS :- which is subset of CTS. Common language specifications. This defines Set of Rules which every language must follow which run under .NET Framework. Every language which follows these rules thats known as CLS compliant.
E.g. It enables cross language integration. Means If I write business logic code in C# and want to consume VB.net Application.
Another rule example is such as we can not use multiple inheritance in C#. But In C++ can do it.
Another rule is like VB.net is not case sensitive although C# is case sensitive. So we can do ADD() and add() in C# code.
So now we will discuss over CLR which is major component and brain of .NET framework. This component work flow process always asked in interview although you are C# developer or Javascript developer. But here I will explain about only .NET Framework CLR work flow and features.
CLR stands for common language runtime or virtual machine which manage to code execution through JIT compilers, memory management, debugging, Garbage collection, Thread support, exception handling and code access security. These are major features of CRL and duties.
Here Interviewer always ask about these features in details and candidate always go without preparation of these :) or sometime forget to recall all these :). But today we will once again go through all these and see what are these duties and how beneficial in daily development work.
1) Code Execution : - It provides an environment to run all the .NET Programs. The code which runs under the CLR is called as Managed Code.
Managed code is a code whose execution is managed by Common Language Runtime. It gets the managed code and compiles it into machine code. After that, the code is executed. The runtime here i.e. CLR provides automatic memory management, type safety, etc.
Applications that are not under the control of the CLR are unmanaged 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. Programmatically, when our program needs memory, CLR allocates the memory for scope and de-allocates the memory if the scope is completed. Language Compilers (e.g. C#, VB.Net, J#) will convert the Code/Program to Microsoft Intermediate Language (MSIL/IL/CIL) internal this will be converted to Native Code by CLR.
Here one question comes in mind that how MSIL is converting to Native Code or Machine Code. Yes guys. Here JIT compilers comes in picture and play important role for compilation process.
JIT and the CLR’s ‘Execution Engine’ (EE) or ‘Virtual Machine’ (VM) work closely with one another. JIT comes in picture only in RUNTIME Compilation.
JIT means just in time compiler. These three types.
1) Normal : 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.
2) Ecno : This complies only those methods that are called at runtime and removes them from memory after execution.
3) Pre : This complies entire MSIL code into native code in a single compilation cycle. This is done at the time of deployment of the application.
2) Memory Management : CLR take care of allocation and release to memory for object in heap. *(Not in Stack)
But HOW ? There is GC component which plays a main role for this functionality.
Garbage Collector (GC)
The Garbage Collector (GC) is the part of the .NET Framework that allocates and releases memory for your .NET applications. CLR manages allocation and deallocation of a managed object in memory. Programmers never do this directly and there is no delete keyword in the C# language. It relies on the garbage collector.
The .NET objects are allocated to a region of memory termed the managed heap. They will be automatically destroyed by the garbage collector. Heap allocation only occurs when you are creating instances of classes. It eliminates the need for the programmer to manually delete objects that are no longer required for program execution. This reuse of memory helps reduce the amount of total memory that a program needs to run. Objects are allocated in the heap continuously, one after another. It is a very fast process, since it is just adding a value to a pointer. The process of releasing memory is called garbage collection. It releases only objects that are no longer being used in the application. A root is a storage location containing a reference to an object on the managed heap. The runtime will check objects on the managed heap to determine whether they are still reachable (in other words, rooted) by the application. The CLR builds an object graph, that represents each reachable object on the heap. Object graphs are used to document all reachable objects.
GC works on managed heap, which is nothing but a block of memory to store objects, when GC process is put in motion, it checks for dead objects and the objects which are no longer used, then it compacts the space of live object and tries to free more memory.
Basically, heap is managed by different 'Generations', it stores and handles long-lived and short-lived objects, see the below generations of Heap:
0 Generation (Zero): This generation holds short-lived objects, e.g., Temporary objects. GC initiates garbage collection process frequently in this generation.
1 Generation (One): This generation is the buffer between short-lived and long-lived objects.
2 Generation (Two): This generation holds long-lived objects like a static and global variable, that needs to be persisted for a certain amount of time. Objects which are not collected in generation Zero, are then moved to generation 1, such objects are known as survivors, similarly objects which are not collected in generation One, are then moved to generation 2 and from there onwards objects remain in the same generation.
GC checks the below information to check if the object is live:
- It collects all handles(just a reference or opaque number in memory) of an object that are allocated by user code or by CLR
- Keeps track of static objects, as they are referenced to some other objects
- Use stack provided by stack walker and JIT
There are no specific timings for GC to get triggered, GC automatically starts operation on the following conditions:
- When virtual memory is running out of space.
- When allocated memory is suppressed acceptable threshold (when GC found if the survival rate (living objects) is high, then it increases the threshold allocation).
- When we call GC.Collect() method explicitly, as GC runs continuously, we actually do not need to call this method.
3) Code Access Security : This is core feature of CLR. Security means preventing code execution from unauthorized access Or providing security to assets from unauthorized actions through permission by putting over code execution.
CAS is only possible with managed code not with unmanaged code. for this purpose in the .NET Framework CAS policy must be enabled. If CAS is used to restrict the permissions of an assembly then the assembly is considered partially trusted. Partially trusted assemblies must undergo CAS permission checks each time they access a protected resource. Fully trusted assemblies, like unmanaged code, can access any system resource that the user has permissions to access.
4 ) Debugging : This is a major feature of CLR which we use daily in our code development for testing , bug fixing and while executing code over our local work station.
5) Thread Support : CLR provides functionality to handle threading and multithreading functionality for code in application. CLR thread pool determines when threads are to be added or taken away. Thread pool is just collection of threads and thread is a path of execution. Thread is a part of process. Process means a executing program.
The CLR thread pool contains two kinds of threads—the worker threads and the I/O completion port or IOCP threads. That means your ASP.Net worker process actually contains two thread pools: the worker thread pool and the IOCP thread pool. Actually, these pools have different purposes.
When you use methods like Task.Run, TaskFactory.StartNew, and ThreadPool.QueueUserWorkItem, the runtime takes advantage of worker threads for processing. When you make asynchronous I/O calls in your application, or your application accesses the file system, databases, web services, etc., then the runtime uses IOCP threads. The .Net thread pool injects or removes threads at intervals of 500 milliseconds or as a thread becomes free, whichever comes first. Now, based on the feedback available to the runtime, the .Net thread pool either removes threads or adds threads to maximize the throughput.
E.g. Now suppose you are running your ASP.Net application on IIS and your web server has a total of four CPUs. Assume that at any given point in time, there are 24 requests to be processed. By default the runtime would create four threads(always equal to number of CPU core), which would be available to service the first four requests. Because no additional threads will be added until 500 milliseconds have elapsed, the other 20 requests will have to wait in the queue. After 500 milliseconds have passed, a new thread is created.
As you can see, it will take many 500ms intervals to catch up with the workload. This is a good reason for using asynchronous programming. With async programming, threads aren’t blocked while requests are being handled, so the four threads would be freed up almost immediately.
Recommended thread settings
Given the way the .Net thread pool works and what we have discussed thus far, it is strongly recommended that you change the minimum configuration value—the default value—for both worker and IOCP threads. To do this in ASP.Net, you should change the minWorkerThreads and minIoThreads configuration settings under the <processModel> configuration element in the machine.config file in your system.
<configuration> <system.web> <processModel minWorkerThreads=”provide your desired value here” minIoThreads=”provide your desired value here” /> </system.web> < </configuration>
You can set the minimum configuration values for both worker and IOCP threads to any value between one and 50. A good approach is to take a user mode process dump of the IIS worker process (W3wp.exe) and then use the !threadpool command to report the total number of worker threads. Once you know this value, simply divide it by the number of processor cores on your system to determine the minimum worker and IOCP thread settings. For example, if the total count of worker threads is 100 and you have four processors in your system, you can set the minimum values for both worker and IOCP threads to 25.
To change the default minimum thread settings outside of ASP.Net, you can use the ThreadPool.SetMinThreads() method.
With the goal of better thread management and improved performance, the CLR thread pool has been improved with each version of the CLR. As an example, with .Net Framework 4, the CLR gained thread stealing algorithms and support for concurrency and parallelism. With each new version of the CLR, the .Net thread pool is getting smarter about optimizing the throughput by creating and destroying threads as needed.
6) Exception handling : An exception is the signal raised when a condition is detected that was not expected in the normal execution of a program thread. Many agents can detect incorrect conditions and raise exceptions. Program code (or the library code it uses) can throw types derived from System.Exception, the CLR execution engine can raise exceptions, and unmanaged code can raise exceptions as well.
Note : A single thread in one AppDomain can bring down an entire CLR instance by not handling an exception
Interview Questions Can be
- What GC?
- How GC work?
- What is CLR and what are features?
- Difference in CTS and CLS, FCL?
- What is type safety?
- What are Value type and reference type in C#?
- What is heap and Why GC work for only Heap?
Answer : Stack space is mainly used for storing order of method execution and local variables. Stack always stored blocks in LIFO order whereas heap memory used dynamic allocation for allocating and deallocating memory blocks. Memory allocated to the heap lives until one of the following events occurs : Program Terminated. Stack-memory has less storage space as compared to Heap-memory.
- What are strong references and weak references in GC?
Answer : In the context of garbage collection (GC), strong references and weak references are two different types of object references that affect how the GC manages memory and determines the eligibility of objects for garbage collection.
**1. Strong References**:
- By default, most references in .NET are strong references.
- A strong reference to an object keeps it alive and prevents the GC from collecting it as long as the reference is in use.
- As long as an object has one or more strong references pointing to it, it will be considered live and will not be eligible for garbage collection.
- Strong references are what we typically use when assigning objects to variables or passing them as method parameters.
**Example of Strong Reference**:
```csharp
Related links:Maximizing Clothes Rail Capacity: Unveiling the Secrets to Heavy-Duty Hanging
what is combed cotton
Exploring the Distinction: 2 Stage vs. 3 Stage Standing Desks
class MyClass
{
// Class with a property
public string Data { get; set; }
}
// Strong reference to an object of MyClass
MyClass strongReference = new MyClass();
```
In the above example, the variable `strongReference` holds a strong reference to the `MyClass` object, and as long as `strongReference` exists, the object will not be collected by the GC.
**2. Weak References**:
- Weak references are references that do not prevent the GC from collecting an object.
- Unlike strong references, weak references do not keep an object alive. If an object has only weak references pointing to it, it will be eligible for garbage collection.
- Weak references are useful when you want to hold a reference to an object temporarily and allow the GC to collect the object when it is no longer strongly referenced.
**Example of Weak Reference**:
```csharp
class MyClass
{
public string Data { get; set; }
}
// Creating a weak reference to an object of MyClass
WeakReference<MyClass> weakReference = new WeakReference<MyClass>(new MyClass());
```
In this example, the `weakReference` holds a weak reference to the `MyClass` object. If there are no strong references to the object, it can be collected by the GC even if the weak reference is still present.
**Benefits of Weak References**:
- Weak references are commonly used in scenarios where you want to cache or store a reference to an object temporarily but allow the GC to collect it when memory is needed.
- Caching mechanisms and event handling are some scenarios where weak references are useful.
Using strong and weak references appropriately can help in managing memory efficiently and avoiding memory leaks in your application. By understanding these reference types, you can design your code to ensure objects are collected when they are no longer needed, freeing up memory for other parts of the application.
- How GC come to know that object is ready to get collected?
The GC performs a reachability analysis starting from the root objects to find all objects that are still in use and reachable from the root objects. It traverses the object graph by following references from one object to another.
- What are generations in GC?
- How value types get collected v/s reference types?
Answer : Value types are gets stored on the stack and therefore it gets removed from the stack by its pop method when application is done with its use.
Reference types get stored on heap so gets collected by garbage collector.
- Dispose v/s Finalize
Answer : `Dispose` and `Finalize` are two different mechanisms used in C# for managing resources and memory cleanup. Let's understand each of them:
Dispose:
- `Dispose` is a method that belongs to the `IDisposable` interface, which is used to release unmanaged resources held by an object.
- Objects that allocate unmanaged resources (such as file handles, database connections, network sockets, etc.) should implement the `IDisposable` interface and provide a `Dispose` method to release those resources explicitly.
- The primary purpose of `Dispose` is to release resources as soon as they are no longer needed, rather than waiting for the garbage collector to collect the object and finalize it.
- The developer is responsible for calling the `Dispose` method explicitly when the object is no longer needed or when the scope of usage is finished.
- The `using` statement is a convenient way to ensure that `Dispose` is called automatically at the end of a block of code.
**Example using Dispose**:
```csharp
public class MyResource : IDisposable
{
// Unmanaged resource
private IntPtr handle = IntPtr.Zero;
// Dispose method to release the unmanaged resource
public void Dispose()
{
// Release the unmanaged resource
// Cleanup code goes here...
}
}
// Usage with using statement to ensure Dispose is called
using (MyResource resource = new MyResource())
{
// Use the resource
}
// Dispose is called automatically when the object goes out of the 'using' scope
```
**Finalize (Destructor)**:
- `Finalize` is a special method called the "destructor" in C#. It is used for cleaning up unmanaged resources before an object is garbage collected.
- It is recommended to override the `Finalize` method only when you are working with unmanaged resources directly and need to perform cleanup before the object is garbage collected.
- The timing of when the `Finalize` method is called is determined by the garbage collector, and it may not execute immediately after the object becomes unreachable. The GC runs on its own schedule.
- Using `Finalize` to clean up managed resources is not recommended, as managed resources are typically handled by the GC automatically.
Example using Finalize:
public class MyResourceWithFinaliz { // Unmanaged resource private IntPtr handle = IntPtr.Zero; // Finalize method to release the unmanaged resource ~MyResourceWithFinalize() { // Release the unmanaged resource // Cleanup code goes here... } }
Summary:
- Use `Dispose` when working with unmanaged resources to explicitly release them as soon as they are no longer needed.
- Use `Finalize` (destructor) when dealing with unmanaged resources directly and require cleanup before the object is garbage collected. Avoid using it for managing managed resources, as the GC handles them automatically.
- How to manage Unmanaged resources?
- Does GC work similar for Web Application and windows application? Is there any difference?
Answer : No, There is difference.
GC works in “Workstation Mode” for windows application , which can be can be concurrent or non-concurrent. Concurrent garbage collection enables managed threads to continue operations during a garbage collection.
For Web application it works in “Server garbage collection” mode, which is intended for server applications that need high throughput and scalability. Server garbage collection can be non-concurrent or background.
- 9. How to Force Garbage Collection?
Answer : GC.Collect();
I hope you enjoyed this content and got so much info about these components. Thanks for read and share me your feedback through your valuable comments.
What Are CTS And CLS In .NET
What are CTS,CLS , FCL , BCL and CLR in .NET Framework?
210
0
0
Comments
All Comments (0)