C# Programming Language Technical Interview Questions Answers

C# Programming Language

Technical Interview Questions Answers

What is C#?

C# is a modern, general-purpose, object-oriented programming language developed by Microsoft. C# is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime environment that allows the use of various high-level languages on different computer platforms and architectures.


How will you differentiate between a Class and a Struct?

Although both class and structure are user-defined data types, they are different in several fundamental ways. A class is a reference type and stores on the heap. Struct, on the other hand, is a value type and is, therefore, stored on the stack. While the structure doesn’t support inheritance and polymorphism, the class provides support for both. A class can be of an abstract type, but a structure can’t. All members of a class are private by default, while members of a struct are public by default. Another distinction between class and struct is based on memory management. The former supports garbage collection while the latter doesn’t.


Compare Virtual methods and Abstract methods.

Any Virtual method must have a default implementation, and it can be overridden in the derived class using the override keyword. On the contrary, an Abstract method doesn’t have an implementation, and it resides in the abstract class. The derived class must implement the abstract method. Though not necessary, we can use an override keyword here.


What are Namespaces in C#?

Use of namespaces is for organizing large code projects. The most widely used namespace in C# is System. Namespaces are created using the namespace keyword. It is possible to use one namespace in another, known as Nested Namespaces.


What are I/O classes in C#? Define some of the most commonly used ones.

The System.IO namespace in C# consists of several classes used for performing various file operations, such as creation, deletion, closing, and opening. Some of the most frequently used I/O classes in C# are:

File – Manipulates a file
Path – Performs operations related to some path information
StreamReader – Reads characters from a stream
StreamWriter – Writes characters to a stream
StringReader – Reads a string buffer
StringWriter – Writes a string buffer


What do you understand by regular expressions in C#? Write a program that searches a string using regular expressions.

Regular expression is a template for matching a set of input. It can consist of constructs, character literals, and operators. Regex is used for string parsing, as well as replacing the character string. Following code searches a string “C#” against the set of inputs from the languages array.


Explain Reflection

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 behavior
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.


Name some of the most common places to look for a Deadlock in C#.

For recognizing deadlocks, one should look for threads that get stuck on one of the following:

.Result, .GetAwaiter().GetResult(), WaitAll(), and WaitAny() (When working with Tasks)
Dispatcher.Invoke() (When working in WPF)
Join() (When working with Threads)
lock statements (In all cases)
WaitOne() methods (When working with AutoResetEvent/EventWaitHandle/Mutex/Semaphore)


Define Serialization and its various types in C#.

The process of converting some code into its binary format is known as Serialization in C#. Doing so allows the code to be stored easily and written to a disk or some other storage device. We use Serialization when there is a strict need for not losing the original form of the code. A class marked with the attribute [Serializable] gets converted to its binary form. A stream that contains the serialized object and the System.Runtime.Serialization namespace can have classes for serialization. Serialization in C# is of three types:

Binary SerializationFaster and demands less space; it converts any code into its binary form. Serialize and restore public and non-public properties.


SOAPIt produces a complete SOAP compliant envelope that is usable by any system capable of understanding SOAP. The classes about this type of serialization reside in System.Runtime.Serialization.


XML SerializationSerializes all the public properties to the XML document. In addition to being easy to read, the XML document manipulated in several formats. The classes in this type of serialization reside in System.sml.Serialization.


Note: - Retrieving the C# code back from the binary form is known as Deserialization.


Explanation on Thread Pooling in C#

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.


Is it possible to use this keyword within a static method in C#?

A special type of reference variable, this keyword is implicitly defined with each non-static method and constructor as the first parameter of the type class, which defines it. Static methods don’t belong to a particular instance. Instead, they exist without creating an instance of the class and calls with the name of the class. Because this keyword returns a reference to the current instance of the class containing it, it can’t be used in a static method. Although we can’t use this keyword within a static method, we can use it in the function parameters of Extension Methods.


What can you tell us about the XSD file in C#?

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.


What do you mean by Constructor Chaining in C#?

Constructor chaining in C# is a way of connecting two or more classes in a relationship as an inheritance. Every child class constructor is mapped to the parent class constructor implicitly by using the base keyword in constructor chaining.


Explain different states of a Thread in C#?

A thread in C# can have any of the following states:

Aborted – The thread is dead but not stopped
Running – The thread is executing
Stopped – The thread has stopped execution
Suspended – The thread has been suspended
Unstarted – The thread is created but has not started execution yet
WaitSleepJoin – The thread calls sleep, calls wait on another object, and calls join on some other thread.



Why do we use Async and Await in C#?

Processes belonging to asynchronous programming run independently of the main or other processes. In C#, using Async and Await keywords for creating asynchronous methods.


What is an Indexer in C#, and how do you create one?

known as an indexed property, an indexer is a class property allowing accessing a member variable of some class using features of an array. Used for treating an object as an array, indexer allows using classes more intuitively. Although not an essential part of the object-oriented programming, indexers are a smart way of using arrays. As such, they are also called smart arrays. Defining an indexer enables creating classes that act like virtual arrays. Instances of such classes can be accessed using the [] array access operator.


What is the Race condition in C#?

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.


What do you understand by Get and Set Accessor properties?

Made using properties, Get and Set are called accessors in C#. A property enables reading and writing to the value of a private field. Accessors are used for accessing such private fields. While we use the Get property for returning the value of a property, use the Set property for setting the value.


Give a detailed explanation of the differences between ref and out keywords.

In any C# function, there can be three types of parameters, namely in, out and ref. Although both out and ref are treated differently at the run time, they receive the same treatment during the compile time. It is not possible to pass properties as an out or ref parameter. Following are the differences between ref and out keywords:

Initializing the Argument or Parameter – While it is not compulsory to initialize an argument or parameter before passing to an out parameter, the same needs to be initialized before passing it to the ref parameter.
Initializing the Value of the Parameter – Using ref doesn’t necessitate for assigning or initializing the value of a parameter before returning to the calling method. When using out, however, it is mandatory to use a called method for assigning or initializing a value of a parameter before returning to the calling method.
Usefulness – When the called method requires modifying the passed parameter, passing a parameter value by Ref is useful. Declaring a parameter to an out method is appropriate when multiple values are required to be returned from a function or method. Initializinga Parameter Value in Calling

Method – It is a compulsion to initialize a parameter value within the calling method while using out. However, the same is optional while using the ref parameter.

Data Passing – Using out allows for passing data only in a unidirectional way. However, data can be passed in a bidirectional manner when using ref.


What is Singleton Design Patterns in C#? Explain their implementation using an example.

A singleton in C# is a class that allows the creation of only a single instance of itself and provides simple access to that sole instance. Because the second request of an instance with a different parameter can cause problems, singletons typically disallow any parameters to be specified.

A Singleton Design Pattern ensures that a class has one and only one instance and provides a global point of access to the same. There are numerous ways of implementing the Singleton Design Patterns in C#. Following are the typical characteristics of a Singleton Pattern:

A public static means of getting the reference to the single instance created
A single constructor, private and parameter-less
A static variable holding a reference to the single instance created
The class is sealed


Explain Code compilation in C#.

There are four steps in code compilation which include:

Compiling the source code into Managed code by C# compiler.
Combining the newly created code into assemblies.
Loading the Common Language Runtime(CLR).
Executing the assembly by CLR.


Explain Abstraction.

Abstraction is one of the OOP concepts. It is used to display only the essential features of the class and hides the unnecessary information.

Let us take an Example of a Car:

A driver of the car should know the details about the Car such as color, name, mirror, steering, gear, brake, etc. What he doesn't have to know is an Internal engine, Exhaust system.

So, Abstraction helps in knowing what is necessary and hiding the internal details from the outside world. Hiding of the internal information can be achieved by declaring such parameters as Private using the private keyword.


Explain Polymorphism?

Programmatically, Polymorphism means same method but different implementations.

It is of 2 types, Compile-time and Runtime.

Compile time polymorphism is achieved by operator overloading.

Runtime polymorphism is achieved by overriding. Inheritance and Virtual functions are used during Runtime Polymorphism.

For Example, If a class has a method Void Add(), polymorphism is achieved by Overloading the method, that is, void Add(int a, int b), void Add(int add) are all overloaded methods.


How is Exception Handling implemented in C#?

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


What are C# I/O Classes? What are the commonly used I/O Classes?

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 path information.



What is a Destructor in C#?

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. But sometimes it may be necessary to implement destructors manually.


What is an Abstract Class?

An Abstract class is a class which is denoted by abstract keyword and can be used only as a Base class. An Abstract class should always be inherited. An instance of the class itself cannot be created. If we do not want any program to create an object of a class, then such classes can be made abstract.

Any method in the abstract class does not have implementations in the same class. But they must be implemented in the child class.


What is the difference between Continue and Break Statement?

Break statement breaks the loop. It makes the control of the program to exit the loop. Continue statement makes the control of the program to exit only the current iteration. It does not break the loop.


What is the difference between finally and finalize block?

inally 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 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.


What is a Jagged Array?

A Jagged array is an array whose elements are arrays. It is also called as the array of arrays. It can be either single or multiple dimensions.

int[] jaggedArray = new int[4][];


What is a String? What are the properties of a String Class?

A String is a collection of char objects. We can also declare string variables in c#.

string name = “Hello World”;

A string class in C# represents a string.

The properties of String class are Chars and Length.
Chars get the Char object in the current String.
Length gets the number of objects in the current String.


What is an Escape Sequence? Name some String escape sequences in C#.

An Escape sequence is denoted by a backslash (\). The backslash indicates that the character that follows it should be interpreted literally or it is a special character. An escape sequence is considered as a single character.

String escape sequences are as follows:

\n – Newline character
\b – Backspace
\\ – Backslash
\’ – Single quote
\’’ – Double Quote


What are Regular expressions? Search a string using regular expressions?

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.


What are the basic String Operations? Explain.

Some of the basic string operations are:

ConcatenateTwo strings can be concatenated either by using System.String.Concat or by using + operator.


ModifyReplace(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 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.


What are Synchronous and Asynchronous operations?

Synchronization is a way to create a thread-safe code where only one thread can access the resource at any given time.

Asynchronous call waits for the method to complete before continuing with the program flow. Synchronous programming badly affects the UI operations, when the user tries to perform time-consuming operations since only one thread will be used.

In Asynchronous operation, the method call will immediately return so that the program can perform other operations while the called method completes its work in certain situations.

In C#, Async and Await keywords are used to achieve asynchronous programming.


What is Reflection in C#?

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.

The MemberInfo object of the class reflection is used to discover the attributes associated with a class.

Reflection is implemented in two steps, first, we get the type of the object, and then we use the type to identify members such as methods and properties.

To get type of a class, we can simply use

Type mytype = myClass.GetType();

Once we have a type of class, the other information of the class can be easily accessed.

System.Reflection.MemberInfo Info = mytype.GetMethod(“AddNumbers”);

Above statement tries to find a method with name AddNumbers in the class myClass.


Explain Get and Set Accessor properties?

Get and Set are called Accessors. These are made use by Properties. A property provides a mechanism to read, write the value of a private field. For accessing that private field, these accessors are used.

Get Property is used to return the value of a property
Set Property accessor is used to set the value.

What is a Thread? What is Multithreading?

A Thread is a set of instructions that can be executed, which will enable our program to perform concurrent processing. Concurrent processing helps us do more than one operation at a time. By default, C# has only one thread. But the other threads can be created to execute the code in parallel with the original thread.

Thread has a life cycle. It starts whenever a thread class is created and is terminated after the execution. System.Threading is the namespace which needs to be included to create threads and use its members.

Threads are created by extending the Thread Class. Start() method is used to begin thread execution.

//CallThread is the target method// ThreadStart methodThread = new ThreadStart(CallThread);
Thread childThread = new Thread(methodThread);
childThread.Start();
C# can execute more than one task at a time. This is done by handling different processes by different threads. This is called MultiThreading.

There are several thread methods that are used to handle the multi-threaded operations:

Start, Sleep, Abort, Suspend, Resume and Join.

Most of these methods are self-explanatory.

What are Async and Await?

Async and Await keywords are used to create asynchronous methods in C.

Asynchronous programming means that the process runs independently of main or other processes.
Async keyword is used for the method declaration.
The count is of a task of type int which calls the method CalculateCount().
Calculatecount() starts execution and calculates something.
Independent work is done on my thread and then await count statement is reached.
If the Calculatecount is not finished, myMethod will return to its calling method, thus the main thread doesn’t get blocked.
If the Calculatecount is already finished, then we have the result available when the control reaches await count. So the next step will continue in the same thread. However, it is not the situation in the above case where Delay of 1 second is involved.

What is a Deadlock?

A Deadlock is a situation where a process is not able to complete its execution because two or more processes are waiting for each other to finish. This usually occurs in multi-threading.

Here a Shared resource is being held by a process and another process is waiting for the first process to release it and the thread holding the locked item is waiting for another process to complete.

Explain Lock, Monitors, and Mutex Object in Threading.

Lock keyword ensures that only one thread can enter a particular section of the code at any given time. In the above Example, lock(ObjA) means the lock is placed on ObjA until this process releases it, no other thread can access ObjA.

A Mutex is also like a lock but it can work across multiple processes at a time. WaitOne() is used to lock and ReleaseMutex() is used to release the lock. But Mutex is slower than lock as it takes time to acquire and release it.

Monitor.Enter and Monitor.Exit implements lock internally. a lock is a shortcut for Monitors. lock(objA) internally calls.

What is a Race Condition?

A 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.

What is Thread Pooling?

A 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 which manage the threads in the pool and its operations.

What is Serialization?

Serialization is a process of converting a 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 which can contain the serialized object and namespace System.Runtime.Serialization can contain classes for serialization.

What are the types of Serialization?

The different types of Serialization are: XML serialization, SOAP, and Binary.

XML serialization – It serializes all the public properties to the XML document. Since the data is in XML format, it can be easily read and manipulated in various formats. The classes reside in System.sml.Serialization.
SOAP – Classes reside in System.Runtime.Serialization. Similar to XML but produces a complete SOAP compliant envelope which can be used by any system that understands SOAP.
Binary Serialization – Allows any code to be converted to its binary form. Can serialize and restore public and non-public properties. It is faster and occupies less space.

What is an XSD file?

An XSD file stands for XML Schema Definition. It gives a structure for the XML file. It means it decides the elements that the XML should have and in what order and what properties should be present. Without an XSD file associated with XML, the XML can have any tags, any attributes, and any elements.

Xsd.exe tool converts the files to XSD format. During Serialization of C# code, the classes are converted to XSD compliant format by xsd.exe.

What is Jagged Array in C#?

You can initialize a jagged array as − int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}}; Where, scores is an array of two arrays of integers - scores[0] is an array of 3 integers and scores[1] is an array of 4 integers.

In how many ways you can pass parameters to a method?

There are three ways that parameters can be passed to a method −

Value parameters − This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

Reference parameters − This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument.

Output parameters − This method helps in returning more than one value.


Can you return multiple values from a function in C#?

Yes! Using output parameters. A return statement can be used for returning only one value from a function. However, using output parameters, you can return two values from a function.

What is the difference between ref and out parameters?

Output parameters are similar to reference parameters, except that they transfer data out of the method rather than into it. Reference parameter copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument.

What is namespace in C#?

A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another.

What is the purpose of using statement in C#?

"using" keyword is used to include a namespace in the program. A program generally has multiple using statements.

What are value types in C#?

Value type variables can be assigned a value directly. They are derived from the class System.ValueType. The value types directly contain data. Some examples are int, char, and float, which stores numbers, alphabets, and floating point numbers, respectively. When you declare an int type, the system allocates memory to store the value.

What are reference types in C#?

The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables. In other words, they refer to a memory location. Using multiple variables, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. Example of built-in reference types are: object, dynamic, and string.

Which class acts as a base class for all the data types in .net?

The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. However, before assigning values, it needs type conversion.

What is boxing in C#?

When a value type is converted to object type, it is called boxing.

What is unboxing in C#?

When an object type is converted to a value type, it is called unboxing.

What are dynamic type variables in C#?

You can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time. Syntax for declaring a dynamic type is − dynamic <variable_name> = value; For example, dynamic d = 20;

What is the difference between dynamic type variables and object type variables?

Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at run time.

What are pointer types in C#?

Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as the pointers in C or C++. Syntax for declaring a pointer type is − type* identifier; For example char* cptr; int* iptr;

What is the purpose of is operator in C#?

is operator determines whether an object is of a certain type. If( Ford is Car) // checks if Ford is an object of the Car class.


What is the purpose of as operator in C#?

as operator casts without raising an exception if the cast fails. Object obj = new StringReader("Hello"); StringReader r = obj as StringReader;

What is encapsulation?

Encapsulation is defined 'as the process of enclosing one or more items within a physical or logical package'. Encapsulation, in object oriented programming methodology, prevents access to implementation details.

How encapsulation is implemented in C#?

Encapsulation is implemented by using access specifiers.

What is the purpose of an access specifier in C#?

An access specifier defines the scope and visibility of a class member.

What is scope of a public member variable of a C# class?

Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class.

What is scope of a private member variable of a C# class?

Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.

What is scope of a protected member variable of a C# class?

Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing inheritance.

What is scope of a Internal member variable of a C# class?

Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly. In other words, any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined.

What is scope of a Protected Internal member variable of a C# class?

The protected internal access specifier allows a class to hide its member variables and member functions from other class objects and functions, except a child class within the same application. This is also used while implementing inheritance.

What are nullable types in C#?

C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values. For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32> variable. Similarly, you can assign true, false, or null in a Nullable<bool> variable.

What is the use of Null Coalescing Operator (??) in C#?

The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible. If the value of the first operand is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand.

Can you create a function in C# which can accept varying number of arguments?

By using the params keyword, a method parameter can be specified which takes a variable number of arguments or even no argument.

Can you pass additional type of parameters after using params in function definition?

No! additional parameters are not permitted after the params keyword in a method declaration. Only one params keyword is allowed in a method declaration.

Which class acts as a base class for all arrays in C#?

The Array class is the base class for all the arrays in C#. It is defined in the System namespace. The Array class provides various properties and methods to work with arrays.

How to sort an array in C#?

Using Array.sort(array) function. It sorts the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array.

How to sort an array in C# in descending order?

First sort the array using Array.sort(array) then reverse the same using Array.reverse(array) method.

What is a structure in C#?

In C#, a structure is a value type data type. It helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure. Structures are used to represent a record. To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program.

What are the differences between a class and structure?

classes are reference types and structs are value types. structures do not support inheritance. structures cannot have default constructor.

What is a enumeration in C#?

An enumeration is a set of named integer constants. An enumerated type is declared using the enum keyword. C# enumerations are value data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance.

What is the default access for a class?

Default access specifier for a class type is internal.

What is the default access for a class member?

Default access for the members is private.

What is inheritance?

One of the most important concepts in object-oriented programming is inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time. When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class. The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal, dog IS-A mammal hence dog IS-A animal as well, and so on.

Is multiple inheritance supported in C#?

No! C# does not support multiple inheritance.

How to inherit a class in C#?

A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces. The syntax used in C# for creating derived classes is as follows − <acess-specifier> class <base_class> { ... } class <derived_class> : <base_class> { ... }

What is polymorphism?

The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'.

What is the difference between static polymorphism and dynamic polymorphism?

Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time.

How C# supports static polymorphism?

C# provides two techniques to implement static polymorphism. They are − Function overloading Operator overloading

What is early binding?

The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding.

What is function overloading?

You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type.

How C# supports dynamic polymorphism?

Dynamic polymorphism is implemented by abstract classes and virtual functions.

What is a sealed class in C#?

When a class is declared sealed, it cannot be inherited.

How will you create sealed abstract class in C#?

No! It can not be created as abstract classes cannot be declared sealed.

What are virtual functions in C#?

When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime.

Is operator overloading supported in C#?

You can redefine or overload most of the built-in operators available in C#. Thus a programmer can use operators with user-defined types as well. Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. Similar to any other function, an overloaded operator has a return type and a parameter list.

What is an interface?

n interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract. Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow.

What is a preprocessor directives in C#?

The preprocessor directives give instruction to the compiler to preprocess the information before actual compilation starts. All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not statements, so they do not end with a semicolon (;).

What is the use of conditional preprocessor directive in C#?

You can use the #if directive to create a conditional directive. Conditional directives are useful for testing a symbol or symbols to check if they evaluate to be true. If they do evaluate to true, the compiler evaluates all the code between the #if and the next directive.

Which class acts as a base class for all exceptions in C#?

C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes.

What is the difference between System.ApplicationException class and System.SystemException class?

The System.ApplicationException class supports exceptions generated by application programs. Hence the exceptions defined by the programmers should derive from this class. The System.SystemException class is the base class for all predefined system exception.
Previous Post Next Post