Thursday, April 14, 2016

C#t Interview Questions



    What is a Class
  • A class is a Reference Type which represents its data and behaviour.
  • Data is represented by class field Members where as behaviour is represented by methods and properties present inside a class.
     What is an Object
  • An object is an instance of a class through which we can access fields,methods and properties present inside a class.
  • New Keyword is Used to create an instance for a class.
    What is public,Static and Void in C#
  • Public:It is an Access modifier where it can be accessible any where in the application.
  • Static:Variables or methods which are declared as Static are globally accessible and can be accessed by using class name but not by creating an instance(object) for a class.
  • Void:It is a type modifier which does not return any value.
     What is Difference between Array and Array list in C#
  • Both Array and Array list can hold more than one piece of data at a time but the difference between them is
  • Arrays are strongly typed collection of same datatype but where as an  Array list is not a strongly typed and can store the value of any datatype.
  • Arrays cannot grow in Size and are fixed where as an Array list can grow in size and are dynamic.
  • Array performance is better when compare to Array list as boxing and Un boxing happens with Array list which will degrade the performance.
      What is a Constructor
  • Constructor:A constructor of a class is automatically called when we create an instance for a class.
  • Through constructor we can initialise an field members of a class.
  • Constructors does not return a Value.
  • If we doesn't provide any constructor then Language compiler will automatically creates a default constructor.
    What are different types of Constructors
  •    Default Constructor:If a constructor does not contains any parameters then it is said to be a    default constructor.
  •   We can initialize  field members with in the constructor.
            Example:
                         public class clsName()
                     {
                              string tname;   // declaration of field member
                             public clsname()  //  creation of default constructor
                            {
                                tname="Venkat"; // Initialising field member with in the class
                            }
                     }
        NoteName of the constructor should be same as the Class name which is shown above

  • Parameterizwd Constructor:If a constructor contains one or more parameters then it is said to to be Parameterized constructor.
  • We can initialize field members of a class at the time of creation of an instance for a class.
           Example:
                            public class clsName()
                           {
                           public string tName;
                                 public clsName(string tvalue)          //Creation of Parameterixed constructor
                                {
                                tName=tvalue;
                                }
                            }  
                   

  • Copy Constructor:A constructor which contains the parameter of same class Type is Copy Constructor.
  • We can copy the data present in one object into another object by making use of Copy Constructor.
         Example:
                         public class clsName()
                        {
                        public string str1,str2;
                           public clsName(string s1,string s2)
                          {
                          this.str1=s1;
                          this.str2=s2;
                          }
                        public clsName(clsname obj)
                        {
                        str1=obj.str1;
                        str2=obj.str2;
                        }
                          
                        }
  • Static Constructor:These Constructors are invoked before first instance of class is created and are used to initialize Static field Members.
  • Static constructors doesn't contains Access Modifiers and Input Parameters.
  • Static Constructors are called only if an Object for a class is Created.
  • We cannot provide an initialization for instance field members as it will get an Compilation error

  • Private Constructor:A class with private Constructor cannot be inherited and it als restricts us from creating an instance for a class.
         Example:
                          public class clsPrivate()
                         {
                             private clsPrivate()   // Creation of Private Constructor
                             {
                             }
                          }

     What is Constructor Overloading
  • Class which consists of two or more Constructors with same Name but difference in Signature is called as Constructor Overloading.
  • Signature means atleast data type of input parameter must be different or Number of parameters must be different.
          Example:
                           public class clsConstruct()
                          {
                             string str1,str2;
                            public clsConstruct(strint tvalue)
                           {
                             this.str1=tvalue;
                           }
                          public clsConstruct(string tvalue,string tvalue1)
                           {
                            this.str1=tvalue;
                            this.str2=tvalue1;
                           }
                         
                          }
     Note: Above  Program is an example for Constructor Overloading with same name but difference                in signature.

     What is difference between Ref and Out Parameter
  • Ref: If we want to pass a variable as Ref Parameter then we meed to initialize a value for a variable before passing to a method.
  • Any changes made in Calling method will get reflected in the Called Method.
           Example:
                          int ival=12;// initializing the value as 12
                         Getdata(ref ival);  //Called method
                 //The value of ival will be 15 as the variable value is changed in the Calling Method
                          Public int Getdata(ref int idata)  // Calling Method
                         {
                           idata=15;
                          }
  •  Out: No need to initialize a value for the Out parameter before passing it to a calling method but it is mandatory to initialize a value with in the calling method.
  • Changes made in the calling method will get reflected in the Called Method.
           Example:
                          int ival1.ival2;  // No need to initialize a value for Out Parameter
                           int iOutput=Getoutputdata(out i,out j);  // Called Method
                            public int Getoutputdata(out int a,out int b)  // Calling Method
                           {
                           a=16;
                           b=17;
                            }

     What is the use of "Using" statement in CSharp
  • With the help of "Using" we can import Namespace
  • Also with the help of "Using" statement it can obtain resources,make use of it and will dispose the object immediately once after the execution of "Using" statement is completed.
           Example:
                          using(sqlconnection obj=new sqlconnection)
                         {
                           obj.Open();
                         }
                 Note: From the above example we didn't close the connection but it will automatically                                   closes the connection once after the Using block is completed.

       What is Serialization
  • Serialization:If we want to pass an object through network then we need to convert that object into stream of bytes is nothing but a Serialization.
        What is the Use of "this" Keyword in C#
  • It behaves just like an Object which refers to an instance of a class and can also access the field members,methods and properties with in the class.
  • We can also invoke a Constructor from another constructor with the help of "this" Keyword is called as Constructor Chaining
      What is Const,Static and Readonly in C#
  • Const: Constant variable need to be declared and initialize a value at Compile time.
  • It is mandatory to assign a value to it.Once after assigning a value we cannot change the value of a const.
  • Read Only:For Read Only we can assign a value at Runtime or we can change a Value at run time but only through Non Static Constructor.
          Example:
                    
                           public clsReadonly()
                         {
                             public readonly int idata;
                            public clsReadonly   // Initializing a value for Read only with in non static Constructor
                            (
                             idata=100;
                            )
                           }
                         

  • Static Read only:We can assign a value for Static Read only at compile time or at Run time and can change a Value at Run time but only through Static constructor and we cannot change further.
         Example:
                        public class clsstatic()
                        { 
                          readonly static int idata=10;  //Assigned a value at Compile time
                            
                        static clsstatic()  // Changing value with in Static constructor
                         {
                           idata=25;
                         }
                           
                         }

      What is an Interface in C#
  • Interface is a class which contains only declaration but no Implementation
  • Interface does not have any Access Modifier and field Members
  • We cannot create an instance for Interface because it contains only declaration but no implementation.
  • If a class inherits an Interface then class has to provide an implementation for all the methods present in an Interface.
  • Interface can contains input parameters and properties.
  • Interface members do not have any access modifiers as they are "Public"  by default .
  • If we provide an Access modifier explicitly then we will get an Compilation error
       Example:
               Interface Isample
              {
                void Getdata();  // Interface with only declaration but no implementation
               }
             Class clsInterface:Isample
               {
                   void Getdata()    // Interface method with declaration and Implementation
                  {
                     Console.writeline("Get the Value");
                  }
                }

     What is Explicit Interface
  • If we have two interfaces with same name and signature and if a class inherits both the interfaces and implements the method then there will be an Interface clash to which method that class need to invoke.
  • In this cases we need to explicitly call the Interface method by providing an Interface name is Explicit Interface.
          Example:
                          Interface Isample
                          {
                            void Getdata();
                          }
                         
                          Interface Isample1
                         {
                           Void Getdata();
                         }
Note: We have two interfaces with same and signature

                     public class clsInt:Isample,Isample1
                     {
                        public void Getdata() // There will be an ambiguity(confusion) to which interface method the class is invoking.To overcome the problem we make use of Explicit interface
                         {
                             Console.writeline("Getting the value");
                         }

                      }
             Explicitly calling the methods

             Example:
                              public class clsinterface:Isample,Isample1
                             {
                                 public void Isample.Getdata()
                                 {
                                    Console.writeline("Isample Interface");
                                  }
                               public void Isample1.Getdata()  // Explicitly calling an Interface
                              {
                               console.writeline("Isample1 Interface");
                              }

                              }             

    What are Value and Reference Type
  • Value Type:A datatype is said to be value type if it hold the value with in the stack or heap based on the scope of a variable is a value type.
  • Reference Type:A datatype is said to be reference type if it holds a value with in the heap and its address is stored in a variable in Stack memory is a Reference Type.
     What are Sealed Class
  • Sealed Class: If we want to restrict a class from being Inheritance then we need to make use of Sealed Class.
  • We should not create a Sealed class with "Abstract " Keyword as it does not allows us to create an instance for a class.
          Example:
                          Sealed class clssealed
                          {
                             public string sealmethod()
                             {
                               return "Sealed";
                              }
                           }

    Difference between Sealed and Static Class
  • Sealed Class:If a class is defined as a sealed then it cannot be inherited.
  • Sealed class can contain static and instance members.
  • Sealed class can have both static and non static Constructor.
  • Static Class:We cannot create an instance for Static class
  • It contains only static Members and static Constructors.
    What is a Sealed Method
  • Sealed Method:If we want to restrict a next level of derived classes from being overriding a virtual method then we need to create a method with sealed along with override Keyword.


    Note: From the above image clsderivde class has overridden and sealed the Virtual method if                  another class clsderived1 tries to override an Virtual method then we will get an compile error shown above.
   What is Method Overloading
  • Method Overloading: It is the process of creating more than one method with same name but different in signature is Method Overloading.
  • Rule for Method overloading is difference in signature means(it must differ in number of arguments it takes or datatype of at least one parameter must be different.)
  • In case of Method overloading Compiler identifies which method it has to be executed at compile type based on the datatype and the number of arguments.Hence it is an example for Compile time polymorphism.


Note: From the above image class has two Addition methods with difference in signature which is a    Method Overloading.


   What is difference between string and String builder
  • Strings are immutable because when we modify a string variable value then a new memory gets allocated and previous memory allocation is released.Where as String builder is Mutable where a variety of operations can be performed on a variable without allocating a new memory  for the modified value
    How to sort an array elements in descending order
  • Below program shown in the image is an example for sorting an array in descending order.




  What is difference between Abstract class and an Interface
  • Declaration and Implementation can be provided in Abstract class where as in interface it provides only declaration but no implementation.
  • We cannot achieve multiple inheritance using Abstract class but we can achieve it by using Interfaces.
  • Abstract class can have Access modifiers for methods where for Interface it cannot have Access modifiers.
  • Abstract class can have field members where as for Interface it cannot contains Field members.
  • Abstract class contains Constructors and destructors but for Interface it cannot contains Constructors and destructors.
   What is difference between Finalize and Dispose methods
  • Finalize:It is used to free an Unmanaged resources like database connections,files which is used by an Object.
  • We cannot call Finalize method explicitly internally it is called by Garbage collector
  • Performance will be slow as it does not clean up the resources immediately as it is called by Garbage collector.
  • Dispose: It is also used to free an Unmanaged resources like Database connections,files.
  • Dispose method should be explicitly called by implementing Idisposable Interface.
  • There is no Performance cost as it clean up the resources immediately.
      What are Generics in C#
  • Generics: It allows us to create classes and methods with Type<T> as parameter which is a type safe and its type can be mentioned at the time of creating an instance which makes generics Type safe.


Note: From the above program Comparedatatype method is mentioned with string data type but if we access the method with int data type it will thrown an compile error as generics is a type safe which is shown above in diagram

  What are the different ways a method can be overloaded
  • Method can be Overloaded if
  1. Number of parameters must be different.
  2. Data type of at least one parameter must be different.
  3. order of parameter must be different.
 Why can't you specify Access modifiers for a method with in the Interface
  • In an Interface method has only declaration but no implementation.If a class inherits an Interface then it has to provide an implementation for all the methods inside the Interface therefore all the methods  in Interface are public by default.
  • If we explicitly provide an Access modifier to an Interface then it will throw an Compile error as shown below.

    What is difference between Struct and a Class
  • Struct:
  • It is a Value type.
  • We cannot assign Null value for a Variable.
  • Struct cannot contains destructor.
  • All variables inside a Struct a public by default.
  • Structs cannot be inherited
     Class:
  • Classes are Reference type.
  • Null values can be assigned to a variable inside a class.
  • Class can have destructor.
  • All variables inside a class are private by default.
     What is difference between "IS" and "AS" Operator in C#
  • "IS" Operator is used to check the type and it returns a bool value.
  • It returns true if both the objects are of same type else return false.
  • "AS" Operator returns an object if both the types are same else it returns Null.
What is a MultiCast delegate
  • A Multicast delegate is one which holds a reference to more than one method is a Multicast delegate.
What are Indexers or Smart arrays in C#
  • Indexers allows us to treat an object just like an array.Indexers are also as a Smart array.
  • Indexers cannot be a Static.
  • Indexers should have at least one Accessor(Get or Set)
What is an Abstract class
  • An Abstract class ia an incomplete class and it cannot be instantiated.
  • It cannot be instantiated because it may contains an Abstract methods which contains only declaration but no implementation.
  • If a class is  derived from an Abstract class then it has to provide an implementation to all abstract methods.
  • Abstract class should be public but not private or static.
Difference between Abstract and Virtual method

Abstract method
Virtual method
It contains only declaration but no implementation. It contains both declaration and implementation
It is mandatory to implement abstract methods It is optional to implement Virtual method.

What is "Virtual" Keyword in a method
  • If we want to change the base class method definition in the derived class then we need to use Virtual keyword for a method in the base class and override keyword in the derived class.
  • But It is optional to override a virtual method.
What is a Managed code process
  • Managed Code is nothing but the code which runs under the scope of CLR runtime environment is a Managed code.
  • VB6 and C++ are unmanaged code as it does not runs under the scope of CLR.
What are Assemblies and types of Assemblies
  • It is a single deployable unit which contains all the information about the implementation of classes,structs.
  • Assemblies generates exe or dll files based on the type of application.
  • Assemblies are of two types
  • Private Assembly:It is used in a single application and resides in a Application path.
  • Shared Assembly:These assemblies can be shared by the multiple applications and can resides in a GAC.
  • Only strong named assemblies resides in a GAC as it contains Public key token.
What is Inheritance
  • If we create a new class from the existing class then it is said to be a Inheritance.If a new class needs a same field members as an existing class then instead of creating those field members again in the new class we can derive it from the existing class is Inheritance
What is Boxing and Unboxing
  • Boxing:It is the process of converting from value type to Reference type is Boxing.
  • Unboxing:It is the process of converting from Reference type to Value type is Unboxing.
What is Encapsulation
  • The process of hiding data and functionality with in a single unit is Encapsulation.
  • The field members which are declared as private are not exposed outside of the class.
  • Encapsulation can be achieved by using Access modifiers(public,private).
What is Polymorphism
  • Having more than one form is Polymorphism.Method overloading and Method overriding are used to implement Polymorphism.
  • There are two types of Polymorphism which are listed below
  • Compile time polymorphism:In this Compiler identifies which form it has to be executed at compile time is Compile time polymorphism.
  • Compiler invokes a form based on the number of parameters and the types of a method and then it decides which method it has to be executed.
  • Method overloading is an example for Compile time polymorphism.
  • Compile time polymorphism is also called as Static or Early binding.
  • Runtime Polymorphism:In this runtime identifies which method it has to be identified based on the object which is created.
  • Method overriding is an example for Runtime polymorphism.
  • It is also called as Dynamic or Late binding.
Define Satellite Assembly
  • A Satellite assembly is a .net framework assembly which contains a resources specific to a given language is a Satellite Assembly.
What is difference between Convert.tostring() and .tostring() method
  • Convert.Tostring() handles a Null values while .Tostring() does not allow Null values it will throw a Null reference exception.
What is a Namespace
  • A Namespace is a container where we group the collection of classes,structs,Interface,delegates and Namespaces.It also used to avoid the conflict between two classes having same name.
What is a Nullable Type in C#
  • In C# types are broadly classified into two types Value types and Reference types.
  • Bydefault all the value types does not hold a Null value if we want to allow a Null values for a Value type then we make use of Nullable Type.
What is a Partial Class in C#
  • Partial class allows us to split the class into two or more physical files and all these classes are combined into a single class when application is compiled.
  • Advantage:It separates the system generated code from the User's developer code
What is a Partial Method
  • It contains only declaration but no implementation.
  • Implementation for a partial class is Optional.Declaration and implementation cannot be provided at same time.
  • Partial method for declaration and implementation should have same signature.
  • Partial method does not have any return type as it may or may not implement a partial method.
What are Access modifiers in C#
  • Private Modifier:A class which contains a private field members are accessible with in the class.
  • Public Modifier:Public field members can be accessible everywhere.
  • Protected Modifier:These field members can be accessible with in the class and it can also be accessible with the classes if a class inherits a class which has a protected field member.
  • Internal Modifier:These are accessible anywhere in the assembly and it is not accessible outside the assembly.
  • Protected Internal:These are accessible with in the assembly and with in the derived classes in another assembly.
Define Property in C#
  • A class contains a field members and if we make fields as public and expose outside the class is bad as there is no control over the data on what gets assigned and what gets returned.To avoid we make use of properties.
  • Property allows us to control the accessibility of a class variables.
  • A property consists of Get and set methods wrapped inside a property.
What is Constructor Overloading in C#
  • Constructor Overloading: If a class contains two constructors with same name but difference in signature is a Constructor Overloading.
What is an Anonymous Method
  • An anonymous method has only body without name,Optional parameter and a return type is an Anonymous Method and it is created using delegate keyword.
What is Operator Overloading
  • Operator Overloading: It is the concept of extending the functionality of existing operator is an Operator Overloading.
What is an Abstraction
  • Abstraction is a process of displaying only necessary features of an object to outside the class and hide the complexity is Abstraction.
What is CLR in .Net
  • Common Language Runtime is a runtime environment and it is a layer which lies in between Language compiler and Operating system.
  • It also manages the execution of program written in different supported languages.
  • It also consists of JIT Compiler which is responsible for converting an MSIL Code into a Native code in which underlying OS can understand.
  • It also contains Garbage collector which is responsible for destroying Unreferred Objects.
What is CTS
  • Common Type System ensures that data types defined in two different languages get compiled into a Common data type.
What is CLS
  • CLS Stands for Common language specification and it is a subset of CTS.
  • It defines a set of rules and regulations that every .net language must follow.The language which follows the set of rules are said to be CLS Complaint.
What is Garbage Collector
  • It is available in CLR and it is responsible for complete Memory management.
  • Allocation of memory and deallocation of memory when life time of an object is completed is done by GC.
  • GC invokes in two cases 
  • When there is no place for new object to be created.
  • When the application execution comes to end.
What is Null coalescing operator in C#
  • Null Coalescing operator uses "??" two question marks where we can use a  custom value for a Null reference variable
What is JIT Compiler
  • JIT Compiler:It is present in CLR and MSIL Code is passed to JIT Compiler which will convert a MSIL code into a Native code in which underlying OS can understand.
  • It compiles only need based code which will improve performance of an Application.
What is MSIL Code
  • The Source code in .net is compiled by the language compiler and converts into MSIL Code which in turn converts into Native code by the JIT Compiler.
  • The MSIL Code is available in the assembly of .Net Application.The MSIL Code is interoperable as the code in any .net language is compiled into MSIL Code.
What are different types of Inheritance
  • There are Five types of inheritance listed below
  • Single Inheritance: When a single derived class is created from the single base class then it is said to be Single inheritance.
  • Hierarchical inheritance: When more than one derived class is created from the single base class then it is said to be Hierarchical Inheritance.
  • Multi Level Inheritance: When a derived class is created from another derived class then it is said to be Multi level Inheritance.
  • Hybrid Inheritance:Any combination of Single,Hierarchical and Multi level inheritance is called as Hybrid inheritance.
  • Multiple Inheritance:When derived class is derived from more than one base class then it is said to be Multiple inheritance.But Multiple inheritance is not supported in C#.
What is Method Overriding
  • Method Overloading:Creating a method in derived class as the same signature in the base class is Method overloading.
  • Method overriding is possible in derived class but not in the same class.
  • Virtual and override methods are used to implement method overriding.
  • If we want to execute the method of derived class rather than base class then we go for Method overriding.
What is a GAC
  • It stands for Global assembly cache and it contains an assemblies which can be shared by all the applications running on the machine without having the copy of that assembly locally.
  • Only strong named assemblies resides in a GAC as it contains a Public key token.
What is method hiding in c# or shadowing in vb.net
  • It is the process of hiding the functionality provided by the base class and it can also change the Return type of a method.
What is a collection
  • Collection:It is a collection of similar datatype which are grouped together is called a collection.
  • Few examples of collection are Arraylist and Hashtable.
  • Arraylist:These are not a type safe collections and its size can increase or decrease dynamically.
  • Hashtable:It us a dictionary entry object in which values are stored in a Key-Value pair.
  • In a Hashtable value can be a Null but Key should not be Null.
  • But the basic disadvantage of collection is boxing and unboxing happens which may degrade performance.These are also not a type safe.To overcome this problem we make use of Generics.
What is an Exception handling
  • Exception handling is a built in mechanism in .net framework to detect and handle runtime errors.Basically errors occurs during the execution of program because of user logic or system failure.
  • If a user does not provide a proper procedure to  handle the exceptions then runtime environment provides a procedure to terminate the current execution of program.
  • Try,Catch and finally  blocks are used to handle exceptions.
  • Try block is enclosed with a statement which might throws an exception where as catch block handles an exception if exists and finally block is used for clean up resources
What is an Extension method
  • Extension method helps us to add a new method to the existing type without modifying the original code or without using an inheritance is an Extension method.
What is difference between Parse and TryParse
  • Parse:It throws an exception if it does not parse a value where as Tryparse does not throws an exception but it returns a bool value indicating whether it is succeeded or not.
How to create a strong Key name
  • In a Visual Studio Command prompt first we need to specify a path where we want to create a file.
  • Then we need to specify sn -k filename.snk
  • It will create a strong key name in the specified location.
What is the use of PDB File
  • PDB is a Program database file which is used to debug our application with the help of PDB file and it is not possible to debug an application if PDB file does not exists.
  • it contains Source file names.Line numbers and the local variable names.
Difference between int and int32
  • "int" is the datatype defined by the c# language where int32 is the datatype defined by the .net Common type system(CTS).
  • int is the primitive data type in c#.net where as int32 refers the base class of int in C#.
How to identify whether object is Managed code or unmanaged code
  • If an Object implements Idisposable interface then an object is said to be Managed or else unmanaged.
What are Func,Action and Predicate
  • Func:It is a delegate for a function that may or may not takes a parameter and returns a value.
  • Action:It is a delegate for a function that may or may not take a parameters and does not returns a value.
  • Predicate:It is a specialised version of function that takes an arguments,evaluates a value against the set of criteria and always returns a bool value as a result.
Difference between Dictionary and Hashtable

Dictionary
Hash table
It is a generic type. It is not a Generic type
It is faster when compare with hash table It is slower as boxing and unboxing happens in case hash table.
It throws an error if we try to find a key which does not exists, It returns null if we try to find a key which does not exists.

Difference between String and string
  • string(string with small s) is just an alias for String.
Difference between throw and throw ex
  • Stack trace:It helps us to display the complete information about the error.It will display the error from the source where the error has occurred to the current execution of the method.
  • throw:If we make use of throw it will display the complete stack trace information.
  • throw ex:if we make use of throw ex it will display only the partial(not complete) information of stack error.
Can we store multiple types in an Array
  • Yes we can store all types if we create an Object array as all the types in .Net are directly or indirectly inherited from object.So we can add any type in an object array.
Why to use finally block even though we have Garbage collector
  • Garbage collector can clear only managed resources as dot net is managed code.But Garbage collector will not clear unmanaged code.So in order to unrefer an unmanaged code we make use of finally block.
What is difference between "==" and ".Equals()"
  • "=="It compares if both the object references are same.
  • ".Equals()" method compares if the contents are same.
What is a Thread and different types of threads
  • Threading in C# is a parallel code execution.A thread is a small set of instruction which allows us to separate(isolate) a work from a process and achieves a parallel code execution by using multiple threads.
  • Different types of threads are listed below
  • Foreground Thread:By default the threads are Foreground threads.Foreground threads are threads which will continue to run until the last foreground thread is terminated.So the application will wait until all foreground threads are terminated,
  • Background Thread:Background threads will get terminated when all foreground threads are closed.Application won't wait for them unti background threads are completed.





No comments:

Post a Comment