20 C# Intermediate Interview Questions & Answers
Below is a list of our C# Intermediate interview questions. Click on any interview question to view our answer advice and answer examples. You may view 5 answer examples before our paywall loads. Afterwards, you'll be asked to upgrade to view the rest of our answers.
1. Demonstrate the ways a parameter can be passed to a method in C#
This question shows the developer's understanding of the way C# methods work.
You can pass a parameter as an output parameter. An example of this is in Try methods. The int reference type takes a string-out parameter and determines whether or not it can convert it to an int. These are fundamental aspects of C# so it is imperative that you are familiar with this.
Console.WriteLine("Please enter your age");
bool isValid = int.TryParse(Console.ReadLine(), out int age);
string message = isValid ? $"You are {age} Years old" : "Please enter valid age";
Console.WriteLine(message); // if a valid int is entered, the out parameter is properly populated by the user input
Console.ReadKey();
/*
A method with an out parameter is handy when you also want to return a value as well:
*/
public class Program
{
public static void Main(string[] args)
{
// Declaring variable
// without assigning value
int G;
// Pass variable G to the method
// using out keyword
Sum(out G);
// Display the value G
Console.WriteLine("The sum of" +
" the value is: {0}", G);
// Display the result of the calculation of Sum() as well
Console.WriteLine("The return value of Sum() is " + Sum(out G));
/**
output: The sum of the value is: 160
output: The return value of Sum() is 161
**/
}
// Method in which out parameter is passed
// and this method returns the value of
// the passed parameter
public static int Sum(out int G)
{
G = 80;
G += G;
return G + 1;
}
}
/**
When a parameter is passed by reference, any changes made to that parameter is reflected in the value of that parameter when it is referenced again in the call stack
Note that str changes after the SetValue() method
**/
public class Program
{
public static void Main(string[] args)
{
// Assign string value
string str = "The original value of str";
// Pass as a reference parameter
SetValue(ref str);
// Display the given string
Console.WriteLine(str);
//output: The original value of str
//output: The new value of str
}
static void SetValue(ref string str1)
{
// Check parameter value
if (str1 == "The original value of str")
{
Console.WriteLine("The original value of str");
}
// Assign the new value
// of the parameter
str1 = "The new value of str";
}
}
Written by Edward Danganan on May 3rd, 2021
2. ASP.net - Differentiate between a session object and a cache object
This question is looking for a developer's understanding of how data is stored.
As a web developer, you'll encounter situations where you need to persist data relevant to the current user session or when that data is relevant for the entire application or is global. The session object persists only for that current user session goes away when the session object times out or is explicitly destroyed. You can define a session object in your code as follows:
Order currentOrder = new Order();
Item itm = new Item();
currentOrder.AddItem(itm);
Session["order'] = currentOrder;
// perform other actions with the order
// when you're done, you can cancel the session as follows:
Session.Abandon();
/** Persisting data or an object(s) for the lifetime of an application may be relevant when you want to share data across multiple sessions. In this case, the Cache object would be appropriate. **/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class _Default : Page
{
List<string> str = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (Cache["ListOfStrings"] == null){
str.Add("One");
str.Add("Two");
str.Add("Three");
/** Insert() is an overloaded method, so you can add other parameters to define the lifetime of the cache object how the cache expires and cache dependencies. The ListOfStrings Cache object is now available to the entire application and multiple user sessions. **/
Cache.Insert("ListOfStrings", str);
}
else
{
// if it has already been created and populated, you can now do something with the Cache object
List<string> stringList = (List<string>)Cache["ListOfStrings"];
foreach (string str in stringList)
{
//Perform some tasks based upon the string in the list
}
}
}
}
}
Written by Edward Danganan on May 3rd, 2021
3. ASP.net - Describe the different page validators
This question focuses on the developer's understanding of server controls.
Page validators are handy page controls used to validate user input. They are as follows:
CompareValidator -- This control compares the values of 2 controls, text boxes, for example. You define the ControlToValidate (which is the control you want to interrogate) and the ControlToCompare (which contains the value you want to compare against the value of the ControlToValidate). You next select the operator property, which defines the rule for comparison (LessThan, LessThanEqual, MoreThan, MoreThanEqual, DataTypeCheck, Equal, NotEqual). You then define an error message if the operator returns false.
CustomValidator -- This control allows you to define custom validation logic not available in any of the other validators. After specifying the control to validate, the custom validator control has an event called OnServerValidate, which is then hooked up to a method in your code, behind where you can place custom validation code. You can then display an error message based upon the validation.
RangeValidator -- The range validator takes the value of the controltovalidate and confirms whether or not it falls within the range defined by the Minimum and Maximum properties in the rangevalidator control.
RequiredValidator -- This control simply confirms whether or not the controltovalidate has a value. It will return the error message if the user attempts to submit the form without a value in the controltovalidate.
RegularExpression -- The regularexpression validator is often used to determine whether or not the controltovalidate value conforms to a particular format, such as an email address, postal code, date, phone number etc.
ValidationSummary -- The validation control comes in handy when there are multiple validation controls on your page. This will allow you to display all the error messages for all the validation control is a single area on the page. You can display the error messages as a simple list, a bulleted list, or a single paragraph.
Knowing what they are and how they are used can save time in providing ready-to-use, user input validation, with very little effort.
Written by Ryan Brown on May 6th, 2021
4. ASP.net - Explain the page life cycle events
This interview question focuses on the series of processing steps.
Knowing the page life cycle events of an ASP.net application is essential since particular actions take place during each event. You can then add logic to your code behind based on when each event is executed. The main events are as follows:
Pre-Init
Init
PreLoad
Load
PreRender
Render
UnLoad
In the page code-behind, the following are the corresponding methods for the page events.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
// check the IsPostBack property to see if the page has been processed for the first time
// you can create or re-create dynamic controls
}
protected void Page_Init(object sender, EventArgs e)
{
// occurs after controls have been initialized
// read or initialize control properties
}
protected void Page_PreLoad(object sender, EventArgs e)
{
// executed after page view state property is loaded and after postback data is processed
}
protected void Page_Load(object sender, EventArgs e)
{
// called after the OnLoad method is called
// load event of all the controls is raised after the page load event
}
protected void Page_PreRender(object sender, EventArgs e)
{
// The PreRender event is raised for each control on the page, after the page PreRender event is raised.
// You can make final changes to the controls or page itself before the page and control rendering begins
// Each of the controls on the page has a Render() method. This is called after the PreRender event is raised.
}
protected void Page_Unload(object sender, EventArgs e)
{
// Each control's unload event is called followed by that for the page.
// You can add final cleanup method in this method.
}
}
Written by Edward Danganan on May 3rd, 2021
5. ASP.net - What is another method for persisting the state of a page?
This interview question concentrates on the developer's ability to retain data between user requests.
A common use case of web applications is persisting user data as she navigates through the application, for example in a shopping application use the cart. This is where the session object comes into play. HTTP is a stateless protocol, which means that each request is unique and has no knowledge of prior request state so the session object allows you to deal with persisting data between requests.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class _Default : Page
{
List<OrderItem> items = new List<OrderItem>();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["myCart"] == null) {
/**Presumably, the application would have previously created a collection of order items which
can be added to the cart session here **/
Session["myCart"] = items;
/**
Session["myCart"] is now available throughout the application during the user session, until it expires or is explicitly discarded.
You would needd to cast the session object into the List<OrderItem> type and then iterate through the OrderItem objects to do something with them.
**/
}
}
}
public class OrderItem
{
string ProductName{ get;set;}
decimal Price { get; set; }
int Quantity { get; set; }
}
}
Written by Edward Danganan on May 3rd, 2021
6. ASP.net - What is View State?
This question concentrates on ASP.NET methods and their relation to C#.
The creation of web applications is a key feature of .NET and that is what ASP.net offers. If you're going to be interviewing for web application positions, you will most certainly be asked about fundamental elements of ASP.net. The next few questions will be addressing ASP.net fundamentals.
ViewState is how ASP.net maintains the state of the web page and controls between postbacks. The state data is stored on the page in a hidden input field named, "__VIEWSTATE". Let's say you have a web form with multiple text input boxes and a submit button. After clicking on the submit button, the values of the text input boxes are saved after the page posts back to itself. If ViewState were disabled (which in some cases is done) the values typed into the text boxes would be lost after a page postback and you would have very unhappy users if there was an issue with one of the entries.
Written by Ryan Brown on May 6th, 2021
7. What is the difference between managed and unmanaged code?
This interview question relates to C# terminology and how it runs.
Managed code is code compiled and run by the CLR or common language runtime. Managed code is created entirely in .NET. Unmanaged code is written in any language outside of .NET. There may be instances where unmanaged code will need to interact with managed code, for example, when your .NET application needs to access operating system resources. In this case, the unmanaged code will be referenced through .NET wrapper classes. This may occur within pure software shops, so you should be prepared to know this concept in this case.
Written by Edward Danganan on May 3rd, 2021
8. What does it mean when a class is sealed?
This interview question shows a developer's ability to implement class restrictions.
A sealed class cannot be inherited. It often includes static members. You may not want users of your class to inherit it and potentially change its behaviors or properties. The intent may be to define a single way of performing operations.
sealed class SealedClassExample
{
public int PerformAddition(int x, int y)
{
return x + y;
}
}
//Attempting to inherit a sealed class will result in a compiler error:
public class AttemptToInheritSealedClass : SealedClassExample
{
}
/* 'AttemptToInheritSealedClass': cannot derive from sealed type 'SealedClassExample' */
Written by Edward Danganan on May 3rd, 2021
9. What is the Singleton design pattern and provide an example
This interview question relates to C# terminology and understanding of the software design patterns.
This design pattern allows the creation of a single instance of the application. Because of this, a singleton application does not specify any parameters. Calling applications or codes are expected to retrieve that single instance. This fundamental design pattern is advantageous when you need to globally expose a single instance of a class to your application. An example of this could be a Windows service or a bank application.
public sealed class Singleton
{
Singleton()
{
}
private static readonly object padlock = new object();
private static Singleton instance = null;
// The lock ensures there is only one Singleton copy accessible at a time
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
public void DoSomeWork()
{
//
}
}
public class program (
public static void Main(string[] args)
{
// There will be only one instance executing DoSomeWork() at a time.
Singleton.Instance.DoSomeWork();
}
}
Written by Edward Danganan on May 3rd, 2021
10. What is meant by method overriding and provide an example
This interview question relates to C# terminology and invoking functions from another class.
Overriding is another fundamental tenet of object orientation, so an interviewer may ask this in the context of inheritance. In the inheritance model, a derived class is expected to provide a new implementation of an overridden method. The method signature must stay the same as the parent method. Note the keywords, 'virtual' and 'override'
public class Vehicle
{
protected virtual void Move()
{
// the derive class is expected to provide an implementation of Move();
// this method may provide some functionality that should be inherited
}
}
public class Bicycle : Vehicle
{
protected override void Move()
{
// you can call the base Move() implementation
base.Move();
// then provide additional tasks
BeginPedaling();
}
private void BeginPedaling()
{
// Pedal like heck!!
}
}
Written by Edward Danganan on May 3rd, 2021
11. What is an interface and what is an appropriate use case for it?
This interview question relates to C# terminology and understanding of the methods.
An interface defines a contract with classes that implement it. Implementing classes must provide method bodies for methods defined in the interface. The convention for defining an interface is starting the name with an I. If ImplementingClass does not define YouNeedToDefineMe() and YouNeedToDefineMeAlso(), a compiler error will result. An example of where an interface would be appropriate could be where you have a vendor who provides downstream processing of a particular workflow. In the case of payment processing, for example, you know there would be methods like ValidatePayment(), ProcessPayment(), Refund(), ErrorMessage(), etc. These methods would be candidates for interface methods since regardless of what vendor you may have now or in the future, the method signatures would be the same. Instead of hard-coding vendor-specific logic throughout your application, you would just need to change the code in the implementing class if you switch vendors.
interface IMyInterface
{
void YouNeedToDefineMe();
void YouNeedToDefineMeAlso();
}
public class ImplementingClass : IMyInterface
{
public void YouNeedToDefineMe()
{
//add implementing code
}
public void YouNeedToDefineMeAlso()
{
//add implementing code
}
}
Written by Edward Danganan on May 3rd, 2021
12. What is overloading and show an example
This interview question relates to C# terminology and understanding of the operators.
This is another key concept in OO programming. Overloading allows you to define methods of the same name, distinguishing them from one another by differing their method signatures. Fundamentally, DoSomething() may perform the same general task, but there may be use cases where the tasks will be different, based on the passed parameters.
public class ExampleClass
{
public int DoSomething()
{
int a = 1;
int b = 2;
return a + b;
}
public int DoSomething (int a, int b)
{
return a + b;
}
public void DoSomething(int a, int b, int c)
{
// perform some calculations with the three parameters
}
}
Written by Edward Danganan on May 3rd, 2021
13. Explain how the term, 'using', is referenced in code and how is it used.
This question shows the developer's knowledge of C# syntax.
The using expression block is another means of properly disposing of objects no longer being used. It ensures that the referenced object's Dispose() method is called and its resources are released. Doing so in your code is a good practice and should avoid runtime errors or performance issues.
string manyLines = @"This is line one of many lines
Here is the second line
Here is the third line
Here is the fourth line
This can go on and on.";
/** The StringReader object is wrapped in a using block, which ensures that any resources used by reader are released when no longer needed. If
you were reading strings from a file object,for example, not releasing the resources after reading the file contents may result in a file lock not allowing other processes from accessing the file.
**/
using (var reader = new System.IO.StringReader(manyLines))
{
string item = string.Empty;
do
{
item = reader.ReadLine();
Console.WriteLine(item);
} while (item != null);
}
Written by Edward Danganan on May 3rd, 2021
14. Show a way in which you can store values of different datatypes in a single data structure.
This question focuses on the developer's knowledge of conversion in C#.
By creating a collection object, an Array, in this case, defining it as an array of type objects, you can add any type to it. This technique allows you to quickly create
a collection of objects, regardless of their data types.
public class Program
{
public static void Main(string[] args)
{
object[] container = new object[3];
container[0] = 4;
container[1] = "a new day";
Person p = new Person();
p.Name = "Simon Chance";
p.Age = 40;
container[2] = p;
foreach (Object obj in container){
Console.WriteLine(obj);
}
}
}
public class Person
{
public string Name { set; get; }
public int Age { set; get; }
}
Written by Edward Danganan on May 3rd, 2021
15. What is a partial class?
This interview question relates to C# terminology and the special features.
C# offers the ability to split your classes, structs, or interfaces across multiple source files. This can be convenient if you have large classes, especially if you are working with a team. Multiple developers can work on the same class by accessing the appropriate source file. The class name must be preceded by the 'partial' keyword. The following example shows 2 different source files (PartialClass1.cs and PartialClass2.cs) which pertain to the same class.
/** The contents of PartialClass1.cs is: **/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyNameSpace
{
partial class PartialClass1
{
public string Developer1IsWorkingOnThis()
{
return "Developer1 working on this";
}
}
}
/** The contents of PartialClass2.cs is: **/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyNameSpace
{
partial class PartialClass1
{
public string Developer2IsWorkingOnThis()
{
return "Developer2 working on this";
}
}
}
/*
The compiled assembly will contain PartialClass1 with both methods. In your main method, you'll see that both methods are accessible:
*/
PartialClass1 cl = new PartialClass1();
Console.WriteLine(cl.Developer1IsWorkingOnThis());
Console.WriteLine(cl.Developer2IsWorkingOnThis());
Written by Edward Danganan on May 3rd, 2021
16. What is a Windows service and how would you create one?
This interview question relates to C# terminology and the programs that they run.
A Windows service is a non-UI program that is executed in the background, typically as an ongoing thread. They start when the Windows operating system boots up. You can configure it to run manually as well. The purpose of these programs is to execute tasks in the background when the OS is running and to start automatically when your system is restarted. The main advantage of a service is that its execution can be automatically started when your OS restarts, which often happens when patches are applied to your Windows server or when an application is updated or removed.
namespace MyNameSpace
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
// Create a container of services to run
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyNewService()
};
ServiceBase.Run(ServicesToRun);
}
}
}
// The MyNewService class - this encapsulates the task you wish to execute
public partial class MyNewService: ServiceBase
{
bool serviceStarted = false;
bool running = false;
private Thread thread;
public MyNewService()
{
InitializeComponent();
}
// This is the method that starts with the service starts
protected override void OnStart(string[] args)
{
ThreadStart ts = new ThreadStart(SleepAction);
thread = new Thread(ts);
thread.Start();
}
protected override void OnStop()
{
thread.Abort();
running = false;
serviceStarted = false;
}
private void SleepAction()
{
bool ret = false;
running = true;
while (running)
{
try
{
if (!serviceStarted)
{
serviceStarted = true;
}
int sleepSeconds = Configs.secondsToNextRun; // you can store your configuration settings in a separate file to be read at runtime
System.Threading.Thread.Sleep(60000);
ret = MyServiceAction.TheTask(); // This is another class that contains the details of the tasks to be executed.
//Sleep for 60 minutes
System.Threading.Thread.Sleep(300000*12);
}
catch (System.Threading.ThreadAbortException)
{
// just ignore this specific exception. It's normal when the service is stopped.
}
catch (Exception ex)
{
}
}
}// end method
}
Written by Edward Danganan on May 3rd, 2021
17. What is a lambda expression?
This interview question relates to C# terminology and understanding of the input parameters.
Lambda expressions are used to create anonymous functions. Similar to LINQ, it offers another way to query and filter a collection of objects in C#. All lambda expressions use the => operator. The left side of the operator specifies the input parameters and the right side specifies the expression or code block that interacts with the input parameters. You create a collection of Cat objects If an interviewer asked you about LINQ, you may be expected to know about lambda expressions.
System.Collections.Generic.List<Cat> cats = new System.Collections.Generic.List<Cat>() {
new Cat { Name = "Sam", Age = 4 },
new Cat { Name = "BlueEyes", Age = 1 },
new Cat { Name = "Abby", Age = 3 }
};
/*
In your console main method, the following code pulls out all cats from the original collection, whose age is > 1 and their name starts with "A".
*/
System.Collections.Generic.List<Cat> oldCats = new System.Collections.Generic.List<Cat>();
oldCats = cats.FindAll(x => (x.Age > 1 && x.Name.StartsWith("A")));
foreach (Cat ct in oldCats)
{
Console.WriteLine(ct.Name);
}
// output: Abby
Written by Edward Danganan on May 3rd, 2021
18. What is LINQ and how would you use it in an application?
This interview question relates to C# terminology and understanding of the query capabilities.
LINQ stands for language integrated query and integrates querying capabilities within C#. LINQ allows you to perform queries against a collection of objects, regardless of how the collection is populated (database, CSV, flat file, JSON, etc). LINQ offers a way to abstract querying and filtering functionality into your code versus being dependent upon an underlying data store, such as SQL Server and T-SQL. An interviewer may ask you an alternative for querying data outside of T-SQL.
In this example, you have an array of integers. The LINQ query below shows how you would pull only those integers greater than 70 and pull in the integers in descending order. Make sure you pull in the LINQ reference, "using System.Linq". There are a variety of other expressions you can use to filter your results, perform a group by, joins, etc.
int[] scores = { 90, 71, 82, 93, 75, 88};
// Query Expression.
System.Collections.Generic.IEnumerable<int> scoreQuery = //query variable
from score in scores
where score > 70
orderby score descending
select score; //must end with select or group
// Execute the query to produce the results, in your main method in this case
foreach (int testScore in scoreQuery)
{
Console.WriteLine(testScore);
}
/**
output:
93
90
88
82
75
71
**/
Written by Edward Danganan on May 3rd, 2021
19. In what instance would you use to create a Struct versus a Class?
This interview question relates to C# terminology and understanding of the values and classes.
In order to answer this question, you need to know the distinction between the two. Structs are value types whereas classes are reference types. You cannot inherit a struct. Structs' memory allocation occurs on the stack whereas classes are allocated on the heap and garbage collected, making structs less expensive to use. If you plan on iterating over a number of data points with multiple immutable properties, structs are the way to go.
struct Location
{
public int x, y;
public Location(int x, int y)
{
this.x = x;
this.y = y;
}
}
/* In your main program: */
Location a = new Location(20, 20);
Location b = a;
a.x = 100;
System.Console.WriteLine(b.x) ; //output is 20; the properties of a struct is immutable.
// if Location were a class, b.x would now be 100, as x is now a reference type.
Written by Edward Danganan on May 3rd, 2021
20. What is an Abstract class and what is an appropriate use case for it?
This interview question relates to C# terminology and understanding of the classes.
An abstract class cannot be instantiated. It is designed to have at least one method that must be defined in a child class. Following the discussion of the payment vendor example, if you know there is at least one method that should be inherited by all classes, then the abstract class design would be appropriate. For example, you may need to record the transaction in the company's order database, UpdateOrder(), which will occur regardless of the downstream implementation. Any other method implementation may change if the company changes vendors. From an interviewer's standpoint, it will important to provide a use case for an interface versus an abstract class
public abstract class MyAbstractClass {
public abstract void NeedToDefine();
public void InheritedMethod()
{
//This functionality will be used in all inherited classes
}
/* It is not necessary to provide a method implementation in the child class, but by tagging it as virtual, you have the option of doing so */
public virtual void AnotherInheritedMethod()
{
}
}
public class AbstractClassChild : MyAbstractClass
{
/* Because this method was defined as abstract in the parent class, you must define a method body in the inherited method*/
public override void NeedToDefine()
{
}
/* You can optionally provide a method implementation of the parent method. You can also call the parent method as well as providing a custom implementation */
public override void AnotherInheritedMethod()
{
base.AnotherInheritedMethod();
}
}
Written by Edward Danganan on May 3rd, 2021