Sunday 4 December 2016

Interview question one line on .Net Fundamental

Sl No Questions Keyword Answer Example
1 IL Code(Intermediate Language) Paritally compiled code
2 Why IL code is not fully compiled? it is compiled to half compiled code because we do not know which OS or CPU configuration or security configuration In VS command prompt
via ILDASM tool we can view a IL code of a DLL or EXE
3 JIT IL code to machine language
4 Normal JIT compiles only those methods that are called at runtime.
(cached takes more memory like ASP.NET and windows application)
5 Econo JIT compiles only those methods that are called at runtime.
(No caching takes less memory like mob device and console applicaion)
6 Pre JIT compiles complete source code into native code in single compilation cycle In VS command prompt
via ngen.exe command
7 CLR(Common Language Runtime) Heart of the engine
has 4 properties GC, CAS, CV and IL to JIT
8 How does the .NET code compile? Write the code (C#, VB.Net, C++ .Net) -- compiles to a IL code -- CLR gives it to JIT -- JIT compiles to the machine specification language
9 managed code which runs under the control of CLR
10 unmanaged code which runs outside CLR (like skype or excel etc)
11 GC (Garbage collector) It is small background process thread which runs to clean unused managed object does not clear unmanage object Can be checked by CLR profiler
click on objectByAddress tab

for (int a =0; a<1000; a++){
       cls obj = new cls();
}
12 How does the GC run it run in background
13 CAS (Code Access Security) it helps assign the .NET code permission of what they are capable of doing.
Example CAS will allow an application to read but not to write and delete a file or a resource from a folder
14 where do we use CAS when we consume third party components which are not safe
15 CV (Code Verification) Code verification ensure that proper code execution and type safety while the code runs.
It does not allow to perform illegal operation such as invalid memory location.
16 CTS (Common Type System) Communicate 2 language like C#, VB.NET smoothly CLR has CTS can be checked via ILDASM tool.
In IL code
17 CLS (Common Language Specification) Specification/Guideliness of the source code  in AssemblyInfo.cs
[assembly : CLSCompliant(true)]
18 Assembly it’s a unit deployment (EXE, DLL)
Assembly is precompiled .NET code which can be run by CLR
19 EXE (Executable file) EXE - Self starting (Console Application/ Windows application)
20 DLL (Dynamic Link Library) DLL - You have to link (Class Library/ Web application)
21 Types of Assembly Private - normally used by a single application
Shared - normally stored in the global assembly
22 Manifest it describes more about the assembly ( Meta data):-Versioning, References , dependent objects , Security , Scope
23 satellite assembly It’s a  compiled DLL which has images , text files any resource files. In other words no can tamper with your images , text files , icons etc.
24 how do you do versioning Assemblyinfo.cs / right click properties -- assembly information
25 What are strongly typed and weakly typed references ? They help you to identify the publisher.
Strong typed - identify the DLL with a public key token
Weakly typed - are just simple references and identified only by class names
to avoid hack, we can use *.snk file
26 Delay signing 1. Public key [Development]
2. Private key [Development/Production] - Secured

This is meant to protect DLL identity from your internal team developers , public key is give to the developer byextracting using SN.EXE -p , when you ready to go for  production you will inject the private key in the DLL SN.EXE -R
By creating *.snk file
27 GAC To share the assembly across multiple  application in the same computer (C:\WINDOWS\assembly)
28 How to add and remove an assembly from GAC?
How do we register in GAC ?
1. Using Microsoft installer package
2. Using Gacutil
29 Strong names They ensure that the class name is unique to avoi confustion
30 Problem in destructor GC before going disposing object,It will question do you have destructor, if it has destructor then it will move to next generation.
It will not clean object on that time instance even though if is unused, it will wait for destructor then it will clean object
Can be checked by CLR profiler
click on objectByAddress tab

for (int a =0; a<1000; a++){
       cls obj = new cls();
}

class cls
{
       ~cls()
       {
               //clean up unmanaged code
       }
}
31 Idisposable Interface & Finalized dispose to avoid the problem of destructor
Idisposible interface and Finalize dispose pattern is used
for (int a =0; a<1000; a++){
       cls obj = new cls();
}

class cls : IDisposable
{
       ~cls()
       {
               //clean up unmanaged code
       }

       public void Dispose()
       {
               GC.SupressFinalize(true); 
                  //clean object even though find destructor
       }
}
32 What are Gen 0, 1 & 2? Age of the objects. i.e., how long it will stay in memory
Gen 0 has newly created objects.
Gen 1 has objects which are bit older,
Gen 2 has objects which is more older then Gen 1
This is for GC optimazation, garbage collector checks Gen 0 frequently rather then Gen 1 and Gen2
for (int a =0; a<1000; a++){
       cls obj = new cls();
}

class cls : IDisposable
{
       ~cls()
       {
               //clean up unmanaged code
       }

       public void Dispose()
       {
               GC.SupressFinalize(true); 
                  //clean object even though find destructor
       }
}
33 Does garbage collector clean unmanaged code? No
34 Do I need to write clean up code for managed objects? No, GC is smart to figure out unused objects and clean them up
35 so what do I do for unmanaged? You need to write the clean up in destructor
36 What kind of problems do we have with destructors from GC perspective? lot of objects created in Gen 1
37 Finalize (also known as destructor) It's a destructor for cleaniing up unmanaged objects. 
38 how to ensure that lot of objects are not created in Gen 1 with class having destructor ? Implement Idisposable -- Expose a Dispose function -- Call GC.SuppressFinalize
39 What is Dispose function ? Its  method exposed for clean up for client,Idisposable , Dispose , GC.SuppressFinalize
40 Difference between Finalize and Dispose Finalize is a destructor and dispose is function which is implemented via Idisposable.
Finalize is non deterministic since we dont call it. It is up to the GC to call it. However dispose gives more control to the developer to perform cleanup. Since we can call it explicitly.
41 can we force garbage collector yes, GC.Collect
42 what are namespaces? They helps us to logically group classes.
43 Difference between value and reference types Values types int, double, bool etc. Reference types objects and strings

Value types are allocated on stack and Reference types are allocated on heap.
Value types are stored on different memory locations while reference types point to the same memory location
44 Difference between Stack and heap They are memory types
Stack has value types
Heap has reference types
public void method()
{
     int i=4;int j=2; //stack
     cls obj = new cls(); //heap
}
45 Difference between boxing and unboxing Box - Convert from value to reference
Unboxing - reference type to value

VR-B
RV-U
can be seen in ILDASM tool i.e., IL CODE

public void method()
{
     int i=10;
     object obj =I;   //boxing
     int j =(int)obj;  //unboxing
}
46 Does unboxing and boxing bring down performance ? yes they do bring down performance because data has to jump between heap and stack memory types.
47 How can we avoid Boxing and unboxing ? You can not avoid it just minimize it
48 Difference between string and StringBuilder String : immutable[value will not change]
StringBuilder : mutable string
Can be checked by CLR profiler
click on objectByAddress tab

for (int a =0; a<1000; a++){
       cls obj = new cls();
}

object by address
System.String use 96% of memory allocation where as StringBuilder use 60% of memory allocation
49 Difference between readonly and constant const : compile time
readonly :
run time 
const int value = 100; //compile time
readonly double PI;   //run time

static Program(){
      PI = 3.14;
}

const is part of IL code
readonly will be assigned in constructor
50 Difference between check and uncheck Check : check keyword is check if destructor data type is overflow in a arthimetic calculaton
Uncheck : uncheck keyword is ALMOST the same way as checked, but is useful to bypass the constant datatype
int x = m.maxvalue; int y = m.maxvalue;
int z= x+y; //wrong value
z = checked(x+y); //throws overflow exception

const int a = m.maxvalue; const int b = m.maxvalue;
z=a+b; //compile time error
z = unchecked(a+b); 
51 Extension method Extension methods help us to add new methods to existing types without modifying code, inherting or aggregating main()
{
   
}
52 What is DLL hell?
53 Difference between ref and out? Ref and out keyword causes an argument to be passed by reference, not by value

In ref we have to initialize the value before passing through the function while in out we don’t
In out we have to modify inside the function while in ref we don't
static void methodFunction(ref int i){ I =i+44}
main()

      int val =1;
// have to initial the value
      methodFunction(ref val)
}

static void methodFunction(out int i){
I =44}
main()

      int val;
      methodFunction(ref val)
}
54 ParseTry ParseTry checks wheather datatype is true or false int x=123;
bool chek = int.ParseTry("123", out x);

chek will be true
55 Delegates It’s a abstract strong typed pointer to a function
56 create and invoke a delegate Declare , Create , point and invoke. //Declare
delegate double CalAreaPointer(int r);

//point
static CalAreaPointer cPointer = CalculateArea;
static void Main(string[] args)
{
      //invoke
      double area = cPointer.Invoke(20);
}

//Create
static double CalculateArea(int r)
{
        return 3.14 * r * r;
}
57 Use of delegate Delegates helps for call backs. So if you have huge task running  in multithreaded manner and you would like to get messages from that task you will use delegates.
58 Delegate and interfaces Delegate is at method level while interfaces are  at class and object level.
59 Multicast delegate(+= , -=) It helps them to point to multiple functions and execute them sequentially. public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
}
public static void Sub(int x, int y)
{
 }
}
class Program
{
static void Main(string[] args)
{
       Sampleclass sc=new Sampleclass();
       MultiDelegate del = Sampleclass.Add;
      del += Sampleclass.Sub;
      del(10, 5);
      Console.ReadLine();
}
}
60 Use of Multicast delegate For boardcasting to multiple classes
example : broadcast error message (1) event log (2)email (3) file
61 What is Unicast ? When one delegate point to one function its called as unicast.
62 Events  Events encapsulates(hides) delegates. They are useful for boradcasting , publisher and subscriber
63 Difference between delegates and events  Events use delegates internally. Delegates are pointer to function while events encapsulates ( hiudes) delegate function.
In event clients can only subscribe while in delegates the client can subscribe as well as call all the functions of the delegates.
64 Anonymous delegates Anonymous method means method which coded inline or block of code inside the function, then we can point the delegate towards block of function delegate double CalAreaPointer(int r);

static void Main(string[] args)
{
      CalAreaPointer cPointer = new    CalAreaPointer(delegate(int r) {
      return 3.14 * r * r;
 });
double area = cPointer.Invoke(20);
}
65 Use of Anonymous delegates 1) If we want to use the delegate only inside the same function
2) Reduce overhead of instiating the delegate thus performance
Anonymous methods with Lambda Inline code inside the function with Lambda expression delegate double CalAreaPointer(int r);
static void Main(string[] args)
{
        CalAreaPointer cPointer = r => 3.12 * r * r; //Simple inline code
        double area = cPointer(20);
}
66 how can we make a async
67 What are tuples
68 why are anonmymous types better then tuples
69 Lambda Expression Lambda expression points towards a single line of code
Uses of Lambda expression:
1) Lambda expression, action, func, predicate                                                                                                                                                                                                                                                make your delegate code more simple
2) Lambda expression heps to build expression trees in LINQ
  delegate double CalAreaPointer(int r);
        static void Main(string[] args)
        {
            CalAreaPointer cPointer = r => 3.12 * r * r;    //Simple inline code
            double area = cPointer(20);
        }
Func, Action, Predicate Func<I,T> is a predefined delegate type for a method Input <I> and return is required <T>

Action<T> is a predefined delegate type for a method only Input and without expecting output

Predicate<T> is a predefined delegate type for a method where output True or False
//Generic delegate (Lambda + Func)
static void Main(string[] args)
{
            Func<double, double> cPointer = r => 3.12 * r * r; //Func will be used when there is input and output

            Action<string> MyAction = y => Console.WriteLine(y);
//Action will be used when there is only input, without expecting output

            Predicate<string> CheckGreaterThan5 = x => x.Length > 5; 
//Predicate will give output True or False
          Console.WriteLine(CheckGreaterThan5("Amit"));
            MyAction("Hello");
            double area = cPointer(20);
}
70 covariance and contravariance(.net 4.0) This helps to point delegates in a very generic fashion
71 Difference between Array and Arraylist Array - Fixed , ArrayList - resizable , Array has performance improve ment as no boxing and unboxing takes place while in array list it does , Arraylist can not store mutiple data types while array has fixed data types
72 What is a generic list Strognyl typed list and improves performance by avoiding boxing and unboxing
73 Generic confined the type public class cls<T> where T : String
74 Hashtable Stores the value as hashed key , good for comparison , but bad in terms inserting valies
75 Stacks and Queues First in first out and last in first out
76 Are there any performance problems with normal .NET collection ? yes boxing unboxing happens
77 Regex and validation Regex is nothing pattern matching and then validating the data using the pattern
78 Generics Its to increase reusability by seperating logic and data type and its strong typed.
79 What are generic collections / Where have you used generics Generic collections enable simple .NET collections to be generic enabled. So a normall List can be attached with any data type and we can avoid casting
80 Does generic improve performance Yes , type casting is avoided
81 Threading Threading is used to do pararellel execution.
82 How do we use threading Create the thread object , pass the method name using thread start and call the start function.
83 can we set thread priority ThreadPriority
84 threading can we stop and suspend yes by using thread.start , suspend , stop
85 Background and foreground thread
86 What is reflection ? BY using System.reflection you can read meta data like properties , methods and also if needed you can invoked the methods and functions dynamically.
87 In what scenarios we would use reflection ? technological tools like VS IDE , code reviews tools like Fxcop  , unit testing NUNIT etc
88 how do you do reflection Import system.rflection , get the type of t he object using gettype and then you can browser through functio an dproperties , to invoke use the invokemember
89 What is Serialization ? Helps  to store in memory object in file and dessrialization means read the value from file and bring it in memory back.
90 Difference between dynamic and var var is statically typed (early bounded)
Dynamic is checked on runtime (late bounded) and also uses reflection
var x = "string1";  //data type of x is string (early bounded)
int len = x.Length; //length will give in intellisense

dynamic y = "string1"; //y is consider as datatype is runtime (late bounded)
int len = y.Length; //length will check in runtime
91 Difference between == and .Equals() Usage - (==)Technical based
Usage - (Equals)Sementic based

Type checking - (==) Compile Time
Type checking - (Equals) Run Time

Nulls - (==) Works
Nulls - (Equals) Can crash
Technically: - 1 is equal to 1.
Semantically: - 1 Dollar is not equal to 1 Rs.

string str ="test";  object str1 = "test";
str==str1; //Compile time with warning symbol
str.Equals(str1); //Run time no warning symbol

string str =null;  object str1 = null;
str==str1; //works
str.Equals(str1); //Null Reference Exception
92 Difference between IS and AS keyword IS - str1 varirable type of String

AS - convert str1 string AS a object
object obj = "test";
if (obj is string)      // IS
{
       Console.WriteLine("This is same type");
}

string str1 = obj as string;    // AS

No comments:

Post a Comment