C# Coding questions
Q #1) What is Managed and Unmanaged code?
Answer: Managed code is a code that is executed by CLR (Common Language Runtime) i.e all application code is based on .Net platform. It is considered as managed because of the .Net framework which internally uses the garbage collector to clear up the unused memory.
Unmanaged code is any code that is executed by application runtime of any other framework apart from .Net. The application runtime will take care of memory, security and other performance operations.
Q #2) What is an Interface?
Answer: Interface is a class with no implementation. The only thing that it contains is the declaration of methods, properties, and events.
Q #3) What are the different types of classes in C#?
Answer: The different types of class in C# are:
- Partial class: It allows its members to be divided or shared with multiple .cs files. It is denoted by the keyword Partial.
- Sealed class: It is a class that cannot be inherited. To access the members of a sealed class, we need to create the object of the class. It is denoted by the keyword Sealed.
- Abstract class: It is a class whose object cannot be instantiated. The class can only be inherited. It should contain at least one method. It is denoted by the keyword abstract.
- Static class: It is a class that does not allow inheritance. The members of the class are also static. It is denoted by the keyword static. This keyword tells the compiler to check for any accidental instances of the static class.
Q #4) Explain code compilation in C#.
Answer: Code compilation in C# includes the following four steps:
- Compiling the source code into Managed code by C# compiler.
- Combining the newly created code into assemblies.
- Loading the Common Language Runtime(CLR).
- Executing the assembly by CLR.
Q #5) What are the differences between a Class and a Struct?
Answer: Given below are the differences between a Class and a Struct:
Class | Struct |
---|---|
Supports Inheritance | Does not support Inheritance |
Class is Pass by reference (reference type) | Struct is Pass by Copy (Value type) |
Members are private by default | Members are public by default |
Good for larger complex objects | Good for Small isolated models |
Can use waste collector for memory management | Cannot use Garbage collector and hence no Memory management |
Q #6) What is the difference between the Virtual method and the Abstract method?
Answer: The Virtual method must always have a default implementation. However, it can be overridden in the derived class, although it is not mandatory. It can be overridden using the override keyword.
An Abstract method does not have an implementation. It resides in the abstract class. It is mandatory that the derived class implements the abstract method. An override keyword is not necessary here though it can be used.
Q #7) Explain Namespaces in C#.
Answer: They are used to organize large code projects. “System” is the most widely used namespace in C#. We can create our own namespace and can also use one namespace in another, which is called Nested Namespaces.
They are denoted by the keyword “namespace”.
Q #8) What is “using” statement in C#?
Answer: “Using” keyword denotes that the particular namespace is being used by the program.
For Example, using System
Here, System is a namespace. The class Console is defined under System. So, we can use the console.writeline (“….”) or readline in our program.
Q #9) How is Exception Handling implemented in C#?
Answer: Exception handling is done using four keywords in C#:
- try: Contains a block of code for which an exception will be checked.
- catch: It is a program that catches an exception with the help of the exception handler.
- finally: It is a block of code written to execute regardless of whether an exception is caught or not.
- Throw: Throws an exception when a problem occurs.
Q #10) What are C# I/O classes? What are the commonly used I/O classes?
Answer: C# has System.IO namespace, consisting of classes that are used to perform various operations on files like creating, deleting, opening, closing, etc.
Some commonly used I/O classes are:
- File – Helps in manipulating a file.
- StreamWriter – Used for writing characters to a stream.
- StreamReader – Used for reading characters to a stream.
- StringWriter – Used for reading a string buffer.
- StringReader – Used for writing a string buffer.
- Path – Used for performing operations related to the path information.
Q #11) What is StreamReader/StreamWriter class?
Answer: StreamReader and StreamWriter are classes of namespace System.IO. They are used when we want to read or write charact90, Reader-based data, respectively.
Some of the members of StreamReader are: Close(), Read(), Readline().
Members of StreamWriter are: Close(), Write(), Writeline().
Class Program1
{
using(StreamReader sr = new StreamReader(“C:\ReadMe.txt”)
{
//----------------code to read-------------------//
}
using(StreamWriter sw = new StreamWriter(“C:\ReadMe.txt”))
{
//-------------code to write-------------------//
}
}
Q #12) What is a Destructor in C#?
Answer: Destructor is used to clean up the memory and free the resources. But in C# this is done by the garbage collector on its own. System.GC.Collect() is called internally for cleaning up. But sometimes it may be necessary to implement destructors manually.
For Example:
~Car()
{
Console.writeline(“….”);
}
Q #13) What is an Abstract Class?
Answer: An Abstract class is a class which is denoted by abstract keyword and can be used only as a Base class. This class should always be inherited. An instance of the class itself cannot be created. If we do not want any program to create an object of a class, then such classes can be made abstract.
Any method in the abstract class does not have implementations in the same class. But they must be implemented in the child class.
For Example:
abstract class AB1
{
Public void Add();
}
class childClass : AB1
{
childClass cs = new childClass ();
int Sum = cs.Add();
}
All the methods in an abstract class are implicitly virtual methods. Hence, the virtual keyword should not be used with any methods in the abstract class.
Q #14) What are Boxing and Unboxing?
Answer: Converting a value type to reference type is called Boxing.
For Example:
int Value1 -= 10;
//————Boxing——————//
object boxedValue = Value1;
Explicit conversion of same reference type (created by boxing) back to value type is called Unboxing.
For Example:
//————UnBoxing——————//
int UnBoxing = int (boxedValue);
Q #15) What is the difference between Continue and Break Statement?
Answer: Break statement breaks the loop. It makes the control of the program to exit the loop. Continue statement makes the control of the program to exit only the current iteration. It does not break the loop.
Q #16) What is the difference between finally, finalize and dispose block?
Answer: finally block is called after the execution of try and catch block. It is used for exception handling. Regardless of whether an exception is caught or not, this block of code will be executed. Usually, this block will have a clean-up code.
finalize method is called just before garbage collection. It is used to perform clean up operations of Unmanaged code. It is automatically called when a given instance is not subsequently called.
Dispose method should be called explicitly to release the unmanaged resources that it holds. The Dispose method can be called directly by client code or by the .NET runtime environment, through the use of the 'using' statement. The using statement ensures that the Dispose method is called automatically when the object goes out of scope.
Unmanaged resources are like streams, database connections, graphics objects and network connections
class Program
{
static void Main(string[] args)
{
using (FileStream fs = new FileStream("test.txt", FileMode.Create))
{
// Use the file stream...
} // The Dispose method is called automatically when the using block ends.
}
}
Q #17) What is an Array? Give the syntax for a single and multi-dimensional array?
Answer: An Array is used to store multiple variables of the same type. It is a collection of variables stored in a contiguous memory location.
For Example:
double[] numbers = new double[10];
int[] score = new int[4] {25,24,23,25};
A single dimensional array is a linear array where the variables are stored in a single row. Above example is a single dimensional array.
Arrays can have more than one dimension. Multidimensional arrays are also called rectangular arrays.
For Example,
int[,] numbers = new int[3,2] { {1,2} ,{2,3},{3,4} };
Q #18) What is a Jagged Array?
Answer: A Jagged array is an array whose elements are arrays. It is also called as the array of arrays. It can be either single or multiple dimensions.
int[] jaggedArray = new int[4][];
Q #19) What is a String? What are the properties of a String Class?
Answer: A String is a collection of char objects. We can also declare string variables in c#.
string name = “C# Questions”;
A string class in C# represents a string. The properties of the string class are:
- Chars get the Char object in the current String.
- Length gets the number of objects in the current String.
Q #20) What is an Escape Sequence? Name some String escape sequences in C#.
Answer: An Escape sequence is denoted by a backslash (\). The backslash indicates that the character that follows it should be interpreted literally or it is a special character. An escape sequence is considered as a single character.
String escape sequences are as follows:
- \n – Newline character
- \b – Backspace
- \\ – Backslash
- \’ – Single quote
- \’’ – Double Quote
Q #21) What are Regular expressions? Search a string using regular expressions?
Answer: Regular expression is a template to match a set of input. The pattern can consist of operators, constructs or character literals. Regex is used for string parsing and replacing the character string.
For Example:
* matches the preceding character zero or more times. So, a*b regex is equivalent to b, ab, aab, aaab and so on.
Searching a string using Regex:
static void Main(string[] args)
{
string[] languages = { "C#", "Python", "Java" };
foreach(string s in languages)
{
if(System.Text.RegularExpressions.Regex.IsMatch(s,"Python"))
{
Console.WriteLine("Match found");
}
}
}
The above example searches for “Python” against the set of inputs from the languages array. It uses Regex.IsMatch which returns true in case if the pattern is found in the input. The pattern can be any regular expression representing the input that we want to match.
Q #22) What is Parsing? How to Parse a Date Time String?
Answer: Parsing converts a string into another data type.
For Example:
string text = “500”;
int num = int.Parse(text);
500 is an integer. So, the Parse method converts the string 500
into its own base type, i.e int.
Follow the same method to convert a DateTime string.
string dateTime = “Jan 1, 2018”;
DateTime parsedValue = DateTime.Parse(dateTime);
Q #23) Difference Between C# Task and Thread ?
Answer:
Task:
- Task is basically used to implement Asynchronous Programming i.e. executing operations asynchronously. Task is more abstract then threads. It is always advised to use tasks instead of thread, as it is created on the thread pool which has already system created threads to improve the performance.
- The task can return a result.
- You can easily build chains of tasks.
- Task supports cancellation through the use of cancellation tokens.
- Exception can be easily caught if we are using tasks.
- A task is by default a background task. You cannot have a foreground task.
Thread:
- A Thread is a small set of executable instructions.
- Thread Does Not Return Results
- No Continuation in Thread
- We cannot cancel a thread while it is in middle of the operation.
- While using thread if we get the exception in the long running method it is not possible to catch the exception in the parent function
- Thread can be background or foreground.
Q #24) Yield C#??
Answer:
The yield keyword is use to do custom stateful iteration over a collection. When using the "yield return" statement inside an iterator, you need not create a temporary collection to store data before it returned. You can take advantage of the yield return statement to return each element in the collection one at a time, and you can use the "yield return" statement with iterators in a method or a get accessor.
The yield return statement returns one element at a time. The return type of yield keyword is either IEnumerable or IEnumerator.
The yield break statement is used to end the iteration.
yield return is used with enumerators. On each call of yield statement, control is returned to the caller but it ensures that the callee's state is maintained. Due to this, when the caller enumerates the next element, it continues execution in the callee method from statement immediately after the yield statement.
Q #25) What is a Delegate? Explain.
Answer: A Delegate is a variable that holds the reference to a method. Hence it is a function pointer or reference type. All Delegates are derived from System. Delegate namespace. Both Delegate and the method that it refers to can have the same signature.
The delegate provides a kind of encapsulation to the reference method, which will internally get called when a delegate is called.
// C# program to illustrate the use of Delegates using System; namespace GeeksForGeeks { class Program { public delegate void addnum(int a, int b); public delegate void subnum(int a, int b); // method "sum" public void sum(int a, int b) { Console.WriteLine("(100 + 40) = {0}", a + b); } // method "subtract" public void subtract(int a, int b) { Console.WriteLine("(100 - 60) = {0}", a - b); } // Main Method public static void Main(String []args) { // creating object "obj" of class "Program" Program obj = new Program(); addnum del_obj1 = new addnum(obj.sum); subnum del_obj2 = new subnum(obj.subtract); // pass the values to the methods by delegate object del_obj1(100, 40); del_obj2(100, 60); // These can be written as using "Invoke" method // del_obj1.Invoke(100, 40); // del_obj2.Invoke(100, 60); } } } // Output (100 + 40) = 140 (100 - 60) = 40
Q #26) What are Events?
Answer: Events are user actions that generate notifications to the application to which it must respond. The user actions can be mouse movements, keypress and so on.
Programmatically, a class that raises an event is called a publisher and a class which responds/receives the event is called a subscriber. Event should have at least one subscriber else that event is never raised.
Delegates are used to declare Events.
Public delegate void PrintNumbers();
Event PrintNumbers myEvent;
Q #27) How to use Delegates with Events?
Answer: Delegates are used to raise events and handle them. Always a delegate needs to be declared first and then the Events are declared.
Let us see an example:
Consider a class called Patient. Consider two other classes, Insurance, and Bank which requires Death information of the Patient from patient class. Here, Insurance and Bank are the subscribers and the Patient class becomes the Publisher. It triggers the death event and the other two classes should receive the event.
namespace ConsoleApp2
{
public class Patient
{
public delegate void deathInfo();//Declaring a Delegate//
public event deathInfo deathDateEvt;//Declaring the event//
public void Death()
{
deathDateEvt.Invoke();
}
}
public class Insurance
{
Patient myPat;
public Insurance(Patient pat)
{
myPat = pat;
myPat.deathDateEvt += GetDeathDetails;
}
void GetDeathDetails()
{
Console.WriteLine("Get Patient Death Info");
}
}
public class Bank
{
Patient myPat;
public Bank(Patient pat)
{
myPat = pat;
myPat.deathDateEvt += GetPatInfo;
}
void GetPatInfo ()
{
Console.WriteLine("Get Patient Info");
}
}
public class Program
{
// Main Method
public static void Main(String []args)
{
Patient myPat = new Patient();
Insurance ins = new Insurance(myPat);
Bank bank = new Bank(myPat);
myPat.Death();
}
}
}
// Output
Get Patient Death Info
Get Patient Info
Q #28) What are the different types of Delegates?
Answer: Different types of Delegates are:
- Single Delegate: A delegate that can call a single method.
- Multicast Delegate: A delegate that can call multiple methods. + and – operators are used to subscribe and unsubscribe respectively.
- Generic Delegate: It does not require an instance of the delegate to be defined. It is of three types, Action, Funcs and Predicate.
- Action– In the above example of delegates and events, we can replace the definition of delegate and event using Action keyword. The Action delegate defines a method that can be called on arguments but does not return a result Action implicitly refers to a delegate.
- Action<int, string> myDel is same as delegate void myDel(int a, string b);
- Func– A Func delegate defines a method that can be called on arguments and returns a result.
- Func <int, string, bool> myDel is same as delegate bool myDel(int a, string b);
- Predicate– Defines a method that can be called on arguments and always returns the bool.
- Predicate<string> myDel is same as delegate bool myDel(string s);
using System;
namespace GenericDelegatesDemo
{
public class GenericDelegates
{
public delegate double AddNumber1Delegate(int no1, float no2, double no3);
public delegate void AddNumber2Delegate(int no1, float no2, double no3);
public delegate bool CheckLengthDelegate(string name);
static void Main(string[] args)
{
AddNumber1Delegate obj1 = new AddNumber1Delegate(AddNumber1);
double Result = obj1.Invoke(100, 125.45f, 456.789);
Console.WriteLine(Result);
AddNumber2Delegate obj2 = new AddNumber2Delegate(AddNumber2);
obj2.Invoke(50, 255.45f, 123.456);
CheckLengthDelegate obj3 = new CheckLengthDelegate(CheckLength);
bool Status = obj3.Invoke("Pranaya");
Console.WriteLine(Status);
Console.ReadKey();
}
public static double AddNumber1(int no1, float no2, double no3)
{
return no1 + no2 + no3;
}
public static void AddNumber2(int no1, float no2, double no3)
{
Console.WriteLine(no1 + no2 + no3);
}
public static bool CheckLength(string name)
{
if (name.Length > 5)
return true;
return false;
}
}
}
using System;
namespace GenericDelegateDemo
{
public class GenericDelegates
{
static void Main(string[] args)
{
Func<int, float, double, double> obj1 = new Func<int, float, double, double>(AddNumber1);
double Result = obj1.Invoke(100, 125.45f, 456.789);
Console.WriteLine(Result);
Action<int, float, double> obj2 = new Action<int, float, double>(AddNumber2);
obj2.Invoke(50, 255.45f, 123.456);
Predicate<string> obj3 = new Predicate<string>(CheckLength);
bool Status = obj3.Invoke("Pranaya");
Console.WriteLine(Status);
Console.ReadKey();
}
public static double AddNumber1(int no1, float no2, double no3)
{
return no1 + no2 + no3;
}
public static void AddNumber2(int no1, float no2, double no3)
{
Console.WriteLine(no1 + no2 + no3);
}
public static bool CheckLength(string name)
{
if (name.Length > 5)
return true;
return false;
}
}
}
Q #29) What do Multicast Delegates mean?
Answer: A Delegate that points to more than one method is called a Multicast Delegate. Multicasting is achieved by using + and += operator.
// C# program to illustrate the Multicasting of Delegates
using System;
class rectangle
{
// declaring delegate
public delegate void rectDelegate(double height, double width);
public void area(double height, double width)
{
Console.WriteLine("Area is: {0}", (width * height));
}
public void perimeter(double height, double width)
{
Console.WriteLine("Perimeter is: {0} ", 2 * (width + height));
}
public static void Main(String []args)
{
rectangle rect = new rectangle();
// creating delegate object, name as "rectdele" and pass the method as parameter by
// class object "rect"
rectDelegate rectdele = new rectDelegate(rect.area);
// also can be written as
// rectDelegate rectdele = rect.area;
// call 2nd method "perimeter" Multicasting
rectdele += rect.perimeter;
// pass the values in two method
// by using "Invoke" method
rectdele.Invoke(6.3, 4.2);
Console.WriteLine();
rectdele.Invoke(16.3, 10.3);
}
}
//Output
Area is: 26.46
Perimeter is: 21
Area is: 167.89
Perimeter is: 53.2
Q #30) Explain Publishers and Subscribers in Events.
Answer: Publisher is a class responsible for publishing a message of different types of other classes. The message is nothing but Event as discussed in the above questions.
From the Example in Q #27, Class Patient is the Publisher class. It is generating an Event deathEvent, which is received by the other classes.
Subscribers capture the message of the type that it is interested in. Again, from the Example of Q#27, Class Insurance and Bank are Subscribers. They are interested in event deathEvent of type void.
Q #31) What are Synchronous and Asynchronous operations?
Answer: Synchronization is a way to create a thread-safe code where only one thread can access the resource at any given time. The asynchronous call waits for the method to complete before continuing with the program flow.
Synchronous programming badly affects the UI operations when the user tries to perform time-consuming operations since only one thread will be used. In Asynchronous operation, the method call will immediately return so that the program can perform other operations while the called method completes its work in certain situations.
In C#, Async and Await keywords are used to achieve asynchronous programming.
Q #32) What is Reflection in C#?
Answer: Reflection is the ability of a code to access the metadata of the assembly during runtime. A program reflects upon itself and uses the metadata to inform the user or modify its behavior. Metadata refers to information about objects, methods.
The namespace System.Reflection contains methods and classes that manage the information of all the loaded types and methods. It is mainly used for windows applications, For Example, to view the properties of a button in a windows form.
The MemberInfo object of the class reflection is used to discover the attributes associated with a class.
Reflection is implemented in two steps, first, we get the type of the object, and then we use the type to identify members such as methods and properties.
To get type of a class, we can simply use,
Type mytype = myClass.GetType();
Once we have a type of class, the other information about the class can be easily accessed.
System.Reflection.MemberInfo Info = mytype.GetMethod(“AddNumbers”);
Above statement tries to find a method with name AddNumbers in the class myClass.
Q #33) What is a Generic Class?
Answer: Generics or Generic class is used to create classes or objects which do not have any specific data type. The data type can be assigned during runtime, i.e when it is used in the program.
For Example:
So, from the above code, we see 2 compare methods initially, to compare string and int.
In case of other data type parameter comparisons, instead of creating many overloaded methods, we can create a generic class and pass a substitute data type, i.e T. So, T acts as a datatype until it is used specifically in the Main() method.
Q #34) Explain Get and Set Accessor properties?
Answer: Get and Set are called Accessors. These are made use by Properties. The property provides a mechanism to read, write the value of a private field. For accessing that private field, these accessors are used.
Get Property is used to return the value of a property
Set Property accessor is used to set the value.
The usage of get and set is as below:
Q #35) What is a Thread? What is Multithreading?
Answer: A Thread is a set of instructions that can be executed, which will enable our program to perform concurrent processing. Concurrent processing helps us do more than one operation at a time. By default, C# has only one thread. But the other threads can be created to execute the code in parallel with the original thread.
Thread has a life cycle. It starts whenever a thread class is created and is terminated after the execution. System.Threading is the namespace which needs to be included to create threads and use its members.
Threads are created by extending the Thread Class. Start() method is used to begin thread execution.
//CallThread is the target method//
ThreadStart methodThread = new ThreadStart(CallThread);
Thread childThread = new Thread(methodThread);
childThread.Start();
C# can execute more than one task at a time. This is done by handling different processes by different threads. This is called MultiThreading.
There are several thread methods that are used to handle multi-threaded operations:
Start, Sleep, Abort, Suspend, Resume and Join.
Most of these methods are self-explanatory.
Q #36) What are Async and Await?
Answer: Async and Await keywords are used to create asynchronous methods in C.
Asynchronous programming means that the process runs independently of main or other processes.
Usage of Async and Await is as shown below:
- Async keyword is used for the method declaration.
- The count is of a task of type int which calls the method CalculateCount().
- Calculatecount() starts execution and calculates something.
- Independent work is done on my thread and then await count statement is reached.
- If the Calculatecount is not finished, myMethod will return to its calling method, thus the main thread doesn’t get blocked.
- If the Calculatecount is already finished, then we have the result available when the control reaches await count. So the next step will continue in the same thread. However, it is not the situation in the above case where the Delay of 1 second is involved.
Q #37) What is a Deadlock?
Answer: A Deadlock is a situation where a process is not able to complete its execution because two or more processes are waiting for each other to finish. This usually occurs in multi-threading.
Here a shared resource is being held by a process and another process is waiting for the first process to release it and the thread holding the locked item is waiting for another process to complete.
Consider the below Example:
- Perform tasks accesses objB and waits for 1 second.
- Meanwhile, PerformtaskB tries to access ObjA.
- After 1 second, PeformtaskA tries to access ObjA which is locked by PerformtaskB.
- PerformtaskB tries to access ObjB which is locked by PerformtaskA.
This creates Deadlock.
Q #38) Explain Lock, Monitors, and Mutex Object in Threading.
Answer: Lock keyword ensures that only one thread can enter a particular section of the code at any given time. In the above Example, lock(ObjA) means the lock is placed on ObjA until this process releases it, no other thread can access ObjA.
Mutex is also like a lock but it can work across multiple processes at a time. WaitOne() is used to lock and ReleaseMutex() is used to release the lock. But Mutex is slower than lock as it takes time to acquire and release it.
Monitor.Enter and Monitor.Exit implements lock internally. a lock is a shortcut for Monitors. lock(objA) internally calls.
Monitor.Enter(ObjA);
try
{
}
Finally
{
Monitor.Exit(ObjA));
}
Q #39) What is a Race Condition?
Ans: A race condition is a type of software error that can occur in multithreaded or concurrent programs where two or more threads or processes access and modify shared data simultaneously, leading to unpredictable and incorrect behavior. For example, if two threads try to modify the same variable at the same time, the result will depend on which thread gets to access the variable first, and the other thread may end up overwriting the changes made by the first thread.
Race conditions can lead to a range of problems, including data corruption, deadlock, and unexpected program behavior. To avoid race conditions, developers can use synchronization techniques such as locks, semaphores, and monitors to ensure that only one thread can access shared data at a time, or they can use atomic operations to make sure that certain operations are executed as a single, indivisible unit.
If we have two threads, T1 and T2, and they are trying to access a shared resource called X. And if both the threads try to write a value to X, the last value written to X will be saved.
Q #40) What is Thread Pooling?
Ans: Thread pool is a collection of threads. These threads can be used to perform tasks without disturbing the primary thread. Once the thread completes the task, the thread returns to the pool. Every thread in the pool has a specific given task. The thread returns to the pool and waits for the next assignment when the given task is completed.
Usually, the thread pool is required when we have number of threads are created to perform a number of tasks, in this organized in a queue. Typically, we have more tasks than threads. As soon as a thread completes its task, it will request the next task from the queue until all tasks have been completed. The thread can then terminate, or sleep until there are new tasks available..
System.Threading.ThreadPool namespace has classes that manage the threads in the pool and its operations.
System.Threading.ThreadPool.QueueUserWorkItem(
new System.Threading.WaitCallback(SomeTask));
The above line queues a task. SomeTask methods should have a parameter of type Object.
Q #41) What is Serialization?
Answer: Serialization is a process of converting code to its binary format. Once it is converted to bytes, it can be easily stored and written to a disk or any such storage devices. Serializations are mainly useful when we do not want to lose the original form of the code and it can be retrieved anytime in the future.
Any class which is marked with the attribute [Serializable] will be converted to its binary form.
The reverse process of getting the C# code back from the binary form is called Deserialization.
To Serialize an object we need the object to be serialized, a stream that can contain the serialized object and namespace System.Runtime.Serialization can contain classes for serialization.
Q #42) What are the types of Serialization?
Answer: The different types of Serialization are:
- XML serialization – It serializes all the public properties to the XML document. Since the data is in XML format, it can be easily read and manipulated in various formats. The classes reside in System.sml.Serialization.
- SOAP – Classes reside in System.Runtime.Serialization. Similar to XML but produces a complete SOAP compliant envelope that can be used by any system that understands SOAP.
- Binary Serialization – Allows any code to be converted to its binary form. Can serialize and restore public and non-public properties. It is faster and occupies less space.
Q #43) What is an XSD file?
Answer: An XSD file stands for XML Schema Definition. It gives a structure for the XML file. It means it decides the elements that the XML should have and in what order and what properties should be present. Without an XSD file associated with XML, the XML can have any tags, any attributes, and any elements.
Xsd.exe tool converts the files to the XSD format. During Serialization of C# code, the classes are converted to XSD compliant format by xsd.exe.
Q #44) What is the difference between an abstract class and an interface?
Answer: Let’s dig into the differences between an abstract class and an interface:
- Abstract classes are classes that cannot be instantiated ie. that cannot create an object. The interface is like an abstract class because all the methods inside the interface are abstract methods.
- Surprisingly, abstract classes can have both abstract and non-abstract methods but all the methods of an interface are abstract methods.
- Since abstract classes can have both abstract and non-abstract methods, we need to use the Abstract keyword to declare abstract methods. But in the interface, there is no such need.
Ex. Abstract class:
public abstract class Shape
{
public abstract void draw();
}
Interface:
public interface Paintable
{
void paint();
}
Q #45) What are the differences between ref and out keywords?
Answer: C# ref keywords pass arguments by reference and not value. To use the ‘ref’ keyword, you need to explicitly mention ‘ref’.
void Method(ref int refArgument)
{
refArgument = refArgument + 10;
}
int number = 1;
Method(ref number);
Console.WriteLine(number);
// Output: 11
C# out keywords pass arguments within methods and functions. ‘out’ keyword is used to pass arguments in a method as a reference to return multiple values. Although it is the same as the ref keyword, the ref keyword needs to be initialised before it is passed. Here, The out and ref keywords are useful when we want to return a value in the same variables that are passed as an argument.
public static string GetNextFeature(ref int id)
{
string returnText = "Next-" + id.ToString();
id += 1;
return returnText;
}
public static string GetNextFeature(out int id)
{
id = 1;
string returnText = "Next-" + id.ToString();
return returnText;
}
Q #46) What are extension methods in C#?
Answer: Extension methods help to add new methods to the existing ones. The methods that are added are static. At times, when you want to add methods to an existing class but don’t perceive the right to modify that class or don’t hold the rights, you can create a new static class containing the new methods. Once the extended methods are declared, bind this class with the existing one and see the methods will be added to the existing one.
// C# program to illustrate the concept
// of the extension methods
using System;
namespace ExtensionMethod {
static class NewMethodClass {
// Method 4
public static void M4(this Scaler s)
{
Console.WriteLine("Method Name: M4");
}
// Method 5
public static void M5(this Scaler s, string str)
{
Console.WriteLine(str);
}
}
// Now we create a new class in which
// Scaler class access all the five methods
public class IB {
// Main Method
public static void Main(string[] args)
{
Scaler s = new Scaler();
s.M1();
s.M2();
s.M3();
s.M4();
s.M5("Method Name: M5");
}
}
}
Output: Method Name: M1 Method Name: M2 Method Name: M3 Method Name: M4 Method Name: M5
Q #47) What is the difference between an Array and ArrayList in C#?
Answer: An array is a collection of similar variables clubbed together under one common name. While ArrayList is a collection of objects that can be indexed individually.
With ArrayList you can access a number of features like dynamic memory allocation, adding, searching, and sorting items in the ArrayList.
- When declaring an array the size of the items is fixed therefore, the memory allocation is fixed. But with ArrayList, it can be increased or decreased dynamically.
- Array belongs to system.array namespace while ArrayList belongs to the system.collection namespace.
- All items in an array are of the same datatype while all the items in an ArrayList can be of the same or different data types.
- While arrays cannot accept null, ArrayList can accept null values. For ex.:
// C# program to illustrate the ArrayList
using System;
using System.Collections;
class IB
{
// Main Method
public static void Main(string[] args)
{
// Create a list of strings
ArrayList al = new ArrayList();
al.Add("Bruno");
al.Add("Husky");
al.Add(10);
al.Add(10.10);
// Iterate list element using foreach loop
foreach(var names in al)
{
Console.WriteLine(names);
}
}
}
Q #48) What is inheritance? Does C# support multiple inheritance?
Answer: Inheritance means acquiring some of the properties from a master class. Here, class C can inherit properties from Class A and Class B. Here is an example of inheritance:
// C# program to illustrate
// multiple class inheritance
using System;
using System.Collections;
// Parent class 1
class Scaler
{
// Providing the implementation
// of features() method
public void features()
{
// Creating ArrayList
ArrayList My_features= new ArrayList();
// Adding elements in the
// My_features ArrayList
My_features.Add("Abstraction");
My_features.Add("Encapsulation");
My_features.Add("Inheritance");
Console.WriteLine("Features provided by OOPS:");
foreach(var elements in My_features)
{
Console.WriteLine(elements);
}
}
}
// Parent class 2
class Scaler2 :Scaler
{
// Providing the implementation
// of courses() method
public void languages()
{
// Creating ArrayList
ArrayList My_features = new ArrayList();
// Adding elements in the
// My_features ArrayList
My_features.Add("C++");
My_features.Add("C#");
My_features.Add("JScript");
Console.WriteLine("\nLanguages that use OOPS concepts:");
foreach(var elements in My_features)
{
Console.WriteLine(elements);
}
}
}
// Child class
class ScalertoScaler : Scaler2
{
}
public class Scaler1
{
// Main method
static public void Main()
{
// Creating object of ScalertoScaler class
ScalertoScaler obj = new ScalertoScaler();
obj.features();
obj.languages();
}
}
Also, C# doesn’t support multiple inheritances. Instead, you can use interfaces to inherit the properties using the class name in the signature.
Q #49) What are Properties in C#?
Answer: Properties in C# are public members of a class where they provide the ability to access private members of a class.
The basic principle of encapsulation lets you hide some sensitive properties from the users by making the variables private. The private members are not accessible otherwise in a class. Therefore, by using properties in C# you can easily access the private members and set their values.
The values can be easily assigned using get and set methods, also known as accessors. While the get method extracts the value, the set method assigns the value to the variables.
Q #50) What are partial classes in C#?
Answer: Partial classes implement the functionality of a single class into multiple files. These multiple files are combined into one during compile time. The partial class can be created using the partial keyword.
public partial Clas_name
{
// code
}
Q #51) What is the difference between late binding and early binding in C#?
Answer:
Late binding and early binding are examples of one of the primary concepts of OOPS: Polymorphism.
For ex: one function calculateBill() will calculate bills of premium customers, basic customers, and semi-premium customers based on their policies differently. The calculation for all the customer objects is done differently using the same function which is called polymorphism.
When an object is assigned to an object variable in C#, the .NET framework performs the binding. When the binding function happens at compile-time, it is called early binding. It investigates and checks the methods and properties of the static objects. With early binding, the number of run-time errors decreases substantially and it executes pretty quickly.
But when the binding happens at runtime, it is called late binding. Late binding happens when the objects are dynamic (decided based on the data they hold) at run-time. It is slower as it looks through during run-time.
Q #52) What are Indexers in C#?
Answer: Indexers are called smart arrays that allow access to a member variable. Indexers allow member variables using the features of an array. They are created using the Indexer keyword. Indexers are not static members. For ex. Here the indexer is defined the same way.
this[ index]
{
get{
// return the value from the specified index of an internal collection
}
set{
// set values at the specified index in an internal collection
}
}
Q #53) Difference between the Equality Operator (==) and Equals() Method in C#?
Answer: Although both are used to compare two objects by value, still they both are used differently.
For ex.:
int x = 10;
int y = 10;
Console.WriteLine( x == y);
Console.WriteLine(x.Equals(y));
Q #54) What is the difference between constant and readonly in C#?
Answer: A const keyword in C# is used to declare a constant field throughout the program. That means once a variable has been declared const, its value cannot be changed throughout the program. In C#, a constant is a number, string, null reference, or boolean values. For ex:
class IB
{
// Constant fields
public const int xvar = 20;
public const string str = "InterviewBit";
// Main method
static public void Main()
{
// Display the value of Constant fields
Console.WriteLine("The value of xvar: {0}", xvar);
Console.WriteLine("The value of str: {0}", str);
}
}
public readonly int xvar1;
public readonly int yvar2;
// Values of the readonly
// variables are assigned
// Using constructor
public IB(int b, int c)
{
xvar1 = b;
yvar2 = c;
Console.WriteLine("The value of xvar1 {0}, "+
"and yvar2 {1}", xvar1, yvar2);
}
// Main method
static public void Main()
{
IB obj1 = new IB(50, 60);
}
Q #55) What is the difference between String and StringBuilder in C#?
Answer:
The major difference between String and StringBuilder is that String objects are immutable while StringBuilder creates a mutable string of characters. StringBuilder will make the changes to the existing object rather than creating a new object.
StringBuilder simplifies the entire process of making changes to the existing string object. Since the String class is immutable, it is costlier to create a new object every time we need to make a change. So, the StringBuilder class comes into picture which can be evoked using the System.Text namespace.
In case, a string object will not change throughout the entire program, then use String class or else StringBuilder. For ex:
string s = string.Empty;
for (i = 0; i < 1000; i++)
{
s += i.ToString() + " ";
}
StringBuilder sb = new StringBuilder();
for (i = 0; i < 1000; i++)
{
sb.Append(i); sb.Append(' ');
}
By using StringBuilder here, you also de-stress the memory allocator.
Q #56) Anonymous Method in C#?
Answer:
The concept of anonymous method was introduced in C# 2.0. An anonymous method is inline unnamed method in the code. It is created using the delegate keyword and doesn’t require a name and return type. Hence we can say, an anonymous method has the only body without a name, optional parameters and return type. An anonymous method behaves like a regular method and allows us to write inline code in place of explicitly named methods.
delegate int MathOp(int a, int b);
class Program
{
static void Main(string[] args)
{
//anonymous method using delegate keyword
del d1 = delegate(int x, int y) { return x * y; };
int z1 = d1(2, 3);
Console.WriteLine(z1);
}
}
//output:
6
Q #57) Lambda Expressions in C#?
int[] numbers = { 2, 3, 4, 5 };
var squaredNumbers = numbers.Select(x => x * x);
Console.WriteLine(string.Join(" ", squaredNumbers));
// Output:
// 4 9 16 25
- If you declare any member as a non-static member, you will get an error.
- When you try to create an instance to the static class, it again generates a compile time error, because the static members can be accessed directly with its class name.
- The static keyword is used before the class keyword in a class definition to declare a static class.
- A static class members are accessed by the class name followed by the member name.
int a = 2147483647;
int b = 1;
int c = checked(a + b); // throws System.OverflowException
int a = 2147483647;
int b = 1;
int c = unchecked(a + b); // wraps around to -2147483648
- Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is dealt with when the program is compiled.
- When a function or a method calls another function which in turns calls another function etc., the execution of all those functions remains suspended until the very last function returns its value.
- The stack is always reserved in a LIFO order, the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack, freeing a block from the stack is nothing more than adjusting one pointer.
- You can use the stack if you know exactly how much data you need to allocate before compile time and it is not too big.
- 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.
- Element of the heap have no dependencies with each other and can always be accessed randomly at any time.
- You can allocate a block at any time and free it at any time.
- This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time.
- You can use heap if you don't know exactly how much data you will need at runtime or if you need to allocate a lot of data.
- A static constructor doesn't take access modifiers or have parameters.
- A class or struct can only have one static constructor.
- Static constructors cannot be inherited or overloaded.
- A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically.
- The user has no control on when the static constructor is executed in the program.
- A static constructor is called automatically. It initializes the class before the first instance is created or any static members declared in that class (not its base classes) are referenced. A static constructor runs before an instance constructor. A type's static constructor is called when a static method assigned to an event or a delegate is invoked and not when it is assigned. If static field variable initializers are present in the class of the static constructor, they're executed in the textual order in which they appear in the class declaration. The initializers run immediately prior to the execution of the static constructor.
- If you don't provide a static constructor to initialize static fields, all static fields are initialized to their default value as listed in Default values of C# types.
- If a static constructor throws an exception, the runtime doesn't invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain. Most commonly, a TypeInitializationException exception is thrown when a static constructor is unable to instantiate a type or for an unhandled exception occurring within a static constructor. For static constructors that aren't explicitly defined in source code, troubleshooting may require inspection of the intermediate language (IL) code.
- The presence of a static constructor prevents the addition of the BeforeFieldInit type attribute. This limits runtime optimization.
- A field declared as static readonly may only be assigned as part of its declaration or in a static constructor. When an explicit static constructor isn't required, initialize static fields at declaration rather than through a static constructor for better runtime optimization.
- The runtime calls a static constructor no more than once in a single application domain. That call is made in a locked region based on the specific type of the class. No additional locking mechanisms are needed in the body of a static constructor. To avoid the risk of deadlocks, don't block the current thread in static constructors and initializers. For example, don't wait on tasks, threads, wait handles or events, don't acquire locks, and don't execute blocking parallel operations such as parallel loops, Parallel.Invoke and Parallel LINQ queries.
public static class Executor
{
public static void Execute(Action action, int numberOfRetries)
{
var tries = 0;
while (tries <= numberOfRetries)
{
try
{
action();
return;
}
catch
{
tries++;
}
}
throw new RetryException($"Error after {tries} tries");
}
}
Policy.Handle<ArgumentException>().Retry(3).Execute(FirstSimulationMethod);
.Net framework
Q #1) What is the .Net framework?
Answer: It is a platform for building various applications on windows. It has a list of inbuilt functionalities in the form of class, library, and APIs which are used to build, deploy and run web services and different applications. It supports different languages such as C#, VB .Net, Cobol, Perl, etc.
This framework supports the object-oriented programming model.
Q #2) What are the important components of .Net?
Answer: The components of .Net are Common language run-time, .Net Class library, Application domain, Common Type System, .Net framework, Profiling, etc. However, the two important components are the Class library and the Common Language Runtime.
CLR provides building blocks for a wide variety of applications. The class library consists of a set of classes that are used to access common functionality. The functionality can be shared among different applications.
Q #3) What is CTS?
Answer: CTS stands for Common Type System. It has a set of rules which state how a data type should be declared, defined and used in the program. It describes the data types that are to be used in the application.
We can design our own classes and values by following the rules that are present in the CTS. The rules are made so that the data type declared using a programming language can be called by an application that is developed using a different language.
Q #4) What is CLR?
Answer: CLR stands for Common Language Runtime. It is one of the most important components of the .Net framework. It provides building blocks for many applications.
An application built using C# gets compiled by its own compiler and is converted into an Intermediate language. This is then targeted to CLR. CLR does various operations like memory management, security checks, assemblies to be loaded and thread management. It provides a secure execution environment for applications.
Q #5) What is CLS?
Answer: CLS stands for Common Language Specification. With the rules mentioned under CLS, the developers are made to use the components that are inter-language compatible. They are reusable across all the .Net Compliant languages.
Q #6) What is JIT?
Answer: JIT stands for Just In Time. JIT is a compiler that converts Intermediate Language to a Native code.
The code is converted into Native language during execution. Native code is nothing but hardware specifications that can be read by the CPU. The native code can be stored so that it is accessible for subsequent calls.
Q #7) What is MSIL?
Answer: MSIL stands for Microsoft Intermediate Language.
MSIL provides instructions for calling methods, initializing and storing values, operations such as memory handling, exception handling and so on. All .Net codes are first compiled to IL.
Q #8) What is meant by Managed and Unmanaged code?
Answer: The code that is managed by the CLR is called Managed code. This code runs inside the CLR. Hence, it is necessary to install the .Net framework in order to execute the managed code. CLR manages the memory through garbage collection and also uses the other features like CAS and CTS for efficient management of the code.
Unmanaged code is any code that does not depend on CLR for execution. It means it is developed by any other language independent of .Net framework. It uses its own runtime environment for compiling and execution.
Though it is not running inside the CLR, the unmanaged code will work properly if all the other parameters are correctly followed.
Q #9) How is a Managed code executed?
Answer: Follow these steps while executing a Managed code:
- Choosing a language compiler depending on the language in which the code is written.
- Converting the above code into Intermediate language by its own compiler.
- The IL is then targeted to CLR which converts the code into native code with the help of JIT.
- Execution of Native code.
Q #10) What is ASP.Net?
Answer: ASP .Net is a part of .Net technology and it comprises of CLR too. It is an open-source server-side technology that enables the programmers to build powerful web services, websites and web applications.
ASP stands for Active Server Pages.
Q #11) Explain State management in ASP .Net.
Answer: State Management means maintaining the state of the object. The object here refers to a web page/control.
There are two types of State management, Client Side, and Server side.
- Client-Side – Storing the information in the Page or Client’s System. They are reusable, simple objects.
- Server Side – Storing the information on the Server. It is easier to maintain the information on the Server rather than depending on the client for preserving the state.
Q #12) What is an Assembly? What are the different types of Assemblies?
Answer: An Assembly is a collection of logical units. Logical units refer to the types and resources which are required to build an application and deploy them using the .Net framework. The CLR uses this information for type implementations. Basically, Assembly is a collection of Exe and DLLs. It is portable and executable.
There are two types of Assemblies, Private and Shared.
- Private Assembly, as the name itself suggests, it is accessible only to the application. It is installed in the installation directory of the application.
- Shared Assembly can be shared by multiple applications. It is installed in the GAC.
Q #13) Explain the different parts of an Assembly.
Answer: The different parts of an Assembly includes:
- Manifest – It contains the information about the version of an assembly. It is also called as assembly metadata.
- Type Metadata – Binary information of the program.
- MSIL – Microsoft Intermediate Language code.
- Resources – List of related files.
Q #14) What is an EXE and a DLL?
Answer: Exe and DLLs are Assembly executable modules.
Exe is an executable file. This runs the application for which it is designed. An Exe is generated when we build an application. Hence, the assemblies are loaded directly when we run an Exe. However, an Exe cannot be shared with the other applications.
DLL stands for Dynamic Link Library. It is a library that consists of code that needs to be hidden. The code is encapsulated inside this library. An application can consist of many DLLs. These can be shared with the other applications as well.
Other applications which share this DLL need not worry about the code intricacies as long as it is able to call the function on this DLL.
Q #15) What is Caching?
Answer: Caching means storing data temporarily in the memory so that the application can access the data from the cache instead of looking for its original location. This increases the performance of the application and its speed. System.Runtime.Caching namespace is used for Caching information in .Net.
Given below are the 3 different types of Caching:
- Page Caching
- Data Caching
- Fragment Caching
Q #16) What is MVC?
Answer: MVC stands for Model View Controller. It is an architectural model for building the .Net applications.
Models – Model objects store and retrieve data from the database for an application. They are usually the logical parts of an application that is implemented by the application’s data domain.
View – These are the components that display the view of the application in the form of UI. The view gets the information from the model objects for their display. They have components like buttons, drop boxes, combo box, etc.
Controllers – They handle user interactions. They are responsible for responding to the user inputs, work with the model objects, and pick a view to be rendered to the user.
Q #17) What is the difference between Function and Stored procedure?
Answer:
Stored Procedure:
- A Stored Procedure is always used to perform a specific task.
- It can return zero, one or more value.
- It can have both input and output parameters.
- Exception handling can be done using a try-catch block.
- A function can be called from a Procedure.
Functions:
- Functions must return a single value.
- It can only have the input parameter.
- Exception handling cannot be done using a try-catch block.
- A Stored procedure cannot be called from a function.
Q #18) Explain CAS (Code Access Security).
Answer: .Net provides a security model that prevents unauthorized access to resources. CAS is a part of that security model. CAS is present in the CLR. It enables the users to set permissions at a granular level for the code.
CLR then executes the code depending on the available permissions. CAS can be applied only to the managed code. Unmanaged code runs without CAS. If CAS is used on assemblies, then the assembly is treated as partially trusted. Such assemblies must undergo checks every time when it tries to access a resource.
The different components of CAS are Code group, Permissions, and Evidence.
- Evidence– To decide and assign permissions, the CAS and CLR depend on the specified evidence by the assembly. The examination of the assembly provides details about the different pieces of evidence. Some common evidence include Zone, URL, Site, Hash Value, Publisher and Application directory.
- Code Group – Depending on the evidence, codes are put into different groups. Each group has specific conditions attached to it. Any assembly that matches those condition is put into that group.
- Permissions – Each code group can perform only specific actions. They are called Permissions. When CLR loads an assembly, it matches them to one of the code groups and identifies what actions those assemblies can do. Some of the Permissions include Full Trust, Everything, Nothing, Execution, Skip Verification, and the Internet.
Q #19) What is GAC?
Answer: GAC stands for Global Assembly Cache. Whenever CLR gets installed on the machine, GAC comes as a part of it. GAC specifically stores those assemblies which will be shared by many applications. A Developer tool called Gacutil.exe is used to add any file to GAC.
Q #20) What is meant by Globalization and Localization?
Answer: Internationalization is the process of designing applications that support multiple languages. This is divided into Localization and Globalization.
Globalization is nothing but developing applications to support different languages. Existing applications can also be converted to support multiple cultures.
Whereas Localization means changing the already globalized app to cater to a specific culture or language Microsoft.Extensions.Localization is used for localizing the app content. Some of the other keywords that are used for Localization are IHtmlLocalizer, IStringLocalizer, IViewLocalizer and so on
Q #21) What is a Garbage Collector?
Answer: Garbage collection is a .Net feature to free the unused code objects in the memory.
The memory heap is divided into three generations. Generation 0, Generation 1 and Generation 2.
- Generation 0 – This is used to store short-lived objects. Garbage Collection happens frequently in this Generation.
- Generation 1 – This is for medium-lived objects. Usually, the objects that get moved from generation 0 are stored in this.
- Generation 2 – This is for long-lived objects.
Collecting a Generation refers to collecting the objects in that generation and all its younger generations. Garbage collection of Generation 2 means full garbage collection, it collects all the objects in Generation 2 as well as Generation 1 and Generation 0.
During the Garbage collection process, as the first phase, the list of live objects is identified. In the second phase, references are updated for those objects which will be compacted. And in the last phase, the space occupied by dead objects are reclaimed. The remaining objects are moved to an older segment.
Garbage Collection
How Garbage Collection Works
Implicit Garbage Collection should be handled by the .Net framework. When object is created then it will be placed in the Generation 0. The garbage collection uses an algorithm which checks the objects in the generation, the objects life time get over then it will be removed from the memory. The two kinds of objects. One is Live Objects and Dead Objects. The Garbage collection algorithm collects all unused objects that are dead objects in the generation. If the live objects running for long time then based on that life time it will be moved to next generation.
The object cleaning in the generation will not take place exactly after the life time over of the particular objects. It takes own time to implement the sweeping algorithm to free the spaces to the process.
Exception Handling
The Garbage collection has designed such a way that it can be implicitly handling to collect the free spaces in memory. But as I said it takes own time to uses the algorithm to collect unused objects in the memory.
If we want to forces to collect unused objects or explicitly release particular object from the momory.The code allows us to clear the object from the heap immediately.
When it happens
The garbage collector periodically checks the heap memory to reclaim the objects when the object has no valid references in the memory.
When an object is created then it will allocate the memory in the heap then it checks the available space for the newly created objects, if the available space is not adequate to allot the space then it automatically garbage collect the unused objects. If all are valid referenced objects then it gets additional space from the processor.
If the object has reference with managed code objects then it will not free the memory space. However it cannot control the reference with unmanaged code objects, when application forces to collect the unused objects. But it can be achieved to write the explicit coding to avoid managed objects reference with unmanaged objects.
No comments:
Post a Comment