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.

No comments:

Post a Comment

Baisic Useful Git Commands

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