What is the role of C#?
Sample answer:
The role of C# as a programming language is to precisely define a set of operations that a computer can perform to complete a task. It’s used to create desktop apps, mobile apps, web apps, websites, and web services.
2. What is meant by object-oriented programming?
Sample answer:
Object-oriented programming (OOP) is an approach to programming where software is primarily designed by using objects (essentially data) that interact with each other.
When different pieces of data are put together, they come to form the software as a whole. OOP is an alternative to functional or procedural programming and it’s also the approach used by C#.
3. What is the difference between managed and unmanaged code?
Sample answer:
Managed code is executed by the Common Language Runtime (CLR) of the .NET Framework, whereas unmanaged code is executed by the Operating System (OS).
CLR offers inbuilt security to managed code, whereas it’s the developer’s responsibility to write safe and secure code with unmanaged code.
4. How is C# different from C?
Sample answer:
The most significant difference between C# and its predecessor, C, is that C# is an object-oriented programming language, whereas C is a procedural programming language.
Some other differences include:
- C is best suited for hardware apps and system programming, whereas C# is used for desktop and mobile apps as well as web services
- C draws on just 32 different keywords, whereas C# has 87
- C places greater emphasis on functions, whereas C# is more oriented to design
5. What is an object in C#?
Sample answer:
An object is a real-world entity and in C# it’s a single instance of a class. For example, if you had a class of ‘dogs’, ‘labradors’, ‘bulldogs’, and ‘golden retrievers’ would all be objects.
6. What is a class in C#?
Sample answer:
In C#, a class is a user-defined blueprint from which objects are created. It brings various types of data together to form a single unit.
7. What is a method in C#?
Sample answer:
In C#, a method is a code block that contains a series of statements used to perform particular operations. Methods must be declared within a class or a structure. They help save time by reusing code.
8. What is meant by structure in C#?
Sample answer:
In C#, a structure is a composite type of data consisting of various data types, including methods, fields, constructors, constants, properties, indexers, operators, and even other structures.
A structure helps bring various data types together under a single unit. In this way, they are similar to classes. However, while classes are reference types, structures are value types.
9. How is code compiled in C#?
Sample answer:
When a project is developed, C# source code is compiled into Intermediate Language (IL). IL is a set of instructions that produces a machine code for execution on the machine processor.
In four steps, code moves from the preprocessor to the compiler, to the assembler, and, lastly, to the linker.
10. What is file handling in C#?
Sample answer:
File handling is the process of saving information to the disk for external storage. The saved file contains bytes of data and is available for retrieval at a later date.
11. What is the purpose of control statements in C#?
Sample answer:
Control statements are used to control the actions a program takes; this is sometimes referred to as the flow of execution. Common actions in C# include calling methods, assigning values, declaring variables, and looping through collections.
12. What is meant by garbage collection in C#?
Sample answer:
In C#, garbage collection is the process of managing memory in an application. The garbage collector automatically disposes of memory that is no longer used to make memory available for new allocations.
13. What is a constructor in C#?
Sample answer:
In C#, a constructor is a type of method that forms a part of a class. The main purpose of a constructor is to initialize the fields of a class. They are invoked automatically when a new class object is created.
14. What is a destructor in C#?
Sample answer:
In C#, a destructor is a type of method that forms a part of a class. The main purpose of a destructor is to destroy instances of a class when they are no longer needed in order to free up memory. Destructors are also referred to as finalizers.
15. What is an array in C#?
Sample answer:
In C#, an array is a collection of data that stores a fixed number of values of the same data type. Arrays can be retrieved easily for the developer’s reference.
16. What is a constant in C#?
Sample answer:
Constants are fixed values that cannot be altered during the lifetime of the program. For example, the constant ‘Months’ is always 12 and cannot be changed.
17. What is an indexer in C#?
Sample answer:
In C#, indexers are used to index instances of a class or structure. The indexed values can then be easily accessed like an array, but without explicitly specifying a type or instance member.
An indexer is a special type of property that allows a class or a structure to be accessed like an array for its internal collection. C# allows us to define custom indexers, generic indexers, and also overload indexers. An indexer can be defined the same way as property with this keyword and square brackets [].
18. What are the different types of classes in C#?
Sample answer:
There are generally considered to be four types of classes in C#. These include:
- Abstract classes: These provide a common definition for a base class that other classes can be derived from
- Static classes: These contain static items that can only interact with other static items
- Partial classes: These are portions of a class that a compiler can combine to form a complete class
- Sealed classes: These cannot be inherited by any class but can be instantiated
19. What is the difference between fields and properties in C#?
Sample answer:
A field is a member of a class or an object of any type that represents a location for storing a value, whereas a property is a class member that provides a mechanism to read, write, and compute the value of a private field.
20. What are circular references in C#?
Sample answer:
In C#, circular references occur when two or more interdependent resources refer back to each other, either directly or indirectly, resulting in a closed loop or lock condition. This situation makes the resource unusable.
21. What is meant by object pooling in C#?
Sample answer:
Object pooling is a software creational design pattern that recycles objects rather than recreating them. It does that by holding selected objects in a pool ready for use when they are requested by an application.
This process helps to improve performance by minimizing unnecessary object creation.
22. What are the different types of control statements in C#?
Sample answer:
There are generally considered to be three main types of control statements, each serving different purposes. These include:
- Selection statements, which enable you to branch to different sections of code
- Iteration statements, which enable you to loop through connections or perform the same series of operations repeatedly until a specified condition is met
- Jump statements, which enable control of flow to be shifted to another section of code
23. What is method overloading/overriding in C#?
Sample answer:
Overloading:
In C#, method overloading is the process of assigning different signatures or arguments to two or more methods bearing the same name. It’s an example of polymorphism in object-oriented programming.
Method overloading improves the readability of the program by reducing the number of names associated with a specific action.
Overriding :
Method Overriding is a type of polymorphism. It has several names like “Run Time Polymorphism” or “Dynamic Polymorphism” and sometime it is called “Late Binding”.
Method Overriding means having two methods with same name and same signatures [parameters], one should be in the base class and other method should be in a derived class [child class]. You can override the functionality of a base class method to create a same name method with same signature in a derived class. You can achieve method overriding using inheritance. Virtual and Override keywords are used to achieve method overriding.
24. What are boxing and unboxing in C#?
Sample answer:
Boxing:
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
Unboxing :
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
Difference between a Value Type and a Reference Type
The Types in .NET Framework are either treated by Value Type or by Reference Type. A Value Type holds the data within its own memory allocation and a Reference Type contains a pointer to another memory location that holds the real data. Reference Type variables are stored in the heap while Value Type variables are stored in the stack.
Value Type:
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. Value types can be created at compile time and Stored in stack memory, because of this, Garbage collector can’t access the stack.
Reference Type:
Reference Types are used by a reference which holds a reference (address) to the object but not the object itself. Because reference types represent the address of the variable rather than the data itself, assigning a reference variable to another 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. Reference Type variables are stored in a different area of memory called the heap. This means that when a reference type variable is no longer used, it can be marked for garbage collection. Examples of reference types are Classes, Objects, Arrays, Indexers, Interfaces etc.
In the above code the space required for the 20 integers that make up the array is allocated on the heap.
Stack and Heap
Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer’s RAM. More about…. Differences between Stack and Heap
Difference between Stack and Heap Memory in C#
Category | Stack Memory | Heap Memory |
What is Stack & Heap? | It is an array of memory. It is a LIFO (Last In First Out) data structure. In it data can be added to and deleted only from the top of it. | It is an area of memory where chunks are allocated to store certain kinds of data objects.(FIFO) In it data can be stored and removed in any order. |
How Memory is Manages? | ||
Practical Scenario | Value of variable storing in stack | Value of variable storing in heap |
What goes on Stack & Heap? | “Things” declared with the following list of type declarations are Value Types (because they are from System.ValueType): bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct, uint, ulong, ushort | “Things” declared with following list of type declarations are Reference Types (and inherit from System.Object… except, of course, for object which is the System.Object object): class, interface, delegate, object, string |
Memory Allocation | Memory allocation is Static | Memory allocation is Dynamic |
How is it Stored? | It is stored Directly | It is stored indirectly |
Is Variable Resized? | Variables can’t be Resized | Variables can be Resized |
Access Speed | Its access is fast | Its access is Slow |
How is Block Allocated? | Its block allocation is reserved in LIFO. Most recently reserved block is always the next block to be freed. | Its block allocation is free and done at any time |
Visibility or Accessibility | It can be visible/accessible only to the Owner Thread | It can be visible/accessible to all the threads |
In Recursion Calls? | In recursion calls memory filled up quickly | In recursion calls memory filled up slowly |
Used By? | It can be used by one thread of execution | It can be used by all the parts of the application |
StackOverflowException | .NET Runtime throws exception “StackOverflowException” when stack space is exhausted | – |
When wiped off? | Local variables get wiped off once they lose the scope | – |
Contains | It contains values for Integral Types, Primitive Types and References to the Objects | – |
Garbage Collector | – | It is a special thread created by .NET runtime to monitor allocations of heap space. It only collects heap memory since objects are only created in heap |
Class and Struct
Class is pass-by-reference and Struct is pass-by-copy, it means that, Class is a reference type and its object is created on the heap memory where as structure is a value type and its object is created on the stack memory.
S.N | Struct | Classes |
1 | Structs are value types, allocated either on the stack or inline in containing types. | Classes are reference types, allocated on the heap and garbage-collected. |
2 | Allocations and de-allocations of value types are in general cheaper than allocations and de-allocations of reference types. | Assignments of large reference types are cheaper than assignments of large value types. |
3 | In structs, each variable contains its own copy of the data (except in the case of the ref and out parameter variables), and an operation on one variable does not affect another variable. | In classes, two variables can contain the reference of the same object and any operation on one variable can affect another variable. |
Dynamic Data Type
The dynamic keyword brings exciting new features to C# 4. Dynamic Type means that you can store any type of value in the dynamic data type variable because type checking for dynamic types of variables takes place at run-time.
- in most of the cases, the dynamic type behaves like object types.
- You can get the actual type of the dynamic variable at runtime by using GetType() method. The dynamic type changes its type at the run time based on the value present on the right-hand side.
- When you assign a class object to the dynamic type, then the compiler does not check for the right method and property name of the dynamic type which holds the custom class object.
- You can also pass a dynamic type parameter in the method so that the method can accept any type of parameter at run time.
- The compiler will throw an exception at runtime if the methods and the properties are not compatible.
- It does not support the intellisense in visual studio.
- The compiler does not throw an error on dynamic type at compile time if there is no type checking for dynamic type.
Var | Dynamic |
It is introduced in C# 3.0. | It is introduced in C# 4.0 |
The variables are declared using var keyword are statically typed. | The variables are declared using dynamic keyword are dynamically typed. |
The type of the variable is decided by the compiler at compile time. | The type of the variable is decided by the compiler at run time. |
The variable of this type should be initialized at the time of declaration. So that the compiler will decide the type of the variable according to the value it initialized. | The variable of this type need not be initialized at the time of declaration. Because the compiler does not know the type of the variable at compile time. |
If the variable does not initialized it throw an error. | If the variable does not initialized it will not throw an error. |
It support intelliSense in visual studio. | It does not support intelliSense in visual studio |
var myvalue = 10; // statement 1 myvalue = “GeeksforGeeks”; // statement 2 Here the compiler will throw an error because the compiler has already decided the type of the myvalue variable using statement 1 that is an integer type. When you try to assign a string to myvalue variable, then the compiler will give an error because it violating safety rule type. | dynamic myvalue = 10; // statement 1 myvalue = “GeeksforGeeks”; // statement 2 Here, the compiler will not throw an error though the type of the myvalue is an integer. When you assign a string to myvalue it recreates the type of the myvalue and accepts string without any error. |
It cannot be used for properties or returning values from the function. It can only used as a local variable in function. | It can be used for properties or returning values from the function. |
25. What is the difference between ref and out keywords in C#?
Sample answer:
The <ref> and <out> keywords are similar in that they are both used to pass arguments in a reference or function. However, there is a subtle difference:
- With <ref> keywords, the value is already set, meaning the method can read and modify it
- With <out> keywords, the value isn’t set and can’t be read by the method until it is set, meaning the method must set it before it can be returned
good read