Translate to your language...

Showing posts with label .Net Scenario Based Questions. Show all posts
Showing posts with label .Net Scenario Based Questions. Show all posts

5 November 2014

Most Confusing Questions in C# and OOPS

Hi Friends,

This post is regarding the Most Confusing Questions in .Net, C#.Net, ASP.Net and Sql Server. As I have seen that lot of people whether they are searching for jobs, already in the job or they try to understand the things, gets lot of confusions and there are very rare sites where they explain the things in  more detailed and example way.
So I thought to write such post which will be helpful for all of us to try to understand the things in better manner and it will be helpful whether we are in search of job or in actual implementation in our projects:

1. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. How?
Ans. Abstract class is the collection of abstract and concrete members. I am not calling here method or function but members because members can be methods or properties or indexers etc.
A concrete member means non-abstract or general members.
Versioning of a class means adding or removing the members from the class.
So as per question statement, in abstract class we can add or remove the members and it will not impact your classes which are inherited by the abstract class. The only thing is if the class doesn't contain non-abstract members. As the abstract class can contain both abstract and concrete members so it hardly matters to add or remove any non-abstract members.
So we can make another version of the class by adding or removing members in the class. So if we update the base class or the abstract class by adding or removing any non-abstract member, the child class will have no impact, it will be automatically inheriting the new members.
public abstract class MyClass
{
 public abstract void Show();
 public int Add(int a, int b)
 {
  return a+b;
 }
}
This is the abstract class and we can inherit it to the child classes.
Let’s say:
class ChildClass:MyClass
{
 public override void Show()
 {
  // some implementation
 }
}
Now we can create another version of abstract class by adding an extra method;
public abstract class MyClass
{
 public abstract void Show();
 public int Add(int a, int b)
 {
  return a+b;
 }
 public int Sub(int a, int b)
 {
  return a-b;
 }
}
Now it hardly matters for the child class to modify anything.

2. If a new version of an interface is required, you must create a whole new interface.
Ans. For interface which is the collection of abstract members is less flexible. Because when we need to create another version of interface, means adding or removing a member which is abstract so we need to change all the child class either remove or adding override members.
Let's see with the example:
interface MyInf
{
 void Show();
 void Print();
}
Now use this interface in our class:
class ChildClass: MyInf
{
 public void Show()
 {
  // some implementation
 }
 public void Print()
 {
  // some implementation
 }
}
Now if we add another member in the interface, we need to implement it to all our child classes so it is preferable to create another interface and inherit that as below:
interface MyInf2
{
 void Display();
}
Use this in the class:
class ChildClass: MyInf,MyInf2
{
 public void Show()
 {
  // some implementation
 }
 public void Print()
 {
  // some implementation
 }
 public void Display()
 {
  // some implementation
 }
}

3. What are the advantages of properties (get, set)? When we go for properties? What is the difference with using properties and without using properties?
Ans: Properties are the way to carry the data from one class to another class, from one application to another application etc.
When we want to send the data from one class to another class or event one application to another application, we can set the value and get its value to another place.
We can do our tasks without using the properties and in that case we need to send our data as the parameters and get it to another class as below:
class A
{
 public int IsValid(int val1, int val2, string val3, string val4)
 {
  B objB = new B();
  int result= objB.Validate(val1,val2,val3,val4);
 }
}
Now in the class B, we will have the Validate method and will do the validation based on the input values:
class B
{
 public int Validate(int val1, int val2, string val3, string val4)
 {
  // some processing
 }
 return true;
}
here we can see that we have not used the properties for sending the data from class A to class B. And it will work fine.

Now we will try the same task using the properties. We will create a class which will contain all the properties as below:
public class MyProperties
{
 public int Val1{get;set;}
 public int Val2{get;set;}
 public string Val3{get;set;}
 public string Val4{get;set;}
}
Now we will try to set these value and pass this whole object to another class:
class A
{
 public int IsValid(int val1, int val2, string val3, string val4)
 {
  var objMyProperties= new MyProperties()
  {
     Val1 = val1,
     Val2 = val2,
     Val3 = val3,
     Val4 = val4,
  };
  B objB = new B();
  int result= objB.Validate(objMyProperties);
 }
}
And your B class will be:
class B
{
 public int Validate(MyProperties objProperties)
 {
  var value1 = objProperties.Val1;
  var value2 = objProperties.Val2;
  var value3 = objProperties.Val3;
  var value4 = objProperties.Val4;
  // some processing
 }
 return true;
}
Here we can see that if we are adding additional properties or removing the existing properties, our call will not affect in class A and then method signature will also be same in class B.

But in the first case, if we remove one parameter or add additional parameter, we need to make the changes in the Class A calling method as well as the method signature in the Class B also.

4. Can we write goto statement in Finally block.
Ans: No. We can’t write the goto statement in finally block. We can write the goto statement in try or in catch block because finally block must execute all the statements inside whether the exception raised or not. So the control can't move to outside from finally block.

If we try to do, it will show the compile time error saying "Control cannot leave the body of finally clause".  



5. Two class nested ,can we call upper class in inner class?
Ans: Yes, we can class the upper class inside the inner class.

6. Can get and set method have another access modifier  ?
Ans: Yes. We can have protected or private with the access modifiers in getter and setter.

7. Can class declare protected?
Ans: No. The class can NOT be declared as private, protected or protected internal. Not only the class, any elements inside the namespace can't be declared as private, protected or protected internal. We can declare the class either internal or public.
If we create a class with the private or protected modifier, it will show the compile time error:

8. Can abstract class have constructor?
Ans: Yes, abstract class can also have constructor where we can initialize the members.

9. Can a instance class have static constructor?
Ans: Yes, the instance class can have static constructor.

26 January 2014

Scenario Based Questions in Microsoft Technologies - .Net with Answers



Hai Friends,
As we know that getting more experience and then going for the interview requires more knowledge and if we see, it requires more practical knowledge.
So in the continuation, I am trying to post few questions of OOPS which are scenario based and will be helpful when you are going for the interviews with 3+ years experience. These questions will definitely make you to think something more which you were thinking before about the answer of a particular question. With the hope that these questions and answers will be helpful to you, I am posting them and will try to update and include more in the future.
These questions are scenario based questions in .Net technologies which will help to prepare for the interviews. Few questions are related to OOP’s concepts, and then few on Garbage Collector and memory related. So you can prepare them accordingly. These questions will be useful for those who are having the 3+ years experience and looking out for the opportunities in good companies.

1.     How the Encapsulation is different from Abstraction? I think both are used to hide the unnecessary details? Then how they are different?
Ans.
Yes, Both Encapsulation and Abstraction do the same thing but with few differences.
Encapsulation mainly encapsulates the object and so hides the details as well as it binds the data. 
So Encapsulation = Hiding + Binding the data
How it hides the data? Real-time Example?
Take the example of n-Tier application where we have an additional layer called Business Objects. This layer
contains all the entities with their properties. Take an entity name: Employee. This Employee will have the
class name "EmployeeBO.cs" and contains the public properties like EmpId, EmpName, Sal ets
EmployeeBO.cs
So this is the presentation of one property in the Business object class. Now wherever we want this attribute,
We just need to create the object of this class and set/get the value of EmpId as:
// set the EmpId
EmployeeBo objEmployeeBO = new EmployeeBO();
objEmployeeBO.EmpId = 101;
    
// get the EmpId
int empId = objEmployeeBO.EmpID;
Now the question is where its setting or getting the value?
EmpId is the public property in the EmployeeBO class and contain no value. Only _empId contains the value
which is private and so it is not accessible.
So binding of the data happens to the EmpId through _empID and hiding happends through _empId which is
private. The Data is accessed through the Public property while the actual data is in private variable. So
     binding + hiding using Encapsulation.
     Abstraction is to ignore the unnecessary details and get the required details. So it also hides  the unnecessary details. How?
     Abstract class is the special type of class which can contain the abstract and concrete members. If we define
     The member (Method/Property) as abstract, it must be overrides to the child class. We are not bothering here About the non-abstract or concrete members. Which is an unnecessary detail? If we ad an additional concrete Member in the abstract class, we need not to do anything in the child class. But if we add the abstract members, we must have to override it. So abstract doesn't care about the concrete members which are unnecessary for it and so it hides those details.

2.     What do you mean by early binding and late binding in the object bindings? Which is good? Please give me a scenario where you have used the early binding and late binding concepts in your application?
Ans.In .Net, the early binding and last binding concepts comes under the polymorphism. As we know that there are 2 types of polymorphism-
     1. Compile Time polymorphism
      2. Run time polymorphism
    The Compile Time polymorphism also called as the Overloading where we have the same method name with different behaviors. By implementing the multiple prototype of the same method, we can achieve the behavior of the Overloading.
   Also this behavior is valid only for a single class. It means we should have all the overloaded methods in the same class.
     e.g.
    
   The Run time polymorphism also named as the Overriding. This concept works in between classes or multiple classes or parent child classes where the child class has to get the behavior of the base class by inheriting the base class.
    In this concept we generally have an abstract or virtual method in the base class and we override that method in the child class by using the override method.
    e.g.
  
    So now we know the Compile Time polymorphism and Run Time polymorphism. The compile time polymorphism uses the concept of early binding and Run time polymorphism uses it as the late binding.
     In early binding, the runtime (CLR) gets the behavior in the compilation of the program. It means that the method behavior will get compiled before in the early binding.
    In Late binding, like Overriding, the behavior of the class and methods gets by the CLR when creating the object means at runtime. So, in the late binding the behavior of the class members identified by the CLR at runtime.
    Now come to the next part of the question-which is good?
   One can’t say about the answer of this question, there are the scenarios where the early binding is good. When you have lot of objects and in that case, the early binding behavior performs well. While the late binding will be good when we have less objects. Let’s say you want the dropdown list to be loaded when you click on it and not while the loading of the page. So in some scenario, it will be good if we have while load and it will not be good when you click.
    So it’s all depends on how you have implemented and the form structure.

3.  In garbage collection, how the object generations come in the picture? How many generations an object can have? Please tell me the process of disposing the objects based on the generations? Can an object move from one generation to another? If yes then why? What’s the need to have different generations as we are going to dispose the objects which are marked by the Garbage collector?
Ans. 
    Let’s start with what is Garbage collection first and then we will come to our main question of the post. As we know that all the objects created using the new operator gets fits in to the Heap memory. So whenever a new object gets created, it tries to fit in the heap memory. Now let’s say the heap memory is full and there is no place to keep another newly created object.
    In that case the Garbage collector installed, which is the background process, runs through CLR and take the unused objects memory. It mainly cleanup the heap memory and the new objects get placed in to it.
     Now the question comes that for which objects it reclaims for the memory? How the object generations come in the picture?
    It depends on the objects generations. The CLR finds out the objects which are no longer used by the application since longer time and then the Garbage collection reclaim their memory.
     How many generations an object can have? Please tell me the process of disposing the objects based on the generations?
    Actually there are 3 generations exists for the objects which are written under the .Net framework library. When a new object gets created, by default it moves to the generation 0.
     Can an object move from one generation to another?
    Now when the generation 0 objects gets occupied with the memory and garbage collector gets called by the run-time. It checks the objects which are no longer used by the application and mark them for deletion. After deleting or reclaim the memory, the older objects moved to next generation i.e. Generation 1. Now the next time the CLR will check for the Generation 1 object too and if it finds that in generation 1 if the objects are not used since longer time, it will mark them for release and move the remaining objects to generation 2.
     In generation the objects which are under the main method, exists as they gets removed either at the end of the program or when both the generation 0 and generation 1 objects are using.
     What’s the need to have different generations as we are going to dispose the objects which are marked by the Garbage collector?
     With the different generation, it improves the performance of the application as the Garbage collector need not to check for each of the objects in the memory. It first checks for the generation 0 objects and reclaim the memory. If still needs then goes to the generation 1 and then 2.

4.     What is object graph in garbage collector? Is this the graph physically exists? Or how this graph gets created?
Ans. When the Garbage Collector gets called by the CLR to DE-allocate the memory in the heap, the Garbage Collector start finding the references of all the reachable objects which are currently in use. So it find the objects which are used by the processes and for rest of objects which are un-reachable or the Garbage collector is not able to find the references for them, it marks them for deletion.
    Here the Garbage collector makes an Object graph which keeps track of all the objects which are marked for deletion. After the deleting the references for those objects, the heap memory gets compacted and a new root becomes available to use by the new created object.
    Is this the graph physically exists? Or how this graph gets created?
    No, this object graph creates virtually by the Garbage Collector to keep all the objects and to make them for deletion. This is the Garbage Collector responsibility to create this object graph and gets the references of each reachable object which are used by the application

5.     Can we suppress the Garbage collector? If yes, then why do we need to suppress it as it is used to reclaim the unused memory and which improve s the performance of our application?
Ans. Yes, We can suppress the Garbage Collector. There is the Static method in GC class called as SupressFinalize. 
    GC.SuppressFinalize(objectName);
    This Static method takes a parameter for the object. So we can pass it to suppress the claiming memory for this object.
    Now the question comes "why do we need to suppress it as it is used to reclaim the unused memory",
    So, whenever we are using dispose method for class object,which is capable of disposing the object and in that case we don't need to use this method to again reclaim the memory.
    e.g.
    public class DemoClass : IDisposable
{
   public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}
    As we have seen above,the DemoClass is inherited by IDisposable interface and which have the Dispose method to implement.
    Hence after implementation of Dispose() method, we need not to reclaim the memory using the Garbage collector and so we can use the SuppressFinalize() for the current class object.

6.  We already have the Finalize method which reclaims the memory using the Garbage collector. This is automatic process then why do we have the Dispose () method? Is this method different from Finalize ()? What is the interface from which the Dispose () method inherited?
Ans. Yes, We have the Finalize() method which is used to reclaim the memory for the unused objects. The Finalize() method is sufficient to release the memory from heap for the un-referenced object but it is only for the managed objects. So Finalize() method can reclaim the managed objects memory from the heap which are not used since longer time.
    Then what about the objects which are unmanaged? The objects which are out of .Net CLR? The objects  where the CLR can't be used to manage? Dispose() method is used for all those objects which do not comes under CLR or under the Managed heap. Dispose() method can be overrides and can be written to reclaim the object of those classes. Dispose() method is implemented by using the IDisposable interface.
e.g.public class TestClass : IDisposable
    {
          public void Dispose()
         {
            Dispose(true);
         }
} 
7.     Can we call the Finalize() method to be executed explicitly when we want that particular object memory to be reclaim by the Garbage Collector? If yes, then where do we need to write the code? If no then why?
Ans. No, the Finalize() method can't be called as Explicitly. The Garbage collector calls it when the Heap memory is having no space to allocate the new object in the heap.
    Finalize() method is mainly used to perform the cleanup on the unmanaged resources which are held by the current object.
    Working Finalization: Until the Finalize method is overrides, the Garbage collection doesn't mark the object to claim its memory.Internally the Finalization Queue keep each of the objects which are marked for deletion by GC  and then the Finalize() method gets called.
    The Object must be inaccessible(no reference found) to put or keep in the Finalization Queue.
    Limitations: There are the limitation for Finalization:
    a. Un-Deterministic - it is hard to find that when the Finalize() method will be called.
    b. There is no guarantee that which object will be disposed first.
    The C# compiler doesn't allow the overriding of Finalize() method an due to that we need to write the Destructor of the class.
    As the GC is non-Deterministic so we can implement the Dispose() method explicitly to claim the unused memory by the Garbage collection.
    For More details on GC, check the link:
    GC Internal

8.     Can we inherit child class from 2 base classes? If yes then how? If not then why? What is this scenario called as in OOPs? How to implement this kind of scenario where we need to inherit the methods from more than one base class?
Ans. No, We can't inherit more than one base class in to child class. This leads to the Multiple Inheritance where the child class can inherit more than one base class and the Multiple Inheritance doesn't support in .Net.
    So this scenario is called as Multiple inheritance(a type of inheritance in OOPs).
    If you do so, you will see the error 'Interface name expected.' as below:
    
  

    To implement these kind of scenarios, we need the help of Interfaces, Where we can convert the second base class to Interface and then we can inherit one base class and second Interface.
    
  


9.     How the Virtual methods are different from General methods? Can we have a method in the base class and then in the child class can we write the same method? If not? Why? What is the error we will get if we write the same method in the child class with the same name as the parent class method name?
Ans. Yes, Virtual methods are different from the general method. The Virtual       methods are the special type of methods which can be overrides in the           child class and then the child class method will be the output or the default     result.
    
 
        And when creating the child class object, it will take the child class method     as the preference as below:
 

   Now, if we have the same method in the child class as base class then it        will hide the base class method by default and what ever is implemented in    the child class will get executed.
  
    So here we can see that the error will not come but it will show the warning    to use the  'new' operator instead to hide the base class method. This scenario is called as Shadowing in the OOPs.


10. Why do we need abstract class or abstract members? Can’t we simply write the general methods and fulfill our requirements? Can we get any advantage by implantation of abstract members? As per the abstract class scenario, let’s say we have an abstract method called Show () in the abstract base class. Now if I am inheriting this base class to a child class, we need to override this abstract method to the child class. And then we will call this method by creating instance of child class.Now if we only have the method in the child class and then create the instance and call the same method? Then why abstract class method? Is that method doing anything here?
Ans. Abstract class or abstract members(methods, properties) are those which     are not complete. So when the class contains at-least one abstract                 member,the class must be defined with abstract class.
    We can also say that 'When the class does not provides the full                     functionality, we can declare the class as abstract'. the abstract class             works based on the child class memory. Due to that we cant create the           object of Abstract class, instead we can create the reference of the                 abstract class.
    


11. How abstract class and interfaces are different? Can’t we create an abstract class by having all the members as abstract members and wherever required inherit and implement its members? Then why interface? I think interface is also doing the same thing? Then how they are different?


12. Can we have abstract properties in Interface? If yes, then how to write the syntax for the abstract property which is having the return type string?


13. Can we write static methods inside a non-static class? Is it possible to call a non-static method inside the static method? If yes then how?


14. Shadowing is the special type of overriding? How? Please explain?


15. When we inherit a class which is having the private members. Are the private members also gets inherited? If yes? Why cant’ we get them by the class object? If no then why?


16.  What is the Difference between Coupling and Cohesion? If the components are more cohesive the software is good? Or vice versa?



17. See the below code snippet and think about the output.




18.  What is the Difference between HTTP enabled WCF Service and Web Services? I think if we restrict the WCF service just for the HTTP communication, both WCF and Web Service will have the same behavior. Then why still people prefer to have the WCF service rather than the Web Service. What all the things which can be achieved through HTTP enabled WCF service and cant be just from Web Service.

19.  What is the Difference between SOAP enabled Services and ReST Services? Which one is preferred and why?


Sr .Net Consultant | MCP Certified | Microsoft Technologies(.Net with Sql Server, MVC, AngularJS

My photo
Kuala Lumpur, Kuala Lumpur, Malaysia
Overall 17.0+ years of experience in software industry as a Programmer/Developer/Architect with Web & Windows application development and Maintenance, including analysis, design, coding, testing and documentation. • Proficient in Microsoft Technologies i.e. Visual Studio with .Net Framework. • Excellent analytical, problem solving, communication, interpersonal skills with the ability to handle multiple tasks or projects working independently or in a team. • Consistent attention to detail with an ability to analyze and interpret the implication of decisions to minimize bugs and create user-friendly applications. • Experience of Collaborating with Clients and Team Members. Ability to convey Technical Information at all levels. • Ability to work with team/management to ensure successful execution of project management tasks including scheduling, scope management, outside dependency coordination and priorities resolution. • Experience in working with global clients like UK, USA, Europe, Australia etc. and teams located remotely (e.g. Sydney, Australia, USA, and Sweden). • Worked with the Swedish client ManpowerGroup at onsite client location Stockholm, Sweden.