Wednesday, 20 November 2019

Important C# Question and Answers


                    C# Interview Questions
----------------------
QHow will you differentiate between a Class and a Struct?
A: 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.
QCompare Virtual methods and Abstract methods.
A: 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.
QWhat are Namespaces in C#?
A: 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.
QWhat are I/O classes in C#? Define some of the most commonly used ones.
A: 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
QWhat do you understand by regular expressions in C#? Write a program that searches a string using regular expressions.
A: 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 using Regex:
static void Main(strong[] args)
{
string[] languages = {“C#”, “Python”, “Java”};
foreach(string s in languages)
{
if(System.Text.RegularExpressions.Regex.IsMatch(s,“C#”))
{
Console.WriteLine(“Match found”);
}
}
}
QGive a detailed explanation of Delegates in C#.
A: Delegates are variables that hold references to methods. It is a function pointer or reference type. Both the Delegate and the method to which it refers can have the same signature. All Delegates derives from the
System.Delegate namespace.
Following example demonstrates declaring a delegate:
public delegate AddNumbers(int n);
After declaring a delegate, the object must be created of the delegate using the new keyword, such as:
AddNumbers an1 = new AddNumbers(number);
The Delegate offers a kind of encapsulation to the reference method, which gets internally called with the calling of the delegate. In the following example, we have a delegate myDel that takes an integer value as a parameter: public delegate int myDel(int number); public class Program { public int AddNumbers(int a) { Int Sum = a + 10; return Sum; } public void Start() { myDel DelgateExample = AddNumbers; } }
QExplain Reflection in C#.
A: 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
QName some of the most common places to look for a Deadlock in C#.
A: 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)
QDefine Serialization and its various types in C#.
A: 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 Serialization – Faster and demands less space; it converts any code into its binary form. Serialize and restore public and non-public properties.
  • SOAP – It 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 Serialization – Serializes 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.
QGive a brief explanation on Thread Pooling in C#.
A: 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.
QIs it possible to use this keyword within a static method in C#?
A: 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.
QWhat's the difference between the System.Array.CopyTo() and System.Array.Clone() ?
Using Clone() method, we creates a new array object containing all the elements in the original Array and using CopyTo() method. All the elements of existing array copies into another existing array. Both methods perform a shallow copy.

What is IsNullOrEmpty() : In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.Empty (A constant for empty strings).
Syntax:
public static bool IsNullOrEmpty(String str) 
Explanation: This method will take a parameter which is of type System.String and this method will returns a boolean value. If the str parameter is null or an empty string (“”) then return True otherwise return False.

Q: What can you tell us about the XSD file in C#?
A: 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.
QWhat do you mean by Constructor Chaining in C#?
A: 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.
QExplain different states of a Thread in C#?
A: 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
QWhy do we use Async and Await in C#?
A: Processes belonging to asynchronous programming run independently of the main or other processes. In C#, using Async and Await keywords for creating asynchronous methods.
QWhat is an Indexer in C#, and how do you create one?
A: Also 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. The general syntax for creating an indexer in C# is:
< modifier > <
return type > this[argument list] {
get {
// the get block code
}
set {
// the set block code
}
}
QWhat is the Race condition in C#?
A: 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.
QWhat do you understand by Get and Set Accessor properties?
A: 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.
QGive a detailed explanation of the differences between ref and out keywords.
A: 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.
  • Initializing a 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.
QWhat is Singleton Design Patterns in C#? Explain their implementation using an example.
A: 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. Following example demonstrates the implementation of Singleton Design Patterns in C#:
namespace Singleton {
class Program {
static void Main(string[] args) {
Calculate.Instance.ValueOne = 10.5;
Calculate.Instance.ValueTwo = 5.5;
Console.WriteLine("Addition : " + Calculate.Instance.Addition());
Console.WriteLine("Subtraction : " + Calculate.Instance.Subtraction());
Console.WriteLine("Multiplication : " + Calculate.Instance.Multiplication());
Console.WriteLine("Division : " + Calculate.Instance.Division());
Console.WriteLine("\n----------------------\n");
Calculate.Instance.ValueTwo = 10.5;
Console.WriteLine("Addition : " + Calculate.Instance.Addition());
Console.WriteLine("Subtraction : " + Calculate.Instance.Subtraction());
Console.WriteLine("Multiplication : " + Calculate.Instance.Multiplication());
Console.WriteLine("Division : " + Calculate.Instance.Division());
Console.ReadLine();
}
}
public sealed class Calculate {
private Calculate() {}
private static Calculate instance = null;
public static Calculate Instance {
get {
if (instance == null) {
instance = new Calculate();
}
return instance;
}
}
public double ValueOne {
get;
set;
}
public double ValueTwo {
get;
set;
}
public double Addition() {
return ValueOne + ValueTwo;
}
public double Subtraction() {
return ValueOne - ValueTwo;
}
public double Multiplication() {
return ValueOne * ValueTwo;
}
public double Division() {
return ValueOne / ValueTwo;
}
}
}
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
Q. What is the output of the short program below? Explain your answer.
class Program {
  static String location;
  static DateTime time;

  static void Main() {
    Console.WriteLine(location == null ? "location is null" : location);
    Console.WriteLine(time == null ? "time is null" : time.ToString());
  }
}
The output will be:
location is null
1/1/0001 12:00:00 AM
Although both variables are uninitialized, String is a reference type and DateTime is a value type. As a value type, an unitialized DateTime variable is set to a default value of midnight of 1/1/1 (yup, that’s the year 1 A.D.), not null.

Q. Can multiple catch blocks be executed?
No, Multiple catch blocks can't be executed. Once the proper catch code executed, the control is transferred to the finally block, and then the code that follows the finally block gets executed.
Q. What is the difference between public, static, and void?
Public declared variables or methods are accessible anywhere in the application. Static declared variables or methods are globally accessible without creating an instance of the class. Static member are by default not globally accessible it depends upon the type of access modified used. The compiler stores the address of the method as the entry point and uses this information to begin execution before any objects are created. And Void is a type modifier that states that the method or variable does not return any value.
Q. What is an object?
An object is an instance of a class through which we access the methods of that class. "New" keyword is used to create an object. A class that creates an object in memory will contain the information about the methods, variables, and behavior of that class.
Q. Define Constructors
A constructor is a member function in a class that has the same name as its class. The constructor is automatically invoked whenever an object class is created. It constructs the values of data members while initializing the class.
Q. What is Jagged Arrays?
The Array which has elements of type array is called jagged Array. The elements can be of different dimensions and sizes. We can also call jagged Array as an Array of arrays.
Q. What is the difference between ref & out parameters?
An argument passed as ref must be initialized before passing to the method whereas out parameter needs not to be initialized before passing to a method.
Q. 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.
Q. What is serialization?
When we want to transport an object through a network, then we have to convert the object into a stream of bytes. The process of converting an object into a stream of bytes is called Serialization. For an object to be serializable, it should implement ISerialize Interface. De-serialization is the reverse process of creating an object from a stream of bytes.
Q. Can we use "this" command within a static method?
We can't use 'This' in a static method because we can only use static variables/methods in a static method.
Q. What is the difference between constants and read-only?
Constant variables are declared and initialized at compile time. The value can't be changed afterward. Read-only is used only when we want to assign the value at run time.
Q.  Can a private virtual method can be overridden?
No, because they are not accessible outside the class.
Q. Describe the accessibility modifier "protected internal".
Protected Internal variables/methods are accessible within the same assembly and also from the classes that are derived from this parent class.
Q. What are the differences between System.String and System.Text.StringBuilder classes?
System.String is immutable. When we modify the value of a string variable, then a new memory is allocated to the new value and the previous memory allocation released. System.StringBuilder was designed to have a concept of a mutable string where a variety of operations can be performed without allocation separate memory location for the modified string.
Q. What's the difference between the System.Array.CopyTo() and System.Array.Clone() ?
Using Clone() method, we creates a new array object containing all the elements in the original Array and using CopyTo() method. All the elements of existing array copies into another existing array. Both methods perform a shallow copy.
Q.  How can we sort the elements of the Array in descending order?
Using Sort() methods followed by Reverse() method.
Q. What is the difference between Finalize() and Dispose() methods?
Dispose() is called when we want for an object to release any unmanaged resources with them. On the other hand, Finalize() is used for the same purpose, but it doesn't assure the garbage collection of an object.
Q. What are circular references?
Circular reference is situation in which two or more resources are interdependent on each other causes the lock condition and make the resources unusable.
Q. What are generics in C#.NET?
Generics are used to make reusable code classes to decrease the code redundancy, increase type safety, and performance. Using generics, we can create collection classes. To create generic collection, System.Collections.Generic namespace should be used instead of classes such as ArrayList in the System.Collections namespace. Generics promotes the usage of parameterized types.
Q. What is an object pool in .NET?
An object pool is a container having objects ready to be used. It tracks the object that is currently in use, total number of objects in the pool. This reduces the overhead of creating and re-creating objects.
Q. List down the commonly used types of exceptions in .net
ArgumentException, ArgumentNullException , ArgumentOutOfRangeException, ArithmeticException, DivideByZeroException ,OverflowException , IndexOutOfRangeException ,InvalidCastException ,InvalidOperationException , IOEndOfStreamException , NullReferenceException , OutOfMemoryException , StackOverflowException etc.
Q. What are Custom Exceptions?
Sometimes there are some errors that need to be handled as per user requirements. Custom exceptions are used for them and are used defined exceptions.
Q. What is the difference between method overriding and method overloading?
In method overriding, we change the method definition in the derived class that changes the method behavior. Method overloading is creating a method with the same name within the same class having different signatures.
Q. What are the different ways a method can be overloaded?
Methods can be overloaded using different data types for a parameter, different order of parameters, and different number of parameters.
Q. Why can't you specify the accessibility modifier for methods inside the interface?
In an interface, we have virtual methods that do not have method definition. All the methods are there to be overridden in the derived class. That's why they all are public.
Q. How can we set the class to be inherited, but prevent the method from being over-ridden?
Declare the class as public and make the method sealed to prevent it from being overridden.
Q. What happens if the inherited interfaces have conflicting method names?
Implement is up to you as the method is inside your own class. There might be a problem when the methods from different interfaces expect different data, but as far as compiler cares you're okay.
Q. What is the difference between a Struct and a Class?
Structs are value-type variables, and classes are reference types. Structs stored on the Stack causes additional overhead but faster retrieval. Structs cannot be inherited.
Q. How to use nullable types in .Net?
Value types can take either their normal values or a null value. Such types are called nullable types.
Int? someID = null;
If(someID.HasVAlue)
{
}
Q. How we can create an array with non-default values?
We can create an array with non-default values using Enumerable.Repeat.
Q. What is difference between "is" and "as" operators in c#?
"is" operator is used to check the compatibility of an object with a given type, and it returns the result as Boolean.
"as" operator is used for casting of an object to a type or a class.
Q. What are indexers in C# .NET?
Indexers are known as smart arrays in C#. It allows the instances of a class to be indexed in the same way as an array.
Eg:
public int this[int index]    // Indexer declaration
Q. What is difference between the "throw" and "throw ex" in .NET?
"Throw" statement preserves original error stack whereas "throw ex" have the stack trace from their throw point. It is always advised to use "throw" because it provides more accurate error information.
Q. What are C# attributes and its significance?
C# provides developers a way to define declarative tags on certain entities, eg. Class, method, etc. are called attributes. The attribute's information can be retrieved at runtime using Reflection.
Q. What is the difference between directcast and ctype?
DirectCast is used to convert the type of object that requires the run-time type to be the same as the specified type in DirectCast.
Ctype is used for conversion where the conversion is defined between the expression and the type.





No comments:

Post a Comment

Baisic Useful Git Commands

  Pushing a fresh repository Create a fresh repository(Any cloud repository). Open terminal (for mac ) and command (windows) and type the be...