Viva - OOP Question C#

OOP Question
a.       Beginner
Important features of Object Oriented programming are:
  • Inheritance
  • Polymorphism
  • Data Hiding
  • Encapsulation
  • abstraction
  • Overloading
  • Reusability 

Inheritance  is a mechanism in which one object acquires all the properties and behaviors of a parent object. 
1. Encapsulation is to hide the member or variable to outside class.
Encapsulation : Wrapping up of data and methods into a single unit is Encapsulation (e.g. Class)
Encapsulation is used for hide the code and data in a single unit to protect the data from the outside the world.
It solves the problem in implementation level.



2.       What is polymorphism?

Polymorphism Mean by more than one form. Ability to provide different implementation based on different number/type of parameters.
Example:
               class A1
        {
    void hello()
              { Console.WriteLine(“Hello”); }
          void hello(string s)
              { Console.WriteLine(“Hello {0}”,s); }
        }



 3.       Difference abstraction and encapsulation?

Encapsulation : Wrapping up of data and methods into a single unit is Encapsulation (e.g. Class)
Abstraction : It is an act of representing only the essential things without including background details. (e.g. Interface)
Abstraction is used for hide the data and giving relevant information.
It solves the problem in design level itself.
Encapsulation:
Encapsulation is used for hide the code and data in a single unit to protect the data from the outside the world.
It solves the problem in implementation level.
 4.       What is difference between Overloading and Overriding?
When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class


5.       What is static class and method?
A class in C sharp declared with static keyword is a C# static class. The static class prevents the object creation and can be used directly without creating any instance of class. A class that is not a static class is used after creating its object with new keyword. But the class that is static is used directly without creating its object.

Static methods have no instances. They are called with the type name, not an instance identifier. They are slightly faster than instance methods because of this. Static methods can be public or private
 6.       How can you prevent your class to be inherited further?

             The keyword “sealed” will prevent the class from being inherited.
 7.       Difference between abstract and interface
Feature
Interface
Abstract class

Multiple inheritance
A class may inherit several interfaces.
A class may inherit only one abstract class.

Default implementation
An interface cannot provide any code, just the signature.
An abstract class can provide complete, default code and/or just the details that have to be overridden.

Access Modfiers
An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public
An abstract class can contain access modifiers for the subs, functions, properties

Homogeneity
If various implementations only share method signatures then it is better to use Interfaces.
If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.

8.       Difference between class and structure

Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that structs cannot inherit

9.       What are the access modifiers?

·         public - The members (Functions & Variables) declared as public can be accessed from anywhere.
·         private - Private members cannot be accessed from outside the class. This is the default access specifier for a member, i.e if you do not specify an access specifier for a member (variable or function), it will be private. Therefore, string PhoneNumber; is equivalent to private string PhoneNumber;
·         protected - Protected members can be accessed only from the child classes.
internal - Internal members can be accessed from anywhere within the application. This is the default access specifier for a class.

10.   What is shadowing or hiding?
Shadowing hides a method in a base class. Using the example in the question you linked:
class A
{
   public int Foo()
     {
            return 5;
     }
   public virtual int Bar()
     {
            return 5;
     }
}
class B : A
{
   public new int Foo()
     {
     return 1;
     }
   public override int Bar()
     {
     return 1;
     }
}
Class B overrides the virtual method Bar. It hides (shadows) the non-virtual method Foo. Override uses the override keyword. Shadowing is done with the new keyword.
In the code above, if you didn't use the new keyword when defining the Foo method in class B, you would get this compiler warning:
'test.B.Foo()' hides inherited member 'test.A.Foo()'. Use the new keyword if hiding was intended.




11.   Difference between Namespace and Assembly?

Namespace: Namespaces are the logical component that consist of many classes.Within a namespace, you can declare one or more of the following types:

1. another namespace

2. class

3. interface

4. struct

5. enum

6. delegate


Assembly :

An Assembly can contain many namespaces. Assemblies contain MSIL code.
Assemblies are Self-Describing. [e.g. metadata,manifest]

Differences:
1)A namespace is logically groups classes.An assembly is physical grouping of logical units.
2)An Assembly contains one or more namespaces
b.      Intermediate
12.   What are generics?
Generics provide the ability to create type-safe collections in .NET.
In other words, generics allow you to write a class or method that can work with any data type.




 
13.   What is a delegate and event?
·         A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.
·   Every action is a an event.In GUI all the controls have the
event action.For example Button,it has the click,double
click,key press,key up,key down,mouse move,mouse up,mouse
down like that.When you can generate the set of task based
on the event.




14.   Can we have Sealed Method in abstract class?


Answer:
Looking at first site the The Keyword Sealed & Abstract are contradictory to each other..In simple terms we can Say Answer is NO...

Look the code below

using System;
abstract class A
{
public abstract void Hello();
public sealed void Hi();
}

when we will complie the code.. we will get the Compile time Error as below

'A.Hi()' cannot be sealed because it is not an override..

But We can have Sealed methods in abstract class when the abstract class is Dervided class .. for Eg.

using System;

class A
{
public virtual void Hello()
{
Console.WriteLine(" Say Hello");
}

}

abstract class B : A
{
public sealed override void Hello()
{
Console.WriteLine(" Say Hi");
}

}
class C : B
{

}
class Demo
{
public static void Main()
{
C c1 = new C();
c1.Hello();// Output is Say Hi
}
}

Can we have an Abstract class without having any abstract method?

No at least one method must be abastract


15.   Can we have Multiple Main Methods in one .cs file?
No
16.   What is the default access modifier of a class?

by Default Internal is the access modifier of class


17.   How does Composition mechanism works?
c.       Advance
18.   Can you override private virtual methods?

No, you cannot access private methods in inherited classes.

19.   Can you prevent your class from being inherited and becoming a base class for some other classes?

Yes. The keyword “sealed” will prevent the class from being inherited.

20.   Can you allow class to be inherited, but prevent the method from being over-ridden?

Yes. Just leave the class public and make the method sealed.

21.   Why can't you specify the accessibility modifier for methods inside the interface?

They all must be public, and are therefore public by default.


22.   Static data members should be initialized inside the constructor. True or False.

False. Static datamembers should not be initialised inside constructor.

23.   What are OOP designs Principles?



According to Wikipedia the definition of SOLID is   

SOLID are guidelines that can be applied while working on software to remove code smells by causing the programmer to refactor the software's source code until it is both legible and extensible. 


S –Single responsibility principle
Wikipedia defines it as “every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class”.
O –Open/closed principle
Wikipedia definition says “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”
·         Software entities (classes, modules, etc) should be open for extension, but closed for modification.
·         In other words, (in an ideal world...) you should never need to change existing code or classes: All new functionality can be added by adding new subclasses and overriding methods, or by reusing existing code through delegation.
·         This prevents you from introducing new bugs in existing code. If you never change it, you can't break it.
L – Liskov Substitution Principle

  • Subtypes must be substitutable for their base types.
·         Derived classes must be usable through the base class interface without the need for the user to know the difference.
·          "An instance of a derived should be able to replace any instance of its superclass"
I – Interface Segregation Principle

  • Clients should not be forced to depend upon interfaces that they do not use.
  • ·         Many client specific interfaces are better than one general purpose interface
·         The dependency of one class to another one should depend on the smallest possible  interface
D – Dependency Injection / Inversion Principle:  .Net MVC fully utilizing this principle.

Wikipedia: The principle states:  

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
 B. Abstractions should not depend upon details. Details should depend upon abstractions.


Dependency Injection (DI) vs. Inversion of Control (IOC)

The main goal of Inversion of control and Dependency Injection is to remove dependencies of an application. This makes the system more decoupled and maintainable

ersion of control
Dependency injection
It’s a generic term and implemented in several ways (events, delegates etc).
DI is a subtype of IOC and is implemented by constructor injection, setter injection or method injection.



http://mohammadnazmul.blogspot.com/2014/05/solid.html
https://www.codeproject.com/Articles/703634/SOLID-architecture-principles-using-simple-Csharp
Delegate 

http://www.tutorialsteacher.com/csharp/csharp-func-delegate http://www.c-sharpcorner.com/UploadFile/8911c4/simple-delegates-with-examples-in-C-Sharp/
http://www.tutorialspoint.com/csharp/csharp_delegates.htm

Before applying the delegate:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {

        GetData("Mahesh");

    }

}

public
 void GetData(string Name)
{

    lblName.Text = Name;

}

Output
Mahesh
After applying the delegate:  
public delegate void MyDelegare(string var);
protected
 void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)

    {

        MyDelegare objMyDelegare = new MyDelegare(GetData);

        objMyDelegare("Mahesh");

    }

}

public
 void GetData(string Name)
{

    lblName.Text = Name;

}

Output
Mahesh


What is reflection?

All .NET assemblies have metadata information stored about the types defined in modules. This
metadata information can be accessed by mechanism called as “Reflection”.System. Reflection
can be used to browse through the metadata information.

Generics
http://tech.priyo.com/tutorial/2014/11/18/26914.html
refer to a feature in C# that allows defining a class or method with type as a parameter.  
Generics allow for designing a classes and methods whose types are specified only at the time of declaration and instantiation.
The List<T> collection class is an example for generic class
benefits in using generics include:
  • Casting is not required for accessing each element in the collection



class Test<T>
{
    T _value;

    public Test(T t)
    {
 // The field has the same type as the parameter.
 this._value = t;
    }

    public void Write()
    {
 Console.WriteLine(this._value);
    }
}

class Program
{
    static void Main()
    {
 // Use the generic type Test with an int type parameter.
 Test<int> test1 = new Test<int>(5);
 // Call the Write method.
 test1.Write();

 // Use the generic type Test with a string type parameter.
 Test<string> test2 = new Test<string>("cat");
 test2.Write();
    }
}

Output

5
cat

using System;
using System.Collections.Generic;

class Program
{
    static List<T> GetInitializedList<T>(T value, int count)
    {
 // This generic method returns a List with ten elements initialized.
 // ... It uses a type parameter.
 // ... It uses the "open type" T.
 List<T> list = new List<T>();
 for (int i = 0; i < count; i++)
 {
     list.Add(value);
 }
 return list;
    }

    static void Main()
    {
 // Use the generic method.
 // ... Specifying the type parameter is optional here.
 // ... Then print the results.
 List<bool> list1 = GetInitializedList(true, 5);
 List<string> list2 = GetInitializedList<string>("Perls", 3);
 foreach (bool value in list1)
 {
     Console.WriteLine(value);
 }
 foreach (string value in list2)
 {
     Console.WriteLine(value);
 }
    }
}

Output

True
True
True
True
True
Perls
Perls
Perls

http://www.dotnet-tricks.com/Tutorial/csharp/FU4N141113-Difference-Between-Constant-and-ReadOnly-and-Static.html

Constants:
1. Constants can be assigned values only at the time of declaration
2. Constant variables have to be accessed using "Classname.VariableName"
3. Constants are known at compile time
Read Only:
1. Read only variables can be assigned values either at runtime or at the time of instance initialization via constructor
2. Read only variables have to be accessed using the "InstanceName.VariableName"
3. Read only variables are known at run time.

const variables can declared in methods ,while readonly fields cannot be declared in methods

enum 

An enumeration is a set of named integer constants. An enumerated type is declared using the enum keyword


class EnumProgram
   {
      enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

      static void Main(string[] args)
      {
         int WeekdayStart = (int)Days.Mon;
         int WeekdayEnd = (int)Days.Fri;
         Console.WriteLine("Monday: {0}", WeekdayStart);
         Console.WriteLine("Friday: {0}", WeekdayEnd);
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces the following result:
Monday: 1
Friday: 5



struct 
struct Books
{
   public string title;
   public string author;
   public string subject;
   public int book_id;
};  

public class testStructure
{
   public static void Main(string[] args)
   {

      Books Book1;        /* Declare Book1 of type Book */
      Books Book2;        /* Declare Book2 of type Book */

      /* book 1 specification */
      Book1.title = "C Programming";
      Book1.author = "Nuha Ali"; 
      Book1.subject = "C Programming Tutorial";
      Book1.book_id = 6495407;

      /* book 2 specification */
      Book2.title = "Telecom Billing";
      Book2.author = "Zara Ali";
      Book2.subject =  "Telecom Billing Tutorial";
      Book2.book_id = 6495700;

      /* print Book1 info */
      Console.WriteLine( "Book 1 title : {0}", Book1.title);
      Console.WriteLine("Book 1 author : {0}", Book1.author);
      Console.WriteLine("Book 1 subject : {0}", Book1.subject);
      Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);

http://www.herongyang.com/C-Sharp/Intermediate-Language-Compile-and-Run-C-Sharp-Program.html
.NET Compilation and Execution


What is .Net Framework ?

The .NET framework is a programming framework from Microsoft. Developers can use .Net Framework to develop applications,install and run the application on Windows operating systems.
What is Common Language Runtime (CLR) ?
Common Language Runtime or CLR is the run-time execution environment of .Net Framework. Converting MS-IL into platform or OS specific code is done by CLR. .
What is MS-IL (Microsoft Intermediate Language) ?
When a program is complied in .Net , the source code will be converted into an intermediate language called  Microsoft Intermediate Language (MS-IL) . This is done by Just-In time Compiler (JIT)
https://www.youtube.com/watch?v=Mz9BlmST31w&list=PLym69wpbTIIEOesltWGUsVnY9HDWbJit_

https://www.youtube.com/watch?v=umfhcv-UxxQ&list=PLiceGnDCE4Xbtd2y-i8v4PfLp47SX6MkV&index=2

https://www.youtube.com/watch?v=sx2U8kQ3DLM&list=PLKiZXxQe7OiC2RzvzDCKmSn-7ZdsXLeSF

https://www.youtube.com/watch?v=_pgUO1iz8Ps&t=9s


Extension Methods




























Transient objects are always different; a new instance is provided to every controller and every service.

Scoped objects are the same within a request, but different across different requests.

Singleton objects are the same for every object and every request.



https://www.dofactory.com/code-examples/csharp/service-lifetimes

















Filters in ASP.NET Core allow code to be run before or after specific stages in the request processing pipeline.
















Comments

Popular posts from this blog

Travel RESUME CV

PTE