C# is an object-oriented language and classes are its foundation. A class generally depicts the structure of data, how data is stored and managed within a program. A class has its own properties, methods, and other objects that define the class.
Objects are the real-world entity having some characteristics and is created using the class instance. These classes define the type of the defined object.
For example, if we consider a program that covers the object related to the book. We call the class a Book which has two properties: name and the author. In real programming, Vedas is an object and an instance of the class Book.
These are the keywords that help to define the accessibility of class, member, and data type in the program. These keywords are used to restrict the use of some data manipulation done by other classes. There are 4 types of access modifiers- public, private, protected, and internal. These modifiers define 6 other accessibility levels when working together- public, protected, internal, protected internal, private, and private protected.
The using statement is used to control the usage of one or more resources that are being used within the program. The resources are continuously consumed and released. The main function of this statement is to manage unused resources and release them automatically. Once the object is created which is using the resource and when you are done you make sure that the object’s dispose method is called to release the resources used by that object, this is where using statements works well.
Finalize method- The finalize () method is defined in the object class which is used for cleanup activities. This method is generally called by the garbage collector whenever the reference of any object is not used for a long time. Garbage collector frees that managed resources automatically but if you want to free the unused resources like filehandle, data connection, etc., then you have to implement the finalize method manually.
There are three ways of passing parameters to a method:
Value Parameters- Under this method the actual value of an argument is copied to the formal parameter of the function. In, this case the changes made into the formal parameter of the function have no effect on the actual value of the argument.
Reference Parameters- This method copies the argument referring to the memory location into the formal parameter. Meaning changes made to the parameter affect the argument.
Output Parameters- This method returns more than one value.
Let’s move ahead in C# Interview Questions and see the next category.
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);
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.
User controls are very easy to create and are very much the same as the ASP control files. You cannot place a user control on the toolbox and cannot even drag-drop it. They have unique design and individual code behind these controls. Ascx is the file extension for user control.
You can create custom code as the compiled code and can be added to the toolbox. You can include these controls to the web forms easily. Custom controls can be added to multiple applications efficiently. If you want to add a private custom control then you can copy it to dll and then to the bin directory of your web application and use its reference there.
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 behaviour
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
For recognizing deadlocks, one should look for threads that get stuck on one of the following:
1. .Result, .GetAwaiter().GetResult(), WaitAll(), and WaitAny() (When 2.working with Tasks)
3. Dispatcher.Invoke() (When working in WPF)
4. Join() (When working with Threads)
5. lock statements (In all cases)
6. WaitOne() methods (When working with 7.AutoResetEvent/EventWaitHandle/Mutex/Semaphore)
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.
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.
Processes belonging to asynchronous programming run independently of the main or other processes. In C#, using Async and Await keywords for creating asynchronous methods.
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.
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.
Some of the basic string operations are:
Concatenate: Two strings can be concatenated either by using a 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 a 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.
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.
finally block is called after the execution of try and catch blocks, It is used for exception handling whether or not the exception has been caught this block of code gets executed. Generally, this block of code has a cleaner code.
The finalize method is called just before the garbage collection. Main priorities are to perform clean up operation for unmanaged code, it is automatically invoked when an instance is not subsequently called.
Managed code is one which is executed by CLR (Common Language Runtime) in simple terms it means all the application code is dependent on the .NET platform, considered as overseen in view of them. Unmanaged code is any code that is executed by runtime application of some other structure different from .NET platform. The runtime of application will deal with memory, security and other execution activities.
Colon is used as an inheritance operator in C#. Place the colon and the class name.
public class Derivedclass: childclass
A Delegate that points to more than one method is called a Multicast Delegate. Multicasting is achieved by using + and += operator.
Consider the example from Q #32.
There are two subscribers for deathEvent, GetPatInfo, and GetDeathDetails. And hence we have used += operator. It means whenever the myDel is called, both the subscribers get called. The delegates will be called in the order in which they are added.
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.
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.
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 that manage the threads in the pool and its operations.
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.
Streamreader and StreamWriter are classes of namespace.System.IO. Used when we want to read or write charact90, Reader based data,
respectively.
members of StreamReader are: close(), Read(), Readline().
members of Streamwriter are: close(), write(), writeline().
Example program:
Class Testprogram
{
using(StreamReader sr = new StreamReader("C:Readme.txt")
{
// Any code to read//
}
using(StreamWriter sr = ndew StreamWriter("C:Readme.txt")
{
// Any code to write//
}
}
Namespaces are used for organizing large code projects. “System†is one of the most popular and widely used namespaces in C#. One can create their own namespace and use one into another called nesting.
“Using†keyword simply denotes that the particular namespace is being used by the program. For ex- 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.
A Jagged array is referred to as an “array of arraysâ€. It is an array whose elements are arrays, the element of the same can be of different dimensions and sizes. The length of each array index can differ.
Example:
int[][] jagArray = new int[5][];
An Interface is a class with no implementation. It consists of a declaration of methods, Parameters, and values.
The trip of a Web page from the client to the server and then back to the client is known as a round trip. In ASP.NET Response.Redirect() causes a round trip.
Following is the way to define a connection string in Web.config for SQL Server database.
<connectionStrings>
<add name="strcon" connectionString="Data Source=DonetApp; Initial Catalog=dotnetDB; Persist Security Info=True; User ID=asif@123; Password=123@asif" providerName="System.Data.SqlClient"/>
</connectionStrings>
When we want to define a function with ‘n’ arguments, we can use the params keyword in front of the definition of the last parameter.
These n number of arguments are changed by the compiler into elements in a temporary array and actually, this array is received at the receiving end.
public class ParamsExample {
static decimal TotalSum(decimal d1, params int[] values) {
decimal total = d1;
foreach (int value in values) {
total += value; } return total; } static void Main()
{
decimal d1 = 100; int sum1 = TotalSum(d1, 1); Console.WriteLine(sum1);
int sum2 = TotalSum(sum1, 1, 2); Console.WriteLine(sum2);
Console.Read(); } } /* Output 101 104 */
When we have to implement a singleton class pattern, we can declare a constructor private.
Private constructor contains only static members. As it is private constructor, it cannot be externally called. If a class that has one or more private constructor and no public constructor, then other classes except nested classes are not allowed to create an instance of this class and it cannot be inherited.
Sealed classes are special types of class that is being restricted to be inherited. The sealed modifier is used to prevent a class inheritance. If you try to inherit a sealed class then a compile-time error occurs.
Example: Sealed class Example
{
void Display()
{
Console.WriteLine("Sealed class method!"); } } class MyExample : Example {
void Show() {
Console.WriteLine("Show method!"); } } Produces error , 'MyExample' cannot derive from sealed type 'Example'
Hyperlink control does not have the Click and Command events; whereas the LinkButton control has these events, which can be handled in the code-behind file of the Web page.
Navigation controls help us to navigate in a Web application easily. These controls store all the links in a hierarchical or drop-down structure; thereby facilitating easy navigation in a Web application.
Client-side validations work at the client end with the help of scripting languages such as JavaScript or jQuery and VBScript. On the other hand, server-side validations work at the server end with the help of programming languages like C#, VB, F# etc. Server validations work when you submit or send data to the server.
ASP.NET provides resource files to implement globalization and localization. The resource file is an XML file having extension resx. Each resource in the resx file is in the form of a key-value pair. For each culture which your application needs to support create a separate resource file. For example, WebResources.en.resx is a resource file for English language and WebResources.hi.resx is a resource file for the Hindi language.
A neutral culture is a culture that is associated with a language but not with a country or region. For example, "en" for English and in for Hindi. Culture consists of language and the country or region. It is denoted by culture code which contains two lowercase letters denoting the language and two uppercase letters denoting the country or region like as en-US for English in the US, en-GB for UK etc. A language is any spoken language like English (en), Hindi (hi), and German (de) etc.
Parsing is a method of converting a string into another data type.
Example:
string text = "200";
int num = int.Parse(text);
In the above-given example, 200 is an integer. So, the Parse method converts the string 200 into its own base type, i.e. int.
To parse a DateTime String let’s see a small example.
Example:
string dateTime = "Aug 26,2019"; Datetime parsedvalue = Datetime.Parse(dateTime);
Using the Clone() method, a new array object is created containing all elements of the original array. Using the CopyTo() method all the elements of the existing array gets copied into another existing array. Both use a shallow copy method.
To catch an Exception we make use of try-catch blocks. The catch block has a parameter of the system.Exception type.
Example:
try
{
GetAllData();
}
catch(Exception ex){
}
Finally block will be executed irrespective of exception. So while executing the code in try block when exception is occurred, control is returned to catch block and at last finally block will be executed. So closing connection to database / releasing the file handlers can be kept in finally block.
Thread represents an actual OS-level thread, with its own stack and kernel resources. Thread allows the highest degree of control; you can Abort() or Suspend() or Resume() a thread, you can observe its state, and you can set thread-level properties like the stack size, apartment state, or culture. ThreadPool is a wrapper around a pool of threads maintained by the CLR.
The Task class from the Task Parallel Library offers the best of both worlds. Like the ThreadPool, a task does not create its own OS thread. Instead, tasks are executed by a TaskScheduler; the default scheduler simply runs on the ThreadPool. Unlike the ThreadPool, Task also allows you to find out when it finishes, and (via the generic Task) to return a result.
A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.
In the following example, the lambda expression x => x * x, which specifies a parameter that's named x and returns the value of x squared, is assigned to a variable of a delegate type:
Func<int, int> square = x => x * x;
Console.WriteLine(square(5));
// Output:
// 25
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. The answer to second question is "almost never".
Typically one only creates a destructor when your class is holding on to some expensive unmanaged resource that must be cleaned up when the object goes away. It is better to use the disposable pattern to ensure that the resource is cleaned up. A destructor is then essentially an assurance that if the consumer of your object forgets to dispose it, the resource still gets cleaned up eventually.
In an interface, we have virtual methods that do not have method definition. All the methods are there to be overridden in the derived class. That's why they all are public.
The question about interfaces and abstract classes tests the candidate’s understanding of the object oriented paradigm. Plus, the examples are to prove whether or not they can implement interfaces and abstract classes in C#.
The LINQ question tests the candidate’s competence in one of the most practically used APIs provided in .NET platform to query and retrieve data from different sources since data is center of all application workflow. I was asked about C# interfaces and abstract classes so many times during my numerous interviews with different companies that I practically wrote an article to demystify the concept.