Skip to content

hellomrsun/csharp-interview-questions

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 

Repository files navigation

CSharp interview questions and answers


Number Questions
1 What is C#?
2 What is the root type of all types?
3 What is an object?
4 What is a value type?
5 What is a reference type?
6 What is the difference between value type and reference type?
7 What is a class?
8 What is a struct?
9 What are access modifiers?
10 What is sealed class?
11 What is partial class?
12 What is an abstract class?
13 What is a static class?
14 What is a partial method?
15 What is a sealed method?
16 What is interface?
17 What is the difference between interface and abstract class?
18 What is anonymous type?
19 What is boxing and unboxing?
20 What is inheritance?
21 What is encapsulatio?
22 What is polymorphism?
22 What is abstraction?
23 What is managed code and unmanaged code?
24 What is the difference between virtual method and abstract method?
25 What is namespace?
26 What is the difference between break and continue?
27 What is the difference between constant and readonly?
28 What is the difference between ref and out?
29 What is the difference between finalize and dispose ?
30 What is the difference between finalize and finally ?
31 What is the difference between string and System.String ?
32 What is the difference between String and StringBuilder?
33 What is delegate and how to use delegate?
34 What are types of delegates?
35 What is an event ?
36 What is the relationship between delegate and event?
37 What is generics?
38 What is lazy loading?
39 What is IEnumerable?
40 What is property
41 What is indexer?
42 What is .NET Framework?
43 What is CLR?
44 What is CTS?
45 What is CLI?
46 What is BCL?
47 What is DLR?
48 What is side by side execution?
49 What is Application domain?
50 What is GAC?
51 What is JIT?
52 What are the types of JIT?
53 What is GC?
54 What is IL?
55 What is manifest?
56 What is CAS?
57 How many ways are there to overload a method?
58 How "using" is used?
59 What is serialization?
60 What is jagged array?
61 What is LINQ?
62 What is Lambda expression?
63 What is dealock?
64 What is race condition?
65 What is thread?
66 What are status of a thread?
67 What is multithreading?
68 What are types of thread?
69 What are async and await?
70 What is covariance?
71 What is contravariance?
72 What is async and await?
73 What is the difference between HashSet, Hashtable and Dictionary?
74 Write a singleton class
75 What are design patterns?


  1. What is CSharp?

C# (pronounced "See Sharp") is a general-purpose, multi-paradigm programming language encompassing strong typing, lexically scoped, imperative, declarative, functional, generic, object-oriented (class-based), type-safe, and component-oriented programming disciplines.

It was developed around 2000 by Microsoft as part of its .NET initiative, and later approved as an international standard by Ecma (ECMA-334) and ISO (ISO/IEC 23270:2018).

Mono is the name of the free and open-source project to develop a compiler and runtime for the language.

C# is one of the programming languages designed for the Common Language Infrastructure (CLI).

C# was designed by Anders Hejlsberg, and its development team is currently led by Mads Torgersen.

C# Language Specification : Standard ECMA-334

ECMA (European Computer Manufacturers Association) is located in Geneva.

Other ECMA standards:

Number Name
ECMA-335 CLI: Common Language Infrastructure
ECMA-348 WSDL: Web Services Description Language
ECMA-404 The JSON Data Interchange Syntax
ECMA-262 ES2020: ECMAScript® 2020 Language Specification

C# version & features:
C# version Publication year .NET version Visual Studio version New Features
C# 1.0 2002 .NET 1.0 Visual Studio .NET 2002 > Classes
> Structs
> Interfaces
> Events
> Properties
> Delegates
> Expressions
> Statements
> Attributes
C# 1.2 2003 .NET 1.1 Visual Studio .NET 2003 > The code generated in a foreach loop called Dispose on an IEnumerator when that IEnumerator implemented IDisposable.
C# 2.0 2005 .NET 2.0 Visual Studio 2005 > Generics
> Partial types
> Anonymous methods
> Nullable value types
> Iterators
> Covariance and contravariance
> Getter/setter separate accessibility
> Method group conversions (delegates)
> Static classes
> Delegate inference
C# 3.0 2008 .NET 3.5 Visual Studio 2008 > Auto-implemented properties
> Anonymous types
> Query expressions
> Lambda expressions
> Expression trees
> Extension methods
> Implicitly typed local variables(var)
> Partial methods
> Object and collection initializers
> LINQ
C# 4.0 2010 .NET 4.0 Visual Studio 2010 > Dynamic binding
> Named/optional arguments
> Generic covariant and contravariant
> Embedded interop types
C# 5.0 2012 .NET 4.5 Visual Studio 2012 > Asynchronous members
> Caller info attributes
C# 6.0 2015 .NET 4.6
.NET Core 1.0
.NET Core 1.1
Visual Studio 2015 > Static imports
> Exception filters
> Auto-property initializers
> Expression bodied members
> Null propagator
> String interpolation
> nameof operator
> Index initializers
> Await in catch/finally blocks
> Default values for getter-only properties
C# 7.0 2017 .NET 4.7 Visual Studio 2017 > Out variables
> Tuples and deconstruction
> Pattern matching
> Local functions
> Expanded expression bodied members
> Ref locals and returnsDiscards
> Binary Literals and Digit Separators
> Throw expressions
C# 7.1 2017 .NET Core 2.0 Visual Studio 2017 > async Main method
> default literal expressions
> Inferred tuple element names
C# 7.2 2017 .NET Core 2.0 Visual Studio 2017 > Techniques for writing safe efficient code
> Non-trailing named arguments
> Leading underscores in numeric literals
> private protected access modifier
> Conditional ref expressions
C# 7.3 2017 .NET Core 2.1
.NET Core 2.2
.NET 4.8
Visual Studio 2017 > Accessing fixed fields without pinning
> Reassigning ref local variables
> Using initializers on stackalloc arrays
> Using fixed statements with any type that supports a pattern
> Using additional generic constraints
C# 8.0 2019 .NET Core 3.0 Visual Studio 2019 > Readonly members
> Default interface methods
> Switch expressions
> Property patterns
> Tuple patterns
> Positional patterns
> Using declarations
> Static local functions
> Disposable ref structs
> Nullable reference types
> Asynchronous streams
> Indices and ranges
> Null-coalescing assignment
> Unmanaged constructed types
> Stackalloc in nested expressions
> Enhancement of interpolated verbatim strings

back to top


  1. What is the root type of all types?

C# has a unified type system.

All C# types, including primitive types such as int and double, inherit from a single root object type.

Thus, all types share a set of common operations, and values of any type can be stored, transported, and operated upon in a consistent manner.

Furthermore, C# supports both user-defined reference types and value types, allowing dynamic allocation of objects as well as in-line storage of lightweight structures.


back to top


  1. What is an object?

Object is the base type for all the other types.

Object's body:

[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class Object
{
    [NonVersionableAttribute]
    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
    public Object();

    [NonVersionableAttribute]
    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    ~Object();

    public static bool Equals(Object objA, Object objB);
    
    [NonVersionableAttribute]
    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    public static bool ReferenceEquals(Object objA, Object objB);
    
    public virtual bool Equals(Object obj);

    public virtual int GetHashCode();

    [SecuritySafeCritical]
    public Type GetType();

    public virtual string ToString();

    [SecuritySafeCritical]
    protected Object MemberwiseClone();
}

Object has 2 extension methods: Equals and ReferenceEquals. Equals: compares two objects' values ReferenceEquals: compares two objects' references

Object has 3 default virtual methods Equals, GetHashCode, ToString. You can override the default methods in your customized derived types (structs, classes).

Object has 1 public method GetType to get the type of a variable.


back to top


  1. What is a value type?

Value type includes all numeric types, DateTime, Timespan, Struct and Enum types.


C# Value type keyword .NET type Description
bool System.Boolean A true/false value
byte System.Byte Unsigned 8-bit value
sbyte System.SByte Signed 8-bit value
char System.Char 16-bit Unicode character (char never represents an 8-bit value as it would in unmanaged C++.)
decimal System.Decimal A 128-bit high-precision floating-point value commonly used for financial calculations in which rounding errors can't be tolerated.
double System.Double IEEE 64-bit floating point value
float System.Single IEEE 32-bit floating point value
int System.Int32 Signed 32-bit value
uint System.UInt32 Unsigned 32-bit value
long System.Int64 Signed 64-bit value
ulong System.UInt64 Unsigned 64-bit value
short System.Int16 Signed 16-bit value
ushort System.UInt16 Unsigned 16-bit value
DateTime System.DateTime date and time of day
TimeSpan System.TimeSpan time interval

The characteristics of a value type is: a value type variable contains a simple value. When you copy an value type variable, you create a new copy of the value.


//Declare a struct
public struct Rectangle{
    public int X {get;set;}
    public int Y {get;set;}
}

public static void Main(){
    var rectangle1 = new Rectangle(){
        X = 5,
        Y = 10
    };
    var rectangle2 = rectangle1;
    rectangle1.X = 6;
    Console.WriteLine(rectangle1.X); //Display: 6
    Console.WriteLine(rectangle2.X); //Display: 5, rectangle2'X has changed
}

To check if a variable is value type, you can simply do this:

var value = 10;
var isValueType = value.GetType().IsValueType;
Console.WriteLine(isValueType); //Display: true

back to top


  1. What is a reference type?

Reference type includes class, string, delegates, interface, and array types.


C# Reference type keyword .NET type Description
object System.Object Base type of all types
string System.String An array of characters
dynamic System.Object To the common language runtime (CLR), dynamic is identical to object.

When you copy an reference type variable, you create a new copy of reference pointing to the same value.

//Declare a class
public class Circle{
    public int Radius {get;set;}
}

public static void Main(){
    var circle1 = new Circle(){
        Radius = 1
    };
    var circle2 = circle1;
    circle1.Radius = 2;
    Console.WriteLine(circle1.Radius); //Display: 2
    Console.WriteLine(circle2.Radius); //Display: 2, circle2 has the same reference as circle1
}

back to top


  1. What is the difference between value type and reference type?

Value typed data is stored in stack.

Reference typed data is stored in heap, the reference to data is stored in stack.


back to top


  1. What is a class?

A type that is defined as a class is a reference type. Its default value is null.

public class Student{
    public string Name {get;set;}
}
public static void Main(){
    Student student;
    Console.WriteLine(student.Name == null); //Display: true
}

back to top


  1. What is a struct?

A structure type (or struct type) is a value type that can encapsulate data and related functionality.

Typically, you use structure types to design small data-centric types that provide little or no behavior. For example, .NET uses structure types to represent a number (both integer and real), a Boolean value, a Unicode character, a time instance.

public struct Coordinate {
    public decimal X {get;set;}
    public decimal Y {get;set;}
}

back to top


  1. What are access modifiers?

public: can be accessed in same assembly or different assembly

internal: can be accessed in the same assembly, but not from another assembly.

protected internal: can be accessed in the same assembly, or derived types in another assembly.

protected: can be accessed in the same class or derived class.

private protected: can be accessed in the same class or derived class.

private: The type or member can be accessed only by code in the same class or struct.


Classes and structs declared directly within a namespace (in other words, that aren't nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified.

namespace CSharpAssembly {
    //The following are OK
    public class ClassA {}
    internal class ClassB {} 

    //The following are KO
    //Compile-time error: Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal
    private class ClassC {} 
    protected class ClassD {}
    private protected class ClassE {} 
    protected internal class ClassF {} 
}

Class members could be public, internal, protected, protected internal, private, private protected, and private.

Class member access modifier table:

Access ModifierC# versionSame AssemblyDifferent Assembly
Same classDerived classOther classDerived classOther class
PublicYYYYY
InternalYYY
Protected InternalYYYY
ProtectedYYY
Private Protected7.2 or laterYY
PrivateY

back to top


  1. What is a sealed class?

Sealed class can not be inherited.

public sealed class A{
    public int Add(int x, int y){
        return x + y;
    }
}

back to top


  1. What is a partial class?

Partial class means a class can be divided into several classes.

Partial class could be generated automatically by frameworks like ASP.NET Web Forms, or Entity Framework etc.

ASP.NET Web Forms example:

//File: About.aspx.cs
public partial class About : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}
//File: About.aspx.designer.cs
public partial class About
{
}

In the above About class you can see, if one partial class already inherit from a base class, its homologue will not need to inherit the same base class again in the declaration.

Entity framework generated partial dbContext:

public partial class WineDbEntities : DbContext
{
    public WineDbEntities()
        : base("name=WineDbEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<C__EFMigrationsHistory> C__EFMigrationsHistory { get; set; }
    public virtual DbSet<Grape> Grape { get; set; }
}

Entity framework generated partial data model:

public partial class Grape
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

Partial class could also be used in different components of the same framework.

Take a example of CoreCLR:

//File path: TypeSystem\RuntimeDetermined\TypeDesc.RuntimeDetermined.cs
namespace Internal.TypeSystem
{
    partial class TypeDesc
    {
        public abstract bool IsRuntimeDeterminedSubtype
        {
            get;
        }

        public bool IsRuntimeDeterminedType
        {
            get
            {
                return this.GetType() == typeof(RuntimeDeterminedType);
            }
        }

        public abstract TypeDesc GetNonRuntimeDeterminedTypeFromRuntimeDeterminedSubtypeViaSubstitution(Instantiation typeInstantiation, Instantiation methodInstantiation);
    }
}

//File path: TypeSystem\Serialization\TypeDesc.Serialization.cs
namespace Internal.TypeSystem
{
    partial class TypeDesc
    {
        public virtual bool IsSerializable
        {
            get
            {
                return false;
            }
        }
    }
}

Important: partial class must be in the same namespace and same physical assembly (.dll or .exe).


back to top


  1. What is an abstract class?

Abstract class is always used with abstract method, and act as the base class.

Abstract class can not be instantiated, you have to instantiate its derived class.

public abstract class Employee
{
    public abstract void Do();
}
public class Worker : Employee
{
    public override void Do()
    {
        //DO
    }
}

back to top


  1. What is a static class?


back to top


  1. What is the difference between string and System.String?

The string type represents a sequence of zero or more Unicode characters. string is an alias for System.String in .NET.

string is an alias in C# System.String is a .NET type.


back to top


  1. What is delegate and how to use delegate?


back to top


  1. Write a singleton class

This is a singleton logger implemented with Lazy.

public class Logger
{
    private static readonly ILog Log = LogManager.GetLogger(typeof(LoggerConfigurator));

    private static readonly Lazy<LogWrapper> Lazy = new Lazy<LogWrapper>(() => new LogWrapper(Log));

    public static LogWrapper Instance
    {
        get { return Lazy.Value; }
    }
}

back to top


  1. #### What are design patterns?
    

Design patterns are common best practices in developing software.

The book Design Patterns: Elements of Reusable Object-Oriented Software introduced 23 design patterns.

This book has 4 authors: Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, so the design patterns are also called Gang of Four Design Patterns.

They are 3 types of design patterns:

  • Creational design patterns:
    • Abstract factory groups object factories that have a common theme.
    • Builder constructs complex objects by separating construction and representation.
    • Factory method creates objects without specifying the exact class to create.
    • Prototype creates objects by cloning an existing object.
    • Singleton restricts object creation for a class to only one instance.

  • Structual design patterns:

    • Adapter allows classes with incompatible interfaces to work together by wrapping its own interface around that of an existing class.
    • Bridge decouples an abstraction from its implementation so that the two can vary independently.
    • Composite composes zero-or-more similar objects so that they can be manipulated as one object.
    • Decorator dynamically adds/overrides behaviour in an existing method of an object.
    • Facade provides a simplified interface to a large body of code.
    • Flyweight reduces the cost of creating and manipulating a large number of similar objects.
    • Proxy provides a placeholder for another object to control access, reduce cost, and reduce complexity.

  • Behaviorial design patterns:

    • Chain of responsibility delegates commands to a chain of processing objects.
    • Command creates objects which encapsulate actions and parameters.
    • Interpreter implements a specialized language.
    • Iterator accesses the elements of an object sequentially without exposing its underlying representation.
    • Mediator allows loose coupling between classes by being the only class that has detailed knowledge of their methods.
    • Memento provides the ability to restore an object to its previous state (undo).
    • Observer is a publish/subscribe pattern which allows a number of observer objects to see an event.
    • State allows an object to alter its behavior when its internal state changes.
    • Strategy allows one of a family of algorithms to be selected on-the-fly at runtime.
    • Template method defines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.
    • Visitor separates an algorithm from an object structure by moving the hierarchy of methods into one object.


back to top


Releases

No releases published

Packages

No packages published