C# Questions and Answers For Freshers and Experienced

27595
C# Questions and Answers
C# Questions and Answers

C# Questions and Answers For Freshers and Experienced

We have discussed C# Questions and Answers. C# is a general purpose programming language that encompasses various disciplines like object-oriented programming, static typing, component-oriented programming, strong typing, etc. It is widely used in the ASP.NET framework for creating websites, web applications and games. There are vast opportunities for C# programming all over the world. If you are thinking to build a career in C# programming, you need to crack an interview in which you will be asked several C# interview questions and answers as listed below.

Frequently Asked C# Interview Questions and Answers for Freshers and Experienced

#1 What is C#?

C# is a simple, modern, general purpose programming language. It is an object oriented programming language developed by Microsoft. It is a safe and managed language that is compiled by .NET framework to generate Microsoft intermediate language (machine code).

#2  What are constructors in C#?

A constructor is a member function in the class and has the same name as its class. Whenever the object class is created, the constructor is automatically invoked. It constructs the value of data members while initializing the class.

#3 What is an object in C#? 

C# language is an object-oriented programming language. Classes are the foundation of C#. A class is a template that defines what a data structure will look like, and how data will be stored, managed, and transferred. A class has fields, properties, methods, and other members.

While classes are concepts, objects are real. Objects are created using class instances. A class defines the type of an object. Objects store real values in computer memory.

Any real-world entity which has some certain characteristics or that can perform some work is called an Object. This object is also called an instance, i.e. a copy of an entity in a programming language. Objects are instances of classes. 

For example, we need to create a program that deals with cars. We need to create an entity for the car. Let’s call it a class, Car. A car has four properties, i.e., model, type, color, and size. This is most asked C# Questions and Answers

 #4 What is the difference between method overloading and method overriding in C#?

Method parameters must be different in method overloading whereas it must be same in method overriding.

Inheritance is not required in method overloading, it occurs within the same class. But inheritance is required in method overriding.

#5 What is the difference between a struct and a class in C#? 

Class and struct are both user-defined data types, but have some major differences:

Struct

  • The struct is a value type in C# and it inherits from System.Value Type.
  • Struct is usually used for smaller amounts of data.
  • Struct can’t be inherited from other types.
  • A structure can’t be abstract.
  • No need to create an object with a new keyword.
  • Do not have permission to create any default constructor.

Class

  • The class is a reference type in C# and it inherits from the System.Object Type.
  • Classes are usually used for large amounts of data.
  • Classes can be inherited from other classes.
  • A class can be an abstract type.
  • We can create a default constructor.

#6 What is the difference between dispose() and finalize() methods in C#?

The dispose() method is explicitly called by user to free unmanaged resources such as files, database connections etc whereas finalize() method is implicitly called by garbage collector to free unmanaged resources like files, database connections etc.

The dispose() method belongs to IDisposable interface whereas finalize() method belongs the Object class. This is most asked C# Questions and Answers

#7  Which are the access modifiers available in C#?

Following are the access modifiers generally used for accessibility:

  • Public: If you define an attribute or method as public, it can be accessed from any code of the project.
  • Private: A private defined attribute or method can be accessed by any code within the containing class only.
  • Protected: If you define the method or attribute as protected it can be accessed by any method in the inherited classes and any method within the same class.
  • Internal: If you define an attribute or a method as internal, it is restricted to classes within the current position assembly.
  • Protected internal: If you define an attribute or method as protected internal, access is restricted to classes within the current project assembly or types derived from the containing class.

#8 What is enum in C#? 

An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data type that is user-defined.

An enum type can be an integer (float, int, byte, double, etc.). But if you use it beside int it has to be cast.

An enum is used to create numeric constants in the .NET framework. All the members of enum are enum type. There must be a numeric value for each enum type.

The default underlying type of the enumeration element is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. 

enum Dow {Sat, Sun, Mon, Tue, Wed, Thu, Fri};    

Some points about enum,

  • 1. Enums are enumerated data types in c#.
  • 2. Enums are not for the end-user, they are meant for developers.
  • 3. Enums are strongly typed constant. They are strongly typed, i.e. an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members is the same.
  • 4. Enumerations(enums) make your code much more readable and understandable.
  • 5. Enum values are fixed. Enum can be displayed as a string and processed as an integer.
  • 6. The default type is int, and the approved types are byte, sbyte, short, ushort, uint, long, and ulong.
  • 7. Every enum type automatically derives from System.Enum and thus we can use System.Enum methods on enums.
  • 8. Enums are value types and are created on the stack and not on the heap.

#9 How to declare a property in a class?

 int m_PersonID = 0;  
public int PersonID  
{  
get { return m_PersonID; }  
set { m_PersonID = value; }  
}  

#10 What is the lock statement in C#?

Lock statement is used to ensure that one thread doesn?t enter a critical section of code while another thread is in the critical section. If another thread attempts to enter a locked code it will wait, block, until the object is released.

#11  What is method overloading in C#?

Method overloading is mechanism to create multiple methods with the same name and unique signature in the same class. When you go for compilation, the compiler uses overload resolution to determine the specific method to be invoked.

#12 What are the different types of constructors in C#?

Basically, there are five types of constructors:

  • Static constructor
  • Private constructor
  • Copy constructor
  • Default constructor
  • Parameterized constructor

#13 What is the difference between late binding and early binding in C#?

Early Binding and Late Binding concepts belong to polymorphism in C#. Polymorphism is the feature of object-oriented programming that allows a language to use the same name in different forms. For example, a method named Add can add integers, doubles, and decimals.

Polymorphism we have 2 different types to achieve that: 

  • Compile Time also known as Early Binding or Overloading.
  • Run Time is also known as Late Binding or Overriding.

Compile Time Polymorphism or Early Binding

In Compile time polymorphism or Early Binding, we will use multiple methods with the same name but different types of parameters, or maybe the number of parameters. Because of this, we can perform different-different tasks with the same method name in the same class which is also known as Method overloading. This is most asked C# Questions and Answers

Run Time Polymorphism or Late Binding 

Run time polymorphism is also known as late binding. In Run Time Polymorphism or Late Binding, we can use the same method names with the same signatures, which means the same type or the same number of parameters, but not in the same class because the compiler doesn’t allow for that at compile time. Therefore, we can use that bind at run time in the derived class when a child class or derived class object will be instantiated. That’s why we call it Late Binding. We have to create my parent class functions as partial and in driver or child class as override functions with the override keyword. 

#14 What is the use of ‘using’ statement in C#?

The ‘using’ block is used to obtain a resource and process it and then automatically dispose of when the execution of the block completed.

 #15 What are sealed classes in C#?

We create sealed classes when we want to restrict the class to be inherited. Sealed modifier used to prevent derivation from a class. If we forcefully specify a sealed class as base class, then a compile-time error occurs.

#16 What is the difference between dispose() and finalize() methods in C#?

The dispose() method is explicitly called by user to free unmanaged resources such as files, database connections etc whereas finalize() method is implicitly called by garbage collector to free unmanaged resources like files, database connections etc.

The dispose() method belongs to IDisposable interface whereas finalize() method belongs the Object class.

 #17 What is delegate in C#?

A delegate in C# is an object that holds the reference to a method. It is like function pointer in C++.

#18 What is Serialization in C#?

Serialization in C# is the process of converting an object into a stream of bytes to store the object to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

There are three types of serialization,

  1. Binary serialization (Save your object data into binary format).
  2. Soap Serialization (Save your object data into binary format; mainly used in network-related communication).
  3. XmlSerialization (Save your object data into an XML file).

#19 What is Boxing and Unboxing in C#? 

Boxing and Unboxing both are used for type conversions. 

The process of converting from a value type to a reference type is called boxing. Boxing is an implicit conversion. Here is an example of boxing in C#.

 // Boxing  
int anum = 123;  
Object obj = anum;  
Console.WriteLine(anum);  
Console.WriteLine(obj); 

The process of converting from a reference type to a value type is called unboxing. Here is an example of unboxing in C#.

 // Unboxing  
Object obj2 = 123;  
int anum2 = (int)obj;  
Console.WriteLine(anum2);  
Console.WriteLine(obj);  

#20 Difference between Throw Exception and Throw Clause 

The basic difference is that the Throw exception overwrites the stack trace. This makes it hard to find the original code line number that has thrown the exception.

Throw basically retains the stack information and adds to the stack information in the exception that it is thrown.

Let’s see what it means to better understand the differences. I am using a console application to easily test and see how the usage of the two differ in their functionality.

 using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
namespace TestingThrowExceptions {  
    class Program {  
        public void ExceptionMethod() {  
            throw new Exception("Original Exception occurred in ExceptionMethod");  
        }  
        static void Main(string[] args) {  
            Program p = new Program();  
            try {  
                p.ExceptionMethod();  
            } catch (Exception ex) {  
                throw ex;  
            }  
        }  
    }  
}  

#21 What are the different types of classes in C#?

Answer: The different types of class in C# are:

  • Partial class: It allows its members to be divided or shared with multiple .cs files. It is denoted by the keyword Partial.
  • Sealed class: It is a class that cannot be inherited. To access the members of a sealed class, we need to create the object of the class.  It is denoted by the keyword Sealed.
  • Abstract class: It is a class whose object cannot be instantiated. The class can only be inherited. It should contain at least one method.  It is denoted by the keyword abstract.
  • Static class: It is a class that does not allow inheritance. The members of the class are also static.  It is denoted by the keyword static. This keyword tells the compiler to check for any accidental instances of the static class.

#22 What are the different types of classes in C#?

The different types of class in C# are:

  • Partial class: It allows its members to be divided or shared with multiple .cs files. It is denoted by the keyword Partial.
  • Sealed class: It is a class that cannot be inherited. To access the members of a sealed class, we need to create the object of the class.  It is denoted by the keyword Sealed.
  • Abstract class: It is a class whose object cannot be instantiated. The class can only be inherited. It should contain at least one method.  It is denoted by the keyword abstract.
  • Static class: It is a class that does not allow inheritance. The members of the class are also static.  It is denoted by the keyword static. This keyword tells the compiler to check for any accidental instances of the static class.

#23 Explain Namespaces in C#.

Answer: They are used to organize large code projects. “System” is the most widely used namespace in C#. We can create our own namespace and can also use one namespace in another, which is called Nested Namespaces.

They are denoted by the keyword “namespace”.

#24 How is Exception Handling implemented in C#?

Answer: 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 the exception handler.
  • finally: It is a block of code written to execute regardless of whether an exception is caught or not.
  • Throw: Throws an exception when a problem occurs.

#25 What are C# I/O classes? What are the commonly used I/O classes?

Answer: 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 the path information.

#26 What is a Destructor in C#?

Answer: 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.

For Example:

 ~Car()
{
Console.writeline(“….”);
}

#27 What is Reflection in C#?

Answer: 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.

#28 What are the main reasons to use C# language?

These are top reasons to use C# language:

  • Easy to learn
  • General purpose and object oriented programming language
  • Component oriented
  • Structured language
  • Can be compiled on variety of computer platforms
  • Produces efficient programs
  • Part of .net framework

#29 Distinguish between finally and finalize blocks?

Ans- 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. This is an Important C# Questions and Answers

#30 Define sealed classes in C#?

You create sealed classes in situations when you want to restrict the class to be inherited. For doing this sealed modifiers are used. If you forcefully specify a sealed class as a base class then a compilation error occurs.

Check out the Latest Jobs for C# Developer: Link

Join WhatsApp and Telegram groups for daily job updates: Link

Prepare for Technical Round with Interview Questions: Link

Get insights into HR Interview Questions: Link

Craft a standout resume for Quick shortlisting: Link

Assessment with a Mock Test: Link

Colgate Mock Test with Aptitude and Coding Assessment: Click Here

Understand Colgate Recruitment Process, Test, and Exam Pattern: Link

Explore Global Opportunities for Professionals & Freshers Abroad: Link

TCS NQT 2023 Careers: Graduate Trainee Hiring: Link 

PwC Internships 2023: Opportunities in Zurich, Switzerland: Link

Chandrayaan 3: India’s Upcoming Lunar Mission Expectations: Link