MYSQL Interview Questions for Freshers

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

MYSQL Interview Questions for Freshers

Question 1.
What is c#?
Answer:
C# is an object-oriented, type-safe, and managed language that is compiled by the .Net framework to generate Microsoft Intermediate Language.

Question 2.
Explain types of comments in C# with examples
Answer:

Single line 


Example:


//This is a single line comment


ii. Multiple line (/* */)


Example:


/*This is a multiple line comment


We are in line 2


Last line of comment*/


iii. XML Comments (///).


Eg: 


/// summary;


/// Set error message for multilingual language.


/// summary

Question 3.
Can multiple catch blocks be executed?
Answer:
No, Multiple catch blocks can’t be executed. Once the proper catch code is executed, the control is transferred to the final block, and then the code that follows the final block gets executed.

Question 4.
What is the difference between public, static, and void?
Answer:
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 members 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.

Question 5.
What is an object?
Answer:
An object is an instance of a class through which we access the methods of that class. The “New” keyword is used to create an object. A class that creates an object in memory will contain information about the methods, variables, and behavior of that class.

Question 6.
What is a Class?
Answer:
A Class is an encapsulation of properties and methods that are used to represent a real¬time entity. It is a data structure that brings all the instances together in a single unit.

Question 7.
Define Constructors.
Answer:
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.

Question 8.
What is the difference between ref & out parameters?
Answer:
An argument passed as ref must be initialized before passing to the method whereas out parameter needs not be initialized before passing to a method.

Question 9.
What is the use of the ‘using’ statement in C#?
Answer:
The ‘using’ block is used to obtain a resource and process it is then automatically disposed of when the execution of the block is completed.

Question 10.
Can we use the “this” command within a static method?
Answer:
We can’t use ‘This’ in a static method because we can only use static variables/methods in a static method.

Question 11.
What is the difference between constants and read-only?
Answer:
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.

Question 12.
What is an interface class? Give one example of it
Answer:
An Interface is an abstract class that has only public abstract methods, and the methods only have the declaration and not the definition. These abstract methods must be implemented in the inherited classes.

using System;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;
namespace DemoApplication 
{
interface Guru99lnterface
{
void SetTutorial(int pID, string pName);
String GetTutorial( );
}
class Guru99Tutorial: Guru99lnterface
{
protected int TutoriallD;
protected string TutorialName;

public void SetTutorial(int pID, string pName)
{
TutoriallD = pID;
TutorialName = pName;
}

public String GetTutorial( )
{
return TutorialName;
}
static void Main(string[ ] args)
{
Guru99Tutorial pTutor = new Guru99Tutorial( );

pTutor.SetTutorial(l,".Net by Guru99");

Console. WriteLine(pTutor.GetTutorial());

Console.ReadKey( );
}
}
}

Question 13.
The basis of comparison Between C# Interface vs Abstract Class C# Interface
Answer:
Access Specifier: In C#, Interface cannot have an access specifier for functions. It is public by default.
Implementation: In C#, an interface can only have a signature, not the implementation.
Speed: Interface is comparatively slow.
Instantiate: Interface is absolutely abstract and cannot be instantiated.
Fields: Interface cannot have fields.
Methods: Methods

C# Abstract Class

Access Specifier: In C#, an abstract class can have an access specifier for functions.
Implementation: An abstract class can provide a complete implementation.
Speed: An abstract class is fast.
Instantiate: An abstract class cannot be instantiated.
Fields: An abstract class can have defined fields and constants Methods: An abstract class can have non-abstract methods.
Basic Difference: Interfaces have all the methods having only declaration but no definition. In an abstract class, we can have some concrete methods. In an interface class, all the methods are public. An abstract class may have private methods.

Question 14.
What are value types and reference types?
Answer:
A value type holds a data value within its own memory space. Example

int a = 30;

Reference type stores the address of the object where the value is being stored. It is a pointer to another memory location.

string b = “Hello Guru99!l”;

Question 15.
What are Custom Control and User Control?
Answer:
Custom Controls are controls generated as compiled code (Dlls), those are easier to use and can be added to the toolbox. Developers can drag and drop controls to their web forms. Attributes can, at design time. We can easily add custom controls to Multiple Applications (If Shared Dlls). So, If they are private, then we can copy to dll to the bin directory of the web application and then add references and can use them.

User Controls are very much similar to ASP include files, and are easy to create. User controls can’t be placed in the toolbox and dragged – dropped from it. They have their design and code behind them. The file extension for user controls is ascx.

Question 16.
What are sealed classes in C#?
Answer:
We create sealed classes when we want to restrict the class to be inherited. The sealed modifier used to prevent derivation from a class. If we forcefully specify a sealed class as a base class, then a compile-time error occurs.

Question 17.
What is method overloading?
Answer:
Method overloading is creating multiple methods with the same name with unique signatures in the same class. When we compile, the compiler uses overload resolution to determine the specific method to be invoked.

Question 18.
What is an Array? Give the syntax for a single and multi-dimensional array?
Answer:
An Array is used to store multiple variables of the same type. It is a collection of variables stored in a contiguous memory location.

For Example:

double numbers = new double[10];
int[] score = new int[4] {25,24,23,25};

A single-dimensional array is a linear array where the variables are stored in a single row. The above example is a single-dimensional array.
Arrays can have more than one dimension. Multidimensional arrays are also called rectangular arrays.

For Example. int[,] numbers = new int[3,2] {{1,2} ,{2,3},{3,4}};

Question 19.
Name some properties of Array.
Answer:

Properties of an Array include:

  • Length – Gets the total number of elements in an array.
  • IsFixedSize – Tells whether the array is fixed in size or not.
  • IsReadOnly – Tells whether the array is read-only or not.

Question 20.
What is an Array Class?
Answer:
An Array class is the base class for all arrays. It provides many properties and methods. It is present in the namespace System.

Question 21.
What is the difference between Array and Arraylist?
Answer:
In an array, we can have items of the same type only. The size of the array is fixed when compared. An ArrayList is similar to an array, but it doesn’t have a fixed size.

Question 22.
What are Jagged Arrays?
Answer:
The Array which has elements of type array is called a jagged array. The elements can be of different dimensions and sizes. We can also call a jagged Array an Array of arrays.

Question 23.
Can a private virtual method be overridden?
Answer:
No, because they are not accessible outside the class.

Question 24.
Describe the accessibility modifier “protected internal”.
Answer:
Protected Internal variables/methods are accessible within the same assembly and also from the classes that are derived from this parent class.

Question 25.
What are the differences between System. String and System.Text.StringBuilder classes?
Answer:
System. The 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 allocating separate memory locations for the modified string.

Question 26.
What’s the difference between the System.Array.CopyTo() and System.Array.Clone() ?
Answer:
Using Clone() method, we create a new array object containing all the elements in the original Array and using the CopyToQ method. All the elements of the existing array copy into another existing array. Both methods perform a shallow copy.

Question 27.
How can we sort the elements of the Array in descending order?
Answer:
Using Sort( ) methods followed by reverse( )  method.

Question 28.
Write down the C# syntax to catch an exception ‘
Answer:
To catch an exception, we use try-catch blocks. Catch block can have a parameter of system. Exception type.

Eg:
try {
GetAllData( );
}
catch (Exception ex) {
}

In the above example, we can omit the parameter from the catch statement.

Question 29.
What is the difference between Finalize!) and Dispose!) methods?
Answer:
Dispose( ) is called when we want 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.

Dispose

It is used to free unmanaged resources at any time.
It is called by user code and the class which is implementing dispose method must have to implement an IDisposable interface.
It is implemented by implementing the IDisposable interface Dispose ( ) method.
There are no performance costs associated with Dispose method.

Finalize

It can be used to free unmanaged resources held by an object before that object is destroyed.
It is called by Garbage Collector and cannot be called by user code.
It is implemented with the help of Destructors
There are performance costs associated with Finalize method since it doesn’t clean the memory immediately and is called by GC automatically.

Question 30.
What are circular references?
Answer:
A circular reference is a situation in which two or more resources are interdependent on each other causes the lock condition and make the resources unusable.

Question 31.
What are generics in C#.NET?
Answer:
Generics are used to make reusable code classes to decrease code redundancy, increase type safety, and performance. Using generics, we can create collection classes. To create a generic collection, System.Collections.The generic namespace should be used instead of classes such as ArrayList in the System. Collections namespace. Generics promotes the usage of parameterized types.

Question 32.
What is an object pool in .NET?
Answer:
An object pool is a container having objects ready to be used. It tracks the object that is currently in use, the total number of objects in the pool. This reduces the overhead of creating and re-creating objects.

Question 33.
List down the commonly used types of exceptions in .net
Answer:
ArgumentException, ArgumentNullException, ArgumentOutOfRangeException, ArithmeticException, DivideByZeroException ,OverflowException, IndexOutOfRangeException ,lnvalidCastException JnvalidOperationException, lOEndOfStreamException , NullReferenceException , OutOfMemoryException , StackOverflowException etc.

Question 34. What are Custom Exceptions?
Answer:
Sometimes there are some errors that need to be handled as per user requirements. Custom exceptions are used for them and are used as defined exceptions.

Question 35.
What is a Delegate? Explain.
Answer:
A Delegate is a variable that holds the reference to a method. Hence it is a function pointer or reference type. All Delegates are derived from System. Delegate namespace. Both Delegate and the method that it refers to can have the same signature.
Declaring a delegate: public delegate void AddNumbers(int n);
After the declaration of a delegate, the object must be created of the delegate using the new keyword.
AddNumbers aril = new AddNumbers(number);
The delegate provides a kind of encapsulation to the reference method, which will internally get called when a delegate is called.

1 public delegate int myDel(int number);
2 public class Program
3 {
4 public int AddNumbers(int a)
5{ 
6 int Sum = a + 10;
7 return Sum;
8}
9 public void Start( )
10 {
11 myDel DelgateExample = AddNumbers;
12}
13}

In the above example, we have a delegate myDel which takes an integer value as a parameter. Class Program has a method of the same signature as the delegate, called AddNumbers( ).

If there is another method called Start( ) that creates an object of the delegate, then the object can be assigned to AddNumbers as it has the same signature as that of the delegate.

Question 36.
What are Events?
Answer:
Events are user actions that generate notifications to the application to which it must respond. The user actions can be mouse movements, keypress, and so on.

Programmatically, a class that raises an event is called a publisher and a class that responds/receives the event is called a subscriber. An event should have at least one subscriber else that event is never raised.

Delegates are used to declare Events.

Public delegate void PrintNumbers( );

Event PrintNumbers myEvent;

Question 37.
How to use Delegates with Events?
Answer:
Delegates are used to raise events and handle them. Always a delegate needs to be declared first and then the Events are declared.

Let us see an example:

Consider a class called Patient. Consider two other classes, Insurance, and Bank which requires Death information of the Patient from the patient class. Here, Insurance and Bank are the subscribers and the Patient class becomes the Publisher. It triggers the death event and the other two classes should receive the event.

1 namespace ConsoleApp2
2{
3 public class Patient
4{
5 public delegate void deathlnfo( );//Declaring a Delegate//
public event deathlnfo deathDate;//Declaring the
6
event//
7 public void Death( )
8{
9 deathDate();
10}
11} 
12 public class Insurance
13 {
14 Patient myPat = new Patient();
15 void GetDeathDetails( )
16 {
17 //----------Do Something with the deathDate event----------//
18}
19 void Main( )
21 //--------Subscribe the function GetDeathDetails----------//
22 myPat.deathDate += GetDeathDetails;
23}
24}
25 public class Bank
26 {
27 Patient myPat = new Patient( );
28 void GetPatlnfo ( )
29 {
30 //--------Do Something with the deathDate event--------//
31}
32 void Main( )
33 {
34 //--------Subscribe the function GetPatlnfo----------//
35 myPat.deathDate += GetPatlnfo;
36}
37}
38}

Question 38.
What are the different types of Delegates?
Answer:
The Different Types of Delegates are:

Single Delegate – A delegate which can call a single method.
Multicast Delegate – A delegate which can call multiple methods. + and – operators are used to subscribing and unsubscribing respectively.
Generic Delegate – It does not require an instance of the delegate to be defined. It is of three types, Action, Funcs, and Predicate.

  • Action- In the above example of delegates and events, we can replace the definition of delegate and event using the Action keyword. The Action delegate defines a method that can be called on arguments but does not return a result
Public delegate void deathlnfo( );

Public event deathlnfo deathDate;

//Replacing with Action//

Public event Action deathDate;

Action implicitly refers to a delegate.
  • Func- A Func delegate defines a method that can be called on arguments and returns a result.
    Func <int, string, bool> myDel is same as delegate bool myDel(int a, string b);
  • Predicate – Defines a method that can be called on arguments and always returns the bool.
    Predicate<string> myDel is same as delegate bool myDelfstring s);

Question 39.
What’s a multicast delegate?
Answer:
A delegate having multiple handlers assigned to it is called a multicast delegate. Each handler is assigned to a method. In other words
A Delegate that points to more than one method is called a Multicast Delegate. Multicasting is achieved by using the + and += operators.

Consider the Example from previous delegate question

There are two subscribers for death event, GetPatlnfo, and GetDeathDetails. And hence we have used += operator. It means whenever the myDel is called, both the subscribers get called. The delegates will be called in the order in which they are added.

Question 40.
Explain Publishers and Subscribers in Events.
Answer:
A Publisher is a class responsible for publishing a message of different types of other classes. The message is nothing but an Event as discussed in the above questions.

From the Example in Question 32, Class Patient is the Publisher class. It is generating an Event death event, which the other classes receive.

Subscribers capture the message of the type that it is interested in. Again, from the Example of Question 32, Class Insurance and Bank are Subscribers. They are interested in event death event of type void.

Question 41.
How do you inherit a class into another class in C#?
Answer:
Colon is used as an inheritance operator in C#. Just place a colon and then the class name, public class DerivedClass: BaseClass

Question 42.
What is the base class in .net from which all the classes are derived from?
Answer:
System.Object

Question 43.
What is the difference between method overriding and method overloading?
Answer:
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.

Question 44.
What are the different ways a method can be overloaded?
Answer:
Methods can be overloaded using different data types for a parameter, different order of parameters, and different numbers of parameters.

Question 45.
Why can’t you specify the accessibility modifier for methods inside the interface?
Answer:
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.

Question 46.
How can we set the class to be inherited, but prevent the method from being over-ridden?
Answer:
Declare the class as public and make the method sealed to prevent it from being overridden.

Question 47.
What happens if the inherited interfaces have conflicting method names?
Answer:
The 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 the compiler cares you’re okay.

Question 48.
What is the difference between a Struct and a Class?
Answer:
Structs are value-type variables, and classes are reference types. Structs stored on the Stack cause additional overhead but faster retrieval. Structs cannot be inherited.

Class

Supports Inheritance
Class is Pass by reference (reference type)
Members are private by default
Good for larger complex objects
Can use waste collector for memory management

Struct

Does not support Inheritance
Struct is Pass by Copy (Value type)
Members are public by default
Good for Small isolated models
Cannot use Garbage collector and hence no Memory management

Question 49.
How to use nullable types in .Net?
Answer:
Value types can take either their normal values or a null value. Such types are called nullable types.

Int? somelD = null;
If(somelD.HasVAIue)
{
}

Question 50.
How we can create an array with non-default values?
Answer:
We can create an array with non-default values using Enumerable. Repeat.

Question 51.
What is the difference between “is” and “as” operators in c#?
Answer:
“is” operator is used to checking the compatibility of an object with a given type, and it returns the result as Boolean.
“as” operator is used for casting an object to a type or a class.

Question 52.
What are indexers in C# .NET?
Answer:
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

Question 53.
What is the difference between the “throw” and “throw ex” in .NET?
Answer:
The “Throw” statement preserves the original error stack whereas “throw ex” has the stack trace from their throw point. It is always advised to use “throw” because it provides more accurate error information.

Question 54.
What are C# attributes and their significance?
Answer:
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.

Question 55.
How to implement a singleton design pattern in C#?
Answer:
In a singleton pattern, a class can only have one instance and provides an access point to it globally.

Eg:

Public sealed class Singleton

{

Private static readonly Singleton Jnstance = new Singleton();

}

Question 56.
What is the difference between direct cast and type?
Answer:
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.

Question 57.
What is Managed and Unmanaged code?
Answer:
Ans: Managed code is a code that is executed by CLR (Common Language Runtime) i.e all application code based on .Net Platform. It is considered as managed because of the
.Net framework which internally uses the garbage collector to clear up the unused memory.

Unmanaged code is any code that is executed by the application runtime of any other framework apart from .Net. The application runtime will take care of memory, security, and other performance operations.

Question 58.
Is C# code is managed or unmanaged code?
Answer:
C# is managed code because Common language runtime can compile C# code to Intermediate language.

Question 59.
What is a Console application?
Answer:
A console application is an application that can be run in the command prompt in Windows. For any beginner on .Net, building a console application is ideally the first step, to begin with.

Question 60.
Give an example of removing an element from the queue
Answer:
The dequeue method is used to remove an element from the queue,

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoApplication
{
class Program
{
static void Main(string[ ] args)
{
Queue qt = new Queue( );
qt.Enqueue(1);
qt.Enqueue(2);
qt.Enqueue(3);

foreach (Object obj in qt)
{
Console.WriteLine(obj);
}
Console.WriteLine(); Console.WriteLine();
Console.WriteLine("The number of elements in the Queue " + qt.Count);
Console.WriteLine("Does the Queue contain " + qt.Contains(3));
Console.ReadKey( );
}
}
}

Question 61.
What are the fundamental OOP concepts?
Answer:
The four fundamental concepts of Object-Oriented Programming are:
• Encapsulation – The Internal representation of an object is hidden from the view outside the object’s definition. Only the required information can be accessed whereas the rest of the data implementation is hidden.
• Abstraction – It is a process of identifying the critical behavior and data of an object and eliminating the irrelevant details.
• Inheritance – It is the ability to create new classes from another class. It is done by accessing, modifying, and extending the behavior of objects in the parent class.
• Polymorphism – The name means, one name, many forms. It is achieved by having multiple methods with the same name but different implementations.

Question 62.
What are the different types of classes in C#?
Answer:
The different types of classes in C# are:

• Partial class – 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.

Question 63.
Explain Code compilation in C#.
Answer:
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.

Question 64.
What is the difference between the Virtual method and the Abstract method?
Answer:
A Virtual method must always have a default implementation. However, it can be overridden in the derived class, though not mandatory. It can be overridden using override keyword.

An Abstract method does not have an implementation. It resides in the abstract class. It is mandatory that the derived class implements the abstract method. An override keyword is not necessary here though it can be used.

Question 65.
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 use one namespace in another, which are called Nested Namespaces.
They are denoted by the keyword “namespace”.

Question 66.
Explain Abstraction.
Answer:
Abstraction is one of the OOP concepts. It is used to display only the essential features of the class and hides 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 tire private keyword.

Question 67.
Explain Polymorphism?
Answer:
Programmatically, Polymorphism means the 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.

Question 68.
What are C# I/O Classes? What are the commonly used I/O Classes?
Answer:
C# has System.10 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.

Question 69.
What is the StreamReader/StreamWriter class?
Answer:
StreamReader and StreamWriter are classes of namespace System.10. They are used when we want to read or write charact90, Reader-based data, respectively.

Some of the members of StreamReader are: Close( ), Read( ), Readline( ).

Members of StreamWriter are: Close( ), Write( ), Writeline( ).

1 Class Programl
2{
3 using(StreamReader sr = new StreamReader(“C:\ReadMe.txt”)
4{
5 //——–code to read———//
6}
7 using(StreamWriter sw = new StreamWriter(“C:\ReadMe.txt”))
8{
9 //———Code to write——-//
10}
11}

Question 70.
What is a Destructor in C#?
Answer:
A Destructor is used to clean up the memory and free tire 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("....");

}

Question 71.
What are Boxing and Unboxing?
Answer:
Converting a value type to reference type is called Boxing.

For Example:

int Valuel -= 10;
//——Boxing——–//
object boxedValue = Valuel;

Explicit conversion of the same reference type (created by boxing) back to value type is called Unboxing.

For Example:

//——-UnBoxing——–//
int UnBoxing = int (boxed value);

Question 72.
What is the difference between Continue and Break Statement?
Answer:
Break statement breaks the loop. It makes the control of the program exit the loop. Continue statement makes the control of the program exit only the current iteration. It does not break the loop.

Question 73.
What is the difference between the final and finalize blocks?
Answer:
finally 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 a 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.

Question 74.
What is a String? What are the properties of a String Class?
Answer:
A String is a collection of char objects. We can also declare string variables in c#.

string name = “C# Questions”;

A string class in C# represents a string.

The properties of the 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.

Question 75.
What is an Escape Sequence? Name some String escape sequences in C#.
Answer:
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 a single character.

String escape sequences are as follows:

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

Question 76.
What are Regular expressions? Search a string using regular expressions?
Answer:
Ans: 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.

For Example:

* matches the preceding character zero or more times. So, a*b regex is equivalent to b, ab, aab, aaab, and so on.

Searching a string using Regex
1 static void Main(string[ ] args)
2{
3 string}] languages = {"C#", "Python", "Java" };
4 foreach(string s in languages)
5{
6 if(System.Text.RegularExpressions.Regex.lsMatch(s,"Python"))
7{
8 Console.WriteLine("Match found");
9 }
10}
11}

The above example searches for “Python” against the set of inputs from the languages array. It uses Regex.IsMatch returns true in case if the pattern is found in the input. The pattern can be any regular expression representing the input that we want to match.

Question 77.
What are the basic String Operations? Explain.
Answer:
Some of the basic string operations are:

• Concatenate –Two strings can be concatenated either by using a System.String.Concat or by using + operator.
• Modify – Replace(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 a case-sensitive comparison or not case sensitive. Mainly takes two parameters, original string, and string to be compared with.
• Search – start with, EndsWith methods are used to search a particular string.

Question 78.
What is Parsing? How to Parse a Date Time String?
Answer:
Parsing is converting a string into another data type.

For Example:

string text = “500”; int num = int.Parse(text);
500 is an integer. So, Parse method converts the string 500 into its own base type, i.e int.

Follow the same method to convert a DateTime string.
string dateTime = “Jan 1, 2018”;
DateTime parsedValue = DateTime.Parse(dateTime);

Question 79.
What are Synchronous and Asynchronous operations?
Answer:
Synchronization is a way to create a thread-safe code where only one thread can access the resource at any given time.
The asynchronous call waits for the method to complete before continuing with the program flow. Synchronous programming badly affects the Ul 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.

Question 80.
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.
The Memberlnfo 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 the type of a class, we can simply use
Type my type = myClass.GetType( );
Once we have a type of class, the other information of the class can be easily accessed.
System.Reflection.Memberlnfo Info = mytype.GetMethod(“AddNumbers”);
Above statement tries to find a method with name AddNumbers in the class myClass.

Question 81.
Explain Get and Set Accessor properties?
Answer:
Get and Set are called Accessors. These are made use by Properties. The 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.

Question 82.
What is a Thread? What is Multithreading?
Answer:
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 that 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 = newThreadStart(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.

Question 83.
Name some properties of Thread Class.
Answer:
Few Properties of thread class are:

  • IsAlive-contains value True when a thread is Active.
  • Wame – Can return the name of the thread. Also, can set a name for the thread.
  • Priority – returns the prioritized value of the task set by the operating system.
  • background – gets or sets a value that indicates whether a thread should be a background process or foreground.
  • ThreadState- describes the thread state.

Question 84.
What are the different states of a Thread?
Answer:
Different states of a thread are:

  • Unstarted – Thread is created.
  • Running- Thread starts execution.
  • WaitSleepJoin – Thread calls sleep, calls wait on another object and calls join on another thread.
  • Suspended – The thread has been suspended.
  • Aborted – Thread is dead but not changed to state stopped.
  • Stopped – Thread has stopped.

Question 85.
What are Async and Await?
Answer:
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, my method 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 a Delay of 1 second is involved.

Question 86.
What is a Deadlock?
Answer:
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.

Question 87.
Explain lock, Monitors, and Mutex Objects in Threading.
Answer:
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.

Monitor. Enter(ObjA); try
{ 
}
Finally {Monitor.Exit(ObjA));}

Question 88.
What is a Race Condition?
Answer:
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.

Question 89.
What is Thread Pooling?
Answer:
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 that manage the threads in the pool and its operations.

System.Threading.ThreadPool.QueuellserWorkltem(new
System.Threading.WaitCallback(SomeTask));

The above line queues a task. SomeTask methods should have a parameter of type Object.

Question 90.
What is Serialization?
Answer:
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.

Another Explanation for this

Serialization is the 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 device. 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 that can contain the serialized object and namespace System.Runtime.Serialization can contain classes for serialization.

Question 91.
What are the types of Serialization?
Answer:
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 that 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.

Question 92.
What is an XSD file?
Answer:
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.