Thursday, 28 November 2019

Proxy Design Pattern - C# (Structural)

The proxy design pattern is used to provide a surrogate object, which references to other objects. ( it acts as a representation of an object and will basically be the access point to use the original object.) Or we can say it acts as a substitute for a real service object used by a client
The proxy pattern involves a class, called proxy class, which represents the functionality of another class. A proxy receives client requests, does some work (access control, caching, etc.) and then passes the request to a service object.
Examples: For an example, we may have a web service API to get the live Stock Market feed or a live Cricket match score. Client applications that need these kinds of data cannot directly access the resources and need to use some kind of intermediate to fetch it. In this case, any API service acts as a Proxy on behalf of the actual resource. This kind of pattern allows not only to control the access to the resources only when required, but also provides security as the client code cannot directly access the resources and must pass through the proxy.

Tuesday, 26 November 2019

Beautiful C# Basic and concepttual Question and answers


1. Why Main() method is static?
You need an entry point into your program. A static method can be called without instantiating an object. Therefore main() needs to be static in order to allow it to be the entry to your program.

2. What is string[] args in Main method? What is there use?
The parameter of the Main method is a String array that represents the command-line arguments. The string[] args may contain any number of Command line arguments which we want to pass to Main() method.

3. Is .Net Pass by Value or Pass by Reference?
By default in .Net, you don't pass objects by reference. You pass references to objects by value. However, you get the illusion it's pass by reference, because when you pass a reference type you get a copy of the reference (the reference was passed by value).

4. What is nullable type in c#?
Nullable type is new concept introduced in C#2.0 which allow user to assign null value to primitive data types of C# language. It is important to not that Nullable type is Structure type.

5.What is managed/unmanaged code?
Managed code is not directly compiled to machine code but to an intermediate language which is interpreted and executed by some service on a machine and is therefore operating within a secure framework which handles things like memory and threads for you.

Unmanaged code is compiled directly to machine code and therefore executed by the OS directly. So, it has the ability to do damaging/powerful things Managed code does not.

C# is managed code because Common language runtime can compile C# code to Intermediate language.

6. Can I override a static methods in C#?
No. You can't override a static method. A static method can't be virtual, since it's not related to an instance of the class.

7. Can we call a non-static method from inside a static method in C#?
Yes. You have to create an instance of that class within the static method and then call it, but you ensure there is only one instance.

8. Can a private virtual method be overridden?
No, because they are not accessible outside the class.

9.What's a multicast delegate in C#?
Multicast delegate is an extension of normal delegate. It helps you to point more than one method at a single moment of time

10. Can we define private and protected modifiers for variables in interfaces?
Interface is like a blueprint of any class, where you declare your members. Any class that implement that interface is responsible for its definition. Having private or protected members in an interface doesn't make sense conceptually. Only public members matter to the code consuming the interface. The public access specifier indicates that the interface can be used by any class in any package.

11.When does the compiler supply a default constructor for a class?
In the CLI specification, a constructor is mandatory for non-static classes, so at least a default constructor will be generated by the compiler if you don't specify another constructor. So the default constructor will be supplied by the C# Compiler for you.

12.How destructors are defined in C#? A Destructor is used to clean up the memory and free the resources.
C# destructors are special methods that contains clean up code for the object. You cannot call them explicitly in your code as they are called implicitly by GC. In C# they have same name as the class name preceded by the ~ sign.

13.When does the compiler supply a default constructor for a class?
In the CLI specification, a constructor is mandatory for non-static classes, so at least a default constructor will be generated by the compiler if you don't specify another constructor. So the default constructor will be supplied by the C# Compiler for you.

14.How destructors are defined in C#?
C# destructors are special methods that contains clean up code for the object. You cannot call them explicitly in your code as they are called implicitly by GC. In C# they have same name as the class name preceded by the ~ sign.

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

What's the difference between the Debug class and Trace class?
The Debug and Trace classes have very similar methods. The primary difference is that calls to the Debug class are typically only included in Debug build and Trace are included in all builds (Debug and Release).

What is the difference between == and quals() in C#?
The "==" compares object references and .Equals method compares object content

Explain object pool in C#?
Object pool is used to track the objects which are being used in the code. So object pool reduces the object creation overhead.

What is static constructor?
Static constructor is used to initialize static data members as soon as the class is referenced first time.

Difference between this and base ?
"this" represents the current class instance while "base" the parent.

What's the base class of all exception classes?
System.Exception class is the base class for all exceptions.
How the exception handling is done in C#?
In C# there is a "try… catch" block to handle the exceptions.

Why to use "using" in C#?
The reason for the "using" statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens. Using calls Dispose() after the using-block is left, even if the code throws an exception.

What is a collection?
A collection works as a container for instances of other classes. All classes implement ICollection interface.

Can finally block be used without catch?
Yes, it is possible to have try block without catch block by using finally block. The "using" statement is equivalent try-finally.

How do you initiate a string without escaping each backslash?
You put an @ sign in front of the double-quoted string.

String ex = @"without escaping each backslash\r\n"

Can we execute multiple catch blocks in C#?
No. Once any exception is occurred it executes specific exception catch block and the control comes out.

What does the term immutable mean?
The data value may not be changed.

What is Reflection?
Reflection allows us to get metadata and assemblies of an object at runtime.

What namespaces are necessary to create a localized application?
System.Globalization, System.Resources.

Can you return multiple values from a function in C#?
Yes, you can return multiple values from a function using the following approaches:

ref / out parameters
Struct / Class
Tuple
What is the difference between ref and out parameters?
"ref" tells the compiler that the object is initialized before entering the function, while "out" tells the compiler that the object will be initialized inside the function.


int x;
disp(out x); // OK: you can pass without initialize



int y;
disp(ref y); // Error: y should be initialized before calling the method


What are the differences between value types and reference types?
A Value Type holds the data within its own memory allocation and a Reference Type contains a pointer to another memory location that holds the real data. That means, Value type holds some value only and not hold memory addresses and Reference types holds a memory address of a value.

More about.... value types and reference types

What is the difference between "constant" and "readonly" variables in C#?
Constants

Can be assigned values only at the time of declaration
Static by default
Known at compile time
Read only
Must have set value, by the time constructor exits
Are evaluated when instance is created
Known at run time
Mention the assembly name where System namespace lies in C#?
mscorlib.dll

What is the .NET datatype that allows the retrieval of data by a unique key?
HashTable

What is Global Assembly Cache (GAC)? , and where is it located?
The Global Assembly Cache (GAC) is a folder in Windows directory to store the .NET assemblies that are specifically designated to be shared by all applications executed on a system.

By default you could see all assemblies installed in GAC in

c:\windir\assembly folder

Which method do you use to enforce garbage collection in .NET?
System.GC.Collect() forces garbage collector to run. This is not recommended but can be used if situations arise.

See more.... How to force Garbage Collection

See more... What is Garbage Collection

Why do I get errors when I try to serialize a Hashtable?
XmlSerializer will refuse to serialize instances of any class that implements IDictionary.

How can I stop my code being reverse-engineered from IL?
Obfuscate your code. Dotfuscator has a free edition and comes with Visual Studio. These tools work by "optimising" the IL in such a way that reverse-engineering becomes much more difficult. Also host your service in any cloud service provider that will protect your IL from reverse-engineering.

What is the use of Configuration Files?
The configuration file is really only for settings configured at deployment time. It can be used to deal with versioning issues with .NET components. And it's often used for connections strings - it's useful to be able to deploy an application to connect to a test or staging server, but this is not something you'd normally change in production once the application is deployed.

How Reference types and Value types are stored in memory ?
Value types get stored on stack and shared the same process memory, however the Reference Types get stored on Heap and their memory address value gets stored on the stack as value type.

How do you convert a string into an integer in .NET?
Int32.Parse(string)

What is a formatter?
A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.

How many classes can a single .NET DLL contain?
One DLL can contains Unlimited classes.

What is manifest?
It is the metadata that describes the assemblies

What are the different types of classes in C#?

Ans: The different types of class 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 which 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 which 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.


Explain Code compilation in C#.

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

 What is the difference between Virtual method and Abstract method?

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

Explain Abstraction.

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

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

Ans: 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 writing a string buffer.
StringReader – Used for reading a string buffer.
Path – Used for performing operations related to path information.

What is the difference between finally and finalize block?

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

Name some properties of Array.

Ans: 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.
Q #24) What is an Array Class?

Ans: An Array class is the base class for all arrays. It provides many properties and methods. It is present in the namespace System.

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

Ans: 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 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#.

Ans: 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?

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.IsMatch(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 which 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.

What is a Delegate? Explain.

Ans: A Delegate is a variable that holds the reference to a method. Hence it is a function pointer of 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 an1 = new AddNumbers(number);

The delegate provides a kind of encapsulation to the reference method, which will internally get called when a delegate is called.

What are Events?

Ans: 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 which 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;
**Delegates are used to raise events and handle them. Always a delegate needs to be declared first and then the Events are declared.

What are Synchronous and Asynchronous operations?

Ans: 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 are Async and Await?

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

Usage of Async and Await is as shown below:
Async Keyword

Async Keyword

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 Reflection in C#?

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

What is a Generic Class?

Ans: Generics or Generic class is used to create classes or objects which do not have any specific data type. The data type can be assigned during runtime, i.e when it is used in the program.

For Example:
Generic Class
So, from the above code, we see 2 compare methods initially, to compare string and int.

In case of other data type parameter comparisons, instead of creating many overloaded methods, we can create a generic class and pass a substitute data type, i.e T. So, T acts as a datatype until it is used specifically in the Main() method.
Explain Get and Set Accessor properties?

Ans: 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?

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

Q #41) Name some properties of Thread Class.

Ans: Few Properties of thread class are:

IsAlive – contains value True when a thread is Active.
Name – 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.
IsBackground – gets or sets a value which indicates whether a thread should be a background process or foreground.
ThreadState– describes the thread state.
Q #42) What are the different states of a Thread?

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 – Thread has been suspended.
Aborted – Thread is dead but not changed to state stopped.
Stopped – Thread has stopped.

What is a Thread? What is Multithreading?

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

Q #41) Name some properties of Thread Class.

Ans: Few Properties of thread class are:

IsAlive – contains value True when a thread is Active.
Name – 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.
IsBackground – gets or sets a value which indicates whether a thread should be a background process or foreground.
ThreadState– describes the thread state.
Q #42) What are the different states of a Thread?

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 – Thread has been suspended.
Aborted – Thread is dead but not changed to state stopped.
Stopped – Thread has stopped.
 Explain Lock, Monitors, and Mutex Object in Threading.

Ans: 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));}

What is a Race Condition?

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

Q #47) What is Thread Pooling?

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

System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(SomeTask));
The above line queues a task. SomeTask methods should have a parameter of type Object.

What is Serialization?

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

Q #49) What are the types of Serialization?

Ans: 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.
Q #50) What is an XSD file?

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

Monday, 25 November 2019

Interesting General Knowledge on .NET (GK on .Net)

Difference between a Debug and Release build?

Debug mode and Release mode are different configurations for building your .Net project. Programmers generally use the Debug mode for debugging step by step their .Net project and select the Release mode for the final build of Assembly file (.dll or .exe).

The Debug mode does not optimize the binary it produces because the relationship between source code and generated instructions is more complex. This allows breakpoints to be set accurately and allows a programmer to step through the code one line at a time. The Debug configuration of your program is compiled with full symbolic debug information which help the debugger figure out where it is in the source code.

Is Release mode is faster than Debug mode ?
The Release mode enables optimizations and generates without any debug data, so it is fully optimized. . Lots of your code could be completely removed or rewritten in Release mode. The resulting executable will most likely not match up with your written code. Because of this release mode will run faster than debug mode due to the optimizations.

What is .pdb files ?
Debug information can be generated in a .pdb (Program Database File) file depending on the compiler options that are used. A .pdb file holds debugging and project state information that allows incremental linking of a Debug configuration of your program. A Program Database File is created when you compile a VB.Net or C# program with debug mode.

In Asp.Net ?
It is important to note that Debug mode or Release mode in a web application is controlled by the web.config file, not your settings within Visual Studio.
e.g.
<system.web>
    <compilation debug="true">

Difference between normal DLL and .Net DLL

dll: A .dll file contains compiled code you can use in your application to perform specific program functions and may be required by another application or module (such as .exe or .dll) to load it through an entry point. It is a library that contains code and data that can be used by more than one program at the same time. It helps promote modularization of code, code reuse, efficient memory usage, and reduced disk space. So the operating system and the programs load faster, run faster, and take less disk space on the computer.

What is .Net dll ?
When you implement a .Net DLL (Assembly) in .NET Languages such as C# or VB.NET you produce a Managed Assembly. Managed Assembly is the component standard specified by the .NET. Hence, .Net assemblies are understandable only to Microsoft.NET and can be used only in .NET managed applications. A manage assembly contains managed code and it is executing by the .NET Runtime. When you create a DLL with C++ you produce a win32/Com DLL. If you use this dll in a .NET Language, the Visual Studio create automatically an INTEROP file for you, so you can call the "unmanaged" dll from manage code .

For using a .Net DLL (Assembly), the simplest option is to copy the dll to the bin folder. Normal DLL files are need to be register with the "regsvr32" tool.

Difference between a thread and a process

The processes and threads are independent sequences of execution, the typical difference is that threads run in a shared memory space, while processes run in separate memory spaces.

A process has a self contained execution environment that means it has a complete, private set of basic run time resources purticularly each process has its own memory space. Threads exist within a process and every process has at least one thread.

Each process provides the resources needed to execute a program. Each process is started with a single thread, known as the primary thread. A process can have multiple threads in addition to the primary thread.

On a multiprocessor system, multiple processes can be executed in parallel. Multiple threads of control can exploit the true parallelism possible on multiprocessor systems.

Threads have direct access to the data segment of its process but a processes have their own copy of the data segment of the parent process.

Changes to the main thread may affect the behavior of the other threads of the process while changes to the parent process does not affect child processes.

Processes are heavily dependent on system resources available while threads require minimal amounts of resource, so a process is considered as heavyweight while a thread is termed as a lightweight process.

What is multithreading ?

In .NET languages you can write applications that perform multiple tasks simultaneously. Tasks with the potential of holding up other tasks can execute on separate threads is known as multithreading.
Differences between a control and a component

Control and a Component ?

A component is a class that implements the IComponent interface or that derives directly or indirectly from a class that implements IComponent.

public class BaseComponent : IComponent {}

A component does not draw itself on the form, but a control draws itself on the form or on another control. Both the Components and the Controls can be dropped onto a design surface. If you double click the item on the toolbox and it will get placed inside the form then it the item known as Controls where as the item placed below the form area (component tray) then it is known as component.

e.g. Timer is a component and that has no visual representation during runtime, but you can see it in the component tray during the design time. Progress Bar is a control and it has visual representation in both design time and runtime.

All controls are also components, but not all components are controls.

You can create a component if you want to provide functionality without UI such as with the BackgroundWorker component, then you would only need to derive from Component directly. e.g. Timer , Data Source etc.. You can create a custom control if you want to make a component where you have full control over its visual appearance. e.g. Textbox , Button etc.

Globalization and Localization

c# globalization localization: Globalization is the process of internationalizing application code, that is culture neutral and language neutral, and that supports localized user interfaces and regional data for all users. It involves making design and programming decisions function for multiple cultures that are not based on culture-specific assumptions. While a globalized application is not localized, it nevertheless is designed and written so that it can be subsequently localized into one or more languages with relative ease

Globalization allows your web application to be useful for different people in different parts of the world who speaks different languages. ASP.Net makes it easy to localize an application through the use of resource files. Resource files are xml files with .resx extension. Resources can either be a global resource, in which it is accessible throughout the site and placed in App_GlobalResources folder in a website or a local resource which is specific to a page only and is placed in App_LocalResources folder.

What is .Net Localization ?
Localization is the process of translating an application's resources into localized versions for each culture that the application will support. Localization support is possible to automatically detect the user's culture and to respond to that detection with properly formatted dates, currency and other numeric values, properly configured controls etc. You should proceed to the localization step only after completing the Localizability step to verify that the globalized application is ready for localization.

For each localized version of your application, add a new satellite assembly that contains the localized user interface block translated into the appropriate language for the target culture. The code block for all cultures should remain the same. The combination of a localized version of the user interface block with the code block produces a localized version of your application.

CultureInfo Class ,Provides information about a specific culture . The information includes the names for the culture, the writing system, the calendar used, and formatting for dates and sort strings.

Difference between managed and unmanaged code

Managed code C#
Managed code is the code that is written to target the services of the managed runtime execution environment such as Common Language Runtime in .Net Technology.

The Managed Code running under a Common Language Runtime cannot be accessed outside the runtime environment as well as cannot call directly from outside the runtime environment. It refers to a contract of cooperation between natively executing code and the runtime. It offers services like garbage collection, run-time type checking, reference checking etc. By using managed code you can avoid many typical programming mistakes that lead to security holes and unstable applications, also, many unproductive programming tasks are automatically taken care of, such as type safety checking, memory management, destruction of unused Objects etc.

What is Unmanaged Code ?
Unmanaged code compiles straight to machine code and directly executed by the Operating System. The generated code runs natively on the host processor and the processor directly executes the code generated by the compiler. It is always compiled to target a specific architecture and will only run on the intended platform. So, if you want to run the same code on different architecture then you will have to recompile the code using that particular architecture.

Unmanaged executable files are basically a binary image, x86 code, directly loaded into memory. This approach typically results in fastest code execution, but diagnosing and recovery from errors might difficult and time consuming in most cases. The memory allocation, type safety, security, etc needs to be taken care of by the programmer and this will lead unmanaged code prone to memory leaks like buffer overruns, pointer overrides etc.

All code compiled by traditional C/C++ compilers are Unmanaged Code. COM components, ActiveX interfaces, and Win32 API functions are examples of unmanaged code. Managed code is code written in many high-level programming languages that are available for use with the Microsoft .NET Framework, including VB.NET, C#, J#, JScript.NET etc. Since Visual C++ can be compiled to either managed or unmanaged code it is possible to mix the two in the same application.

.NET in-built support for serialization

Serialization is the process of converting the state of an object into a form that can be persisted or transported. There are two separate mechanisms provided by the .NET class library: XmlSerializer and SoapFormatter/BinaryFormatter . Microsoft uses XmlSerializer for Web Services, and SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code. Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is likewise an open standard, which makes it an attractive choice.

XML Serialization
XML Serialization is the process of serializing a .Net Object to the form of XML or from an XML to .Net Object. The primary purpose of XML serialization in the .NET Framework is to enable the conversion of XML documents and streams to common language runtime objects and vice versa. This is the process of converting an object into a form that can be readily transported.
How many types of Jit Compilers?
Just-In-Time compiler- It converts the MSIL code to CPU native code as it is needed during code execution.

Different Types of JIT

Pre JIT Compiler
Econo JIT Compiler
Normal JIT Compiler
Pre JIT Compiler. This Compiler compiles complete source code into native code in a single compilation cycle. It is done through NGen (the process of precompiling from CIL to a native image). It will convert the compiled .NET code from the platform-independent intermediate state to a platform specific stage. This means that, it converts the .NET application that can run on both Windows, Mac and Linux 32-bit and 64-bit to an traditional EXE file that can only run on one of these.

The advantage of PRE JIT Compiler is that you don't have the initial compilation delay that the compiler can introduce when an assembly or type is loaded for the first time in code. It improves the warm startup time of your program. A warm start is one where the assembly data is already in the file system cache so no time is spent by the disk drive to locate the DLL on the disk. As opposed to a cold start, one you'll get when the assembly has never been loaded before or was loaded long ago, the disk drive has to find the file first. Which is slow. You almost always only care about cold start time because that's the one that's so noticeable to the user.

Econo JIT Compiler: Econo JIT Compiler compiles only those methods that are called at runtime . However, these compiled methods are removed when they are not required. The idea of Econo JIT is to spend less time compiling so that startup latency is lower for interactive applications. This is actually what you want once you notice the app takes seconds to start up.

Normal JIT Compiler: Normal-JIT compiles only those methods that are called at runtime . After execution this method is stored in the memory and it is commonly referred as "jitted" . No further compilation is required for the same method. Subsequent method calls are accessible directly from the memory cache.

Difference between web service and .net remoting

What is Web services ?
A web service is a method of communication between two software units over the World Wide Web. Applications can access Web services through different data formats such as HTTP, XML, and SOAP, with no need to worry about how each Web service is implemented.
Extensible Markup Language (XML) is used to tag the data, Simple Object Access Protocol (SOAP) is used to transfer the data, Web Services Description Language (WSDL) is used for describing the services available and Universal Description Discovery and Integration (UDDI) is used for listing what services are available.
Web services do not provide the user with a GUI, instead it share business logic, data and processes through a programmatic interface across a network.
What is .Net Remoting ?
.NET Remoting is a mechanism that allows objects to interact with each other across application domains, whether application components are all on one computer or spread out across the entire world. Remoting was designed in such a way that it hides the most difficult aspects like managing connections, marshaling data, and reading and writing XML and SOAP.
You can study more in detail about .Net Remoting with sample Source code :
Which one is better ?
Both technologies are powerful that provide a suitable framework for developing distributed applications. Web services favor the XML Schema type system, and provide a simple programming model with broad cross-platform reach, while.NET Remoting favors the runtime type system, and provides a more complex programming model with much more limited reach.
If both your clients and components are inside the firewall, Web services will work fine. However, all of your data travels through a Web server, which can slow performance. Remoting is allowing you to communicate between a client application and components in a binary format. It is more suitable as a high speed solution for binary communication between proprietary .NET components, usually over an internal network.

It is important to understand how both technologies work and to choose the one that is right for your application.

What is code access security (CAS)?


Code Access Security (CAS) is the security sandbox for .NET. Local apps typically have full trust which means they can do anything. The .NET apps that are hosted in the browser can't do much. In between, just about any security setting can be fine-tuned using CAS.

The .NET Security Model provides code access permissions and code identity permissions. Code Access Security is the part of the .NET security model that determines whether or not the code is allowed to run, and what resources it can use when it is running. Code Access Security policy uses evidence to help grant the right permissions to the right assembly.

An administrator can configure Code Access Security policy to restrict the resource types that code can access and the other privileged operations it can perform. Code Access Security allows code to be trusted to varying degrees depending on where the code originates and on other aspects of the code's identity. Code Access Security can also help minimize the damage that can result from security vulnerabilities in your code.

Difference between Math.Floor() and Math.Truncate()?

Mat.floor() will always round down and Math.Truncate rounds towards zero.

Math.Floor(2.5) = 2
Math.Truncate(2.5) = 2

Math.Floor(-2.5) = -3
Math.Truncate(-2.5) = -2

.Net Assembly Manifest

An Assembly Manifest is a file that containing Metadata about .NET Assemblies. Assembly Manifest contains a collection of data that describes how the elements in the assembly relate to each other. It describes the relationship and dependencies of the components in the Assembly, versioning information, scope information and the security permissions required by the Assembly.


The Assembly Manifest can be stored in Portable Executable (PE) file with Microsoft Intermediate Language (MSIL) code. You can add or change some information in the Assembly Manifest by using assembly attributes in your code. The Assembly Manifest can be stored in either a PE file (an .exe or .dll) with Microsoft Intermediate Language (MSIL) code or in a standalone PE file that contains only assembly manifest information. Using ILDasm, you can view the manifest information for any managed DLL.

.Net Garbage Collection

The .Net Framework provides a new mechanism for releasing unreferenced objects from the memory (that is we no longer needed that objects in the program) ,this process is called Garbage Collection (GC). When a program creates an Object, the Object takes up the memory. Later when the program has no more references to that Object, the Object's memory becomes unreachable, but it is not immediately freed. The Garbage Collection checks to see if there are any Objects in the heap that are no longer being used by the application. If such Objects exist, then the memory used by these Objects can be reclaimed. So these unreferenced Objects should be removed from memory , then the other new Objects you create can find a place in the Heap.

The reclaimed Objects have to be Finalized later. Finalization allows a resource to clean up after itself when it is being collected. This releasing of unreferenced Objects is happening automatically in .Net languages by the Garbage Collector (GC). The programming languages like C++, programmers are responsible for allocating memory for Objects they created in the application and reclaiming the memory when that Object is no longer needed for the program. In .Net languages there is a facility that we can call Garbage Collector (GC) explicitly in the program by calling System.GC.Collect.

.Net Application Domain

An application domain is a virtual process and is used to isolate applications from one another. Each application domain has their own virtual address space which scopes the resources for the application domain using that address space.

Each application running within its main process boundaries and its application domain boundaries. All objects created within the same application scope are created within the same application domain. Multiple application domains can exist in a single operating system process. An application running inside one application domain cannot directly access the code running inside another application domain.

System.AppDomain is the main class you can use to deal with application domains.

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.





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