Overall Interview Questions C# Flashcards
What is a class?
A class is a template to create an object (instances). It contains properties as well as methods. We can create many instances of objects from a single class. A class can include constructors, destructors, and access modifiers to control the visibility of its members.
What are the main concepts of object-oriented programming?
Encapsulation, abstraction, polymorphism, and inheritance are the main concepts of object-oriented programming.
Explain Encapsulation
Encapsulation is a process of wrapping function and data members together in a class. It is like a capsule, a single unit.
Encapsulation is to prevent the unauthorized or unwanted change of data from outside of the function.
Below is an example of encapsulation.
class User
{
string address;
private string name;
public string Address
{
get
{
return address;
}
set
{
address = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
class MyProgram
{
static void Main(string[] args)
{
User u = new User();
// set accessor will invoke
u.Name = “Denis”;
// set accessor will invoke
u.Address = “Germany”;
// get accessor will invoke
Console.WriteLine(“Name: “ + u.Name);
// get accessor will invoke
Console.WriteLine(“Location: “ + u.Address);
Console.WriteLine(“\nPress Enter Key”);
Console.ReadLine();
}
}
What is abstraction?
Abstraction is the method of exposing only the required features of the class and hiding unnecessary information.
Let us try to understand it with the example of a motorbike
A rider knows the color, name, and model of the bike. Still, he does not know the internal engine and exhaust functionality.
So abstraction focuses on providing access to do a specific functionality without exposing how that functionality works internally.
What is polymorphism?
Polymorphism means the same method but different implementation.
There are two types of polymorphism.
Compile-time polymorphism – achieved by method overloading
Refer to the below example
public class cellphone
{
//function with the same name but different parameters.
public void Typing()
{
Console.WriteLine(“Using keypad”);
}
public void Typing(bool isSmartPhone)
{
Console.WriteLine(“Using qwerty keyboard”);
}
}
Run time polymorphism – achieved by method overriding
Refer to the below example
public class CellPhone { public virtual void Typing() { Console.WriteLine("Using keypad"); } } public class SmartPhone : CellPhone { //method override public override void Typing() { Console.WriteLine("Typing function from child class"); } }
What is Inheritance in C#?
When we create a class that can inherit the data members and the methods of another class (Parent class), it is called inheritance.
The class which inherits the properties and method is called child class, derived class or subclass.
A class from which the child class inherits its properties and methods is a parent class or base class.
Refer to the below example.
using System;
public class A
{
private int value = 1337;
public class B : A
{
public int GetValue()
{
return this.value;
}
}
}
public class InheritanceExample
{
public static void Main(string[] args)
{
var b = new A.B();
Console.WriteLine(b.GetValue());
}
}
Output will be 1337, even though Class B doesn’t directly have any value.
What is an object?
An object is an instance of a class through which we access the functions of that class. We can use the “new” keyword to create an object. A class that creates an object in memory holds information about the functions, data members, and behavior of that class.
Refer below for the syntax of an object.
//Class
public class Employee { //private members private string fName { get; set; } private string lName { get; set; } // Method (function in a class) public void Display() { Console.WriteLine("Full name is {0} {1}", fName, lName); } public void SetName(string firstName, string lastName) { fName = firstName; lName = lastName; } } class Program { static void Main(string[] args) { //this is object Employee employee = new Employee(); employee.SetName("John", "Grande"); employee.Display(); } }
What is a constructor, and what are its different types?
A constructor is like a method with the same name as the class, but it is a unique method. Even if it is not created, the compiler creates a default constructor in memory at the time of creating an object of the class.
The constructor is used to initialize the object with some default values.
Default constructor, parameterized constructor, copy constructor, static constructor, private constructor are different constructor types.
Refer to the below sample for different constructor types.
public class Student
{
private int rollNumber { get; set; }
private string fullName { get; set; }
//default constructor public Student() { //code goes here } //parameterized constructor public Student(int rNum, string fName) { this.rollNumber = rNum; this.fullName = fName; } //static constructor static Student() { //code goes here } //copy constructor public Student(Student student) { rollNumber = student.rollNumber; fullName = student.fullName; } }
What is a destructor in C#?
The Destructor clears out the memory to free up resources. It is managed automatically by the garbage collector. System.GC.collect() is called internally for this purpose. However, if required, it can be done explicitly using a destructor.
Refer to the below example.
public class Purchase
{
//Syntax to write a destructor.
~Purchase()
{
//code here to release resources.
}
}
Is C# code managed or unmanaged code?
C# is managed code because Common language runtime compiles the code to Intermediate language.
What are value types and reference types?
Value Type - Store actual data directly & typically stored in the stack like int, float, double, char, bool, decimal, struct, enum. There are Nullable versions (int? double? etc). Can be stored in heap if part of a reference type.
Reference Type - is a variable type which instead of storing the value in memory directly, stores the memory location of the actual data. Variable here stores the memory reference of the data and not the data directly. Examples are strings, class, Arrays, etc.
Variables of value type contain the value directly while the variable of a reference type contains the reference of the memory address where the value is stored actually in the memory.
For example bool, byte, int, char, and decimal are value type
And String, class, delegates are examples of reference types
Below is the pictorial representation of the value type.Interview Questions
Below is the pictorial representation of the reference type.
What are namespaces, and is that compulsory?
A namespace is a way of organizing classes of the same group or functionality under the same name. We can call it a module. Although it is not compulsory to put class in a namespace.
Refer to the syntax below.
namespace demoapp
{
class SomeClass
{
public static void someMethod()
{
Console.WriteLine(“Creating my namespace”);
}
}
}
Explain types of comments in c# with examples.
There are three types of comments in c#.
Single line comments
Multiline comments
XML comments
Example of a single-line comment
//Hey, this is a single line comment
Example of a multi line comment
/*This is a multiline comment
written in two lines
2*/
Example of an XML comment
///Summary
///Here you can write anything
///summary
What is an interface? Give an example.
An interface is another form of an abstract class that has only abstract public methods, and these methods only have the declaration and not the definition. A class implementing the interface must have the implementation of all the methods of the interface.
For Example
interface IPencil
{
void Write(string text);
void Sharpen(string text);
}
class Pencil : IPencil { public void Write(string text) { //some code here } public void Sharpen(string text) { //some code here } }
How to implement multiple interfaces with the same method name in the same class?
If we want to implement multiple interfaces with the same method name, then we cannot directly implement the body of the function. We have to explicitly provide the name of the interface to implement the body of the method. In this way, the compiler decides which interface methods we are referring to, and this resolves the issue.
Let us see the below example.
interface myInterface1
{
void Print();
}
interface myInterface2
{
void Print();
}
class Student : myInterface1,
myInterface2
{
void myInterface1.Print()
{
Console.WriteLine(“For myInterface1 !!”);
}
void myInterface2.Print() { Console.WriteLine("For myInterface2 !!"); } }
What is the virtual method, and how is it different from the abstract method?
A virtual method must have a default implementation, and We can override this virtual method using the override keyword in the derived class.
The abstract method is without implementation, and it is created inside the abstract class only. In the case of an abstract class, the class derived from the abstract class must have an implementation of that abstract method.
Example of a virtual method.
public class CellPhone
{
public virtual void Typing()
{
Console.WriteLine(“Using old keypad”);
}
}
public class SmartPhone : CellPhone { public override void Typing() { Console.WriteLine("Using qwerty keyboard"); } } Example of an abstract method.
public abstract class CellPhones
{
//no default implementation
public abstract void Typing();
}
public class OldPhones : CellPhones { //function override public override void Typing() { Console.WriteLine("Using keypad"); } } public class SmartPhones : CellPhones { //function override public override void Typing() { Console.WriteLine("Using Qwerty keyboard"); } }
What is method overloading and method overriding?
Method overloading is when we have a function with the same name but a different signature.
Method overriding is when we override the virtual method of a base class in the child class using the override keyword.
Both, method overloading and overriding are a type of polymorphism.
What is the static keyword?
We use the “static” keyword to create a static class, a static method, or static properties.
When we create a static class, then there can be only static data members and static methods in that class.
Static means that we cannot create the instance of that class. That class can be used directly like ClassName.methodName.
When there is a need for special functions, which are typical for all the instances of other classes, then we use static class.
For example, there is a requirement to load some default application-level values. We create a static class with static functions. That class is then accessible to all other classes without creating any instance. It also shares the same data with all the classes.
Refer to the below example.
public static class Setting
{
public static int fetchDefault()
{
int maxAmount = 0;
//code to fetch and set the value from config or some file.
return maxAmount;
}
}
public class Sales { //not required to create an instance. int maxAmount = Setting.fetchDefault(); }
Can we use “this” with the static class?
No, we cannot use “this” with the static class because we can only use static variables and static methods in the static class.
What is the difference between constants and read-only?
Constant variables have to be assigned a value at the time of declaration only, and we cannot change the value of that variable throughout the program.
We can assign the value to the read-only variable at the time of declaration or in a constructor of the same class.
Here is an example of constants.
using System;
namespace demoapp
{
class DemoClass
{
// Constant fields
public const int myvar = 101;
public const string str = “staticstring”;
// Main method
static public void Main()
{
// Display the value of Constant fields
Console.WriteLine(“The value of myvar: {0}”, myvar);
Console.WriteLine(“The value of str: {0}”, str);
}
}
}
Here is an example of read-only.
using System;
namespace demoapp
{
class MyClass
{
// readonly variables
public readonly int myvar1;
public readonly int myvar2;
// Values of the readonly
// variables are assigned
// Using constructor
public MyClass(int b, int c)
{
myvar1 = b;
myvar2 = c;
Console.WriteLine(“Display value of myvar1 {0}, “ +
“and myvar2 {1}”, myvar1, myvar2);
}
// Main method static public void Main() { MyClass obj1 = new MyClass(100, 200); } } }
What is the difference between string and string builder in C#?
A string is an immutable object. When we have to do some actions to change a string or append a new string, it clears out the old value of the string object, and it creates a new instance in memory to hold the new value in a string object. It uses System. String class, for example.
using System;
namespace demoapp
{
class StringClass
{
public static void Main(String[] args) {
string val = “Hello”;
//creates a new instance of the string
val += “World”;
Console.WriteLine(val);
}
}
}
StringBuilder is a mutable object. It means that it creates a new instance every time for the operations like adding string (append), replace string (replace). It uses the old object only for any of the operations done to the string and thus increases the performance. It uses System.Text.StringBuilder class, for example.
using System;
using System.Text;
namespace demoapp
{
class StringClass
{
public static void Main(String[] args) {
StringBuilder val = new StringBuilder(“Hello”);
val.Append(“World”);
Console.WriteLine(val);
}
}
}
The output of both the program is the same, “Hello World.”
Explain the “continue” and “break” statement
We can use continue and break statements in a loop in c#. Using a break statement, we can break the loop execution, while using the continue statement, we can break one iteration of the loop.
An example of the break statement.
using System;
namespace demoapp
{
class LoopingStatements
{
public static void Main(String[] args)
{
for (int i = 0; i <= 5; i++)
{
if (i == 4)
{
break; //this will break the loop
}
Console.WriteLine(“The number is “ + i);
Console.ReadLine();
} //control will jump here after the break statement.
}
}
}
Here is the same example with a continue statement.
using System;
namespace demoapp
{
class LoopingStatements { public static void Main(String[] args) { for (int i = 0; i <= 5; i++) { if (i == 4) { continue;// it will skip the single iteration } Console.WriteLine("The number is " + i); Console.ReadLine(); } } } }
What are boxing and unboxing?
Conversion of value type datatype to reference type (object) datatype is called boxing.
For Example:
namespace demoapp
{
class Conversion
{
public void DoSomething()
{
int i = 10;
object o = i;
}
}
}
Unboxing is the conversion of reference type datatype to value type.
For Example:
namespace demoapp
{
class Conversion
{
public void DoSomething()
{
object o = 222;
int i = (int)o;
}
}
}
What is a sealed class?
We use a “sealed” keyword to create a sealed class. Classes are created as a sealed class when there is no need to inherit that further or when there is a need to restrict that class from being inherited.
Refer to the syntax below.
public sealed class MyClass
{
//properties and methods
}