C# is a modern, general-purpose, object-oriented programming language developed by Microsoft. C# is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime environment that allows the use of various high-level languages on different computer platforms and architectures.
How will you differentiate between a Class and a Struct?
Although both class and structure are user-defined data types, they are different in several fundamental ways. A class is a reference type and stores on the heap. Struct, on the other hand, is a value type and is, therefore, stored on the stack. While the structure doesn’t support inheritance and polymorphism, the class provides support for both. A class can be of an abstract type, but a structure can’t. All members of a class are private by default, while members of a struct are public by default. Another distinction between class and struct is based on memory management. The former supports garbage collection while the latter doesn’t.
Compare Virtual methods and Abstract methods.
Any Virtual method must have a default implementation, and it can be overridden in the derived class using the override keyword. On the contrary, an Abstract method doesn’t have an implementation, and it resides in the abstract class. The derived class must implement the abstract method. Though not necessary, we can use an override keyword here.
What are Namespaces in C#?
Use of namespaces is for organizing large code projects. The most widely used namespace in C# is System. Namespaces are created using the namespace keyword. It is possible to use one namespace in another, known as Nested Namespaces.
What are I/O classes in C#? Define some of the most commonly used ones.
The System.IO namespace in C# consists of several classes used for performing various file operations, such as creation, deletion, closing, and opening. Some of the most frequently used I/O classes in C# are:
File – Manipulates a file
Path – Performs operations related to some path information
StreamReader – Reads characters from a stream
StreamWriter – Writes characters to a stream
StringReader – Reads a string buffer
StringWriter – Writes a string buffer
What do you understand by regular expressions in C#? Write a program that searches a string using regular expressions.
Regular expression is a template for matching a set of input. It can consist of constructs, character literals, and operators. Regex is used for string parsing, as well as replacing the character string. Following code searches a string “C#” against the set of inputs from the languages array.
Explain Reflection
The ability of code to access the metadata of the assembly during runtime is called Reflection. A program reflects upon itself and uses the metadata to:
Inform the user, or
Modify the behavior
The system contains all classes and methods that manage the information of all the loaded types and methods. Reflection namespace. Implementation of reflection is in 2 steps:
Get the type of the object, then
Use the type to identify members, such as properties and methods.
Name some of the most common places to look for a Deadlock in C#.
For recognizing deadlocks, one should look for threads that get stuck on one of the following:
.Result, .GetAwaiter().GetResult(), WaitAll(), and WaitAny() (When working with Tasks)
Dispatcher.Invoke() (When working in WPF)
Join() (When working with Threads)
lock statements (In all cases)
WaitOne() methods (When working with AutoResetEvent/EventWaitHandle/Mutex/Semaphore)
Define Serialization and its various types in C#.
The process of converting some code into its binary format is known as Serialization in C#. Doing so allows the code to be stored easily and written to a disk or some other storage device. We use Serialization when there is a strict need for not losing the original form of the code. A class marked with the attribute [Serializable] gets converted to its binary form. A stream that contains the serialized object and the System.Runtime.Serialization namespace can have classes for serialization. Serialization in C# is of three types:
Binary Serialization – Faster and demands less space; it converts any code into its binary form. Serialize and restore public and non-public properties.
SOAP – It produces a complete SOAP compliant envelope that is usable by any system capable of understanding SOAP. The classes about this type of serialization reside in System.Runtime.Serialization.
XML Serialization – Serializes all the public properties to the XML document. In addition to being easy to read, the XML document manipulated in several formats. The classes in this type of serialization reside in System.sml.Serialization.
Note: - Retrieving the C# code back from the binary form is known as Deserialization.
Explanation on Thread Pooling in C#
A collection of threads, termed as a Thread Pool in C#. Such threads are for performing tasks without disturbing the execution of the primary thread. After a thread belonging to a thread pool completes execution, it returns to the thread pool. Classes that manage the thread in the thread pool, and its operations, are contained in the System.Threading.ThreadPool namespace.
Is it possible to use this keyword within a static method in C#?
A special type of reference variable, this keyword is implicitly defined with each non-static method and constructor as the first parameter of the type class, which defines it. Static methods don’t belong to a particular instance. Instead, they exist without creating an instance of the class and calls with the name of the class. Because this keyword returns a reference to the current instance of the class containing it, it can’t be used in a static method. Although we can’t use this keyword within a static method, we can use it in the function parameters of Extension Methods.
What can you tell us about the XSD file in C#?
XSD denotes XML Schema Definition. The XML file can have any attributes, elements, and tags if there is no XSD file associated with it. The XSD file gives a structure for the XML file, meaning that it determines what, and also the order of, the elements and properties that should be there in the XML file. Note: - During serialization of C# code, the classes are converted to XSD compliant format by the Xsd.exe tool.
What do you mean by Constructor Chaining in C#?
Constructor chaining in C# is a way of connecting two or more classes in a relationship as an inheritance. Every child class constructor is mapped to the parent class constructor implicitly by using the base keyword in constructor chaining.
Explain different states of a Thread in C#?
A thread in C# can have any of the following states:
Aborted – The thread is dead but not stopped
Running – The thread is executing
Stopped – The thread has stopped execution
Suspended – The thread has been suspended
Unstarted – The thread is created but has not started execution yet
WaitSleepJoin – The thread calls sleep, calls wait on another object, and calls join on some other thread.
Why do we use Async and Await in C#?
Processes belonging to asynchronous programming run independently of the main or other processes. In C#, using Async and Await keywords for creating asynchronous methods.
What is an Indexer in C#, and how do you create one?
known as an indexed property, an indexer is a class property allowing accessing a member variable of some class using features of an array. Used for treating an object as an array, indexer allows using classes more intuitively. Although not an essential part of the object-oriented programming, indexers are a smart way of using arrays. As such, they are also called smart arrays. Defining an indexer enables creating classes that act like virtual arrays. Instances of such classes can be accessed using the [] array access operator.
What is the Race condition in C#?
When two threads access the same resource and try to change it at the same time, we have a race condition. It is almost impossible to predict which thread succeeds in accessing the resource first. When two threads try to write a value to the same resource, the last value written is saved.
What do you understand by Get and Set Accessor properties?
Made using properties, Get and Set are called accessors in C#. A property enables reading and writing to the value of a private field. Accessors are used for accessing such private fields. While we use the Get property for returning the value of a property, use the Set property for setting the value.
Give a detailed explanation of the differences between ref and out keywords.
In any C# function, there can be three types of parameters, namely in, out and ref. Although both out and ref are treated differently at the run time, they receive the same treatment during the compile time. It is not possible to pass properties as an out or ref parameter. Following are the differences between ref and out keywords:
Initializing the Argument or Parameter – While it is not compulsory to initialize an argument or parameter before passing to an out parameter, the same needs to be initialized before passing it to the ref parameter.
Initializing the Value of the Parameter – Using ref doesn’t necessitate for assigning or initializing the value of a parameter before returning to the calling method. When using out, however, it is mandatory to use a called method for assigning or initializing a value of a parameter before returning to the calling method.
Usefulness – When the called method requires modifying the passed parameter, passing a parameter value by Ref is useful. Declaring a parameter to an out method is appropriate when multiple values are required to be returned from a function or method. Initializinga Parameter Value in Calling
Method – It is a compulsion to initialize a parameter value within the calling method while using out. However, the same is optional while using the ref parameter.
Data Passing – Using out allows for passing data only in a unidirectional way. However, data can be passed in a bidirectional manner when using ref.
What is Singleton Design Patterns in C#? Explain their implementation using an example.
A singleton in C# is a class that allows the creation of only a single instance of itself and provides simple access to that sole instance. Because the second request of an instance with a different parameter can cause problems, singletons typically disallow any parameters to be specified.
A Singleton Design Pattern ensures that a class has one and only one instance and provides a global point of access to the same. There are numerous ways of implementing the Singleton Design Patterns in C#. Following are the typical characteristics of a Singleton Pattern:
A public static means of getting the reference to the single instance created
A single constructor, private and parameter-less
A static variable holding a reference to the single instance created
The class is sealed
Explain Code compilation in C#.
There are four steps in code compilation which include:
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.
Explain Abstraction.
Abstraction is one of the OOP concepts. It is used to display only the essential features of the class and hides the unnecessary information.
Let us take an Example of a Car:
A driver of the car should know the details about the Car such as color, name, mirror, steering, gear, brake, etc. What he doesn't have to know is an Internal engine, Exhaust system.
So, Abstraction helps in knowing what is necessary and hiding the internal details from the outside world. Hiding of the internal information can be achieved by declaring such parameters as Private using the private keyword.
Explain Polymorphism?
Programmatically, Polymorphism means same method but different implementations.
It is of 2 types, Compile-time and Runtime.
Compile time polymorphism is achieved by operator overloading.
Runtime polymorphism is achieved by overriding. Inheritance and Virtual functions are used during Runtime Polymorphism.
For Example, If a class has a method Void Add(), polymorphism is achieved by Overloading the method, that is, void Add(int a, int b), void Add(int add) are all overloaded methods.
How is Exception Handling implemented in C#?
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 exception handler.
finally – It is a block of code written to execute regardless whether an exception is caught or not.
Throw – Throws an exception when a problem occurs.
What are C# I/O Classes? What are the commonly used I/O Classes?
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 path information.
What is a Destructor in C#?
A 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.
What is an Abstract Class?
An Abstract class is a class which is denoted by abstract keyword and can be used only as a Base class. An Abstract 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.
What is the difference between Continue and Break Statement?
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.
What is the difference between finally and finalize block?
inally 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 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.
What is a Jagged Array?
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][];
What is a String? What are the properties of a String Class?
A String is a collection of char objects. We can also declare string variables in c#.
string name = “Hello World”;
A string class in C# represents a string.
The properties of String class are Chars and Length.
Chars get the Char object in the current String.
Length gets the number of objects in the current String.
What is an Escape Sequence? Name some String escape sequences in C#.
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
What are Regular expressions? Search a string using regular expressions?
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.
What are the basic String Operations? Explain.
Some of the basic string operations are:
Concatenate –Two strings can be concatenated either by using System.String.Concat or by using + operator.
Modify – Replace(a,b) is used to replace a string with another string. Trim() is used to trim the string at the end or at the beginning.
Compare – System.StringComparison() is used to compare two strings, either case-sensitive comparison or not case sensitive. Mainly takes two parameters, original string, and string to be compared with.
Search – StartWith, EndsWith methods are used to search a particular string.
What are Synchronous and Asynchronous operations?
Synchronization is a way to create a thread-safe code where only one thread can access the resource at any given time.
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.
What is Reflection in C#?
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 of 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.
Explain Get and Set Accessor properties?
Get and Set are called Accessors. These are made use by Properties. A 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.
What is a Thread? What is Multithreading?
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 the multi-threaded operations:
Start, Sleep, Abort, Suspend, Resume and Join.
Most of these methods are self-explanatory.
What are Async and Await?
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.
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 Delay of 1 second is involved.
What is a Deadlock?
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.
Explain Lock, Monitors, and Mutex Object in Threading.
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.
A 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.
What is a Race Condition?
A Race condition occurs when two threads access the same resource and are trying to change it at the same time. The thread which will be able to access the resource first cannot be predicted.
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.
What is Thread Pooling?
A 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.
System.Threading.ThreadPool namespace has classes which manage the threads in the pool and its operations.
What is Serialization?
Serialization is a process of converting a 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 which can contain the serialized object and namespace System.Runtime.Serialization can contain classes for serialization.
What are the types of Serialization?
The different types of Serialization are: XML serialization, SOAP, and Binary.
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 which 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.
What is an XSD file?
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 XSD format. During Serialization of C# code, the classes are converted to XSD compliant format by xsd.exe.
What is Jagged Array in C#?
You can initialize a jagged array as − int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}}; Where, scores is an array of two arrays of integers - scores[0] is an array of 3 integers and scores[1] is an array of 4 integers.
In how many ways you can pass parameters to a method?
There are three ways that parameters can be passed to a method −