September 11, 2020

Basic Concepts of OOP's and C#

Basic Concepts---


1. What is OOP?

Object Oriented Programming

2. Can you write the basic concepts of OOP's?

(I personally think this is not a question to ask, but people do ask these kind of questions.)

Abstraction

Encapsulation

Inheritance

Polymorphism

3. What is a class?

A class is a broad definition of something, an instance (or object) is a specific example that fits under that broader class definition. e.g. TV is a class, and my Samsung TV is my instance.

4. What is an object?

It is the actual instance of a class. e.g. Car is class, Mercedes Benz is an instance.

5. What is Encapsulation?

The Class can encapsulate the details of the logic.


6. What is Polymorphism?

class Employee {

public int getDiscount() {

return 5;

}

}

class InternalEmployee : Employee {

public int getDiscount() {

return 10;

}

}

class Contractor : Employee {

public int getDiscount() {

return 20;

}

}

Employee employee = new Employee();

employee.getDiscount(); // returns 5

Employee employee1 = new InternalEmployee();

employee1.getDiscount(); // returns 10

Employee employee2 = new ContractEmployee();

employee2.getDiscount(); // returns 20

As you see, although the variables have been declared with the same type Employee, and depends its actual initialisation, the same method will be executed differently.

So Polymorphism: Objects may behave differently depending on the "type" while keeping the same interface. we use getter and setter methods to encapsulate and protect fields.

7. What is Inheritance?

One class can extend the features of the other Class, and the first class will be the sub class, usually it implies a more specific type of entity. e.g. Dog is subclass of Pet. Dog is more specific whereas Pet can contain some common features of Pet. This way when I create a class called Cat, I do not need to repeat everything Pet has already got.

We can achieve multiple class inheritance using interfaces that solves diamond problem.

8. Why Properties?
Making the class field is public, exposing it to external world is bad as you will not have controlled over what have assigned and returned.

9. Define a constructor?
Constructor is a method used to initialize an object, and it gets invoked at the time of object creation.
The creation of an object involves allocating the right amount of the memory.

10. Define Destructor?
Destructor is a method which is automatically called when the object is destroyed. You can clean up things there if needed.

11. What is a delegate?
A delegate is a point safe function pointer. It holds a reference pointer to a function.

12. What is a virtual method?
Virtual method is a member method of class and its functionality can be overridden in its derived or subclass class.

13. What is overloading?
Same method name, but different number or type of parameters.
e.g.
void add(int a, int b);

void add(double a, double b);

void add(int a, int b, int c);

14. What is an abstract class?
An abstract class is a class which cannot be instantiated.
It will be inherited by specific type or class. (A type is a class, a class is a type)
An abstract class can contain only Abstract method.
for example-
public abstract class Customer
{
public abstract void print();
}
public class Program: Customer 
{
public override void print()
{
Console.Writeline("Print Method");
}

public static void main()
{
Customer c= new Program();
c.print();

}
}


15. What is a ternary operator?

condition ? expr1 : expr2

If condition is true, expr1 is executed otherwise expr2 will be executed.

16. What is method overriding?

Method overriding is a feature that allows sub class to provide implementation of a method that is already defined in the main class. This will override the implementation in the super class by providing the same method name, same parameter and same return type.

17. What is an interface?

An interface is a contract. An interface is a collection of abstract method. If the class implements an inheritance, and then thereby inherits all the abstract methods of an interface.

18. What is exception handling?
Exception is an event that occurs during the execution of a program. Exceptions can be of any type – Run time exception, Error exceptions. Those exceptions are handled properly through exception handling mechanism like try, catch and throw keywords.

19. Difference between class and an object?

An object is an instance of a class. Objects hold information , but classes don’t have any information. Definition of properties and functions can be done at class and can be used by the object. Class can have sub-classes, and an object doesn’t have sub-objects.

20. What is early and late binding?

Early binding refers to assignment of values to variables during design time whereas late binding refers to assignment of values to variables during run time.

Every Console application should have a console method.

21. what is nullable type?

A nullable type can represent the correct range of values for its underlying value type, plus an additional null value.

The C# Null Coalescing Operator (??) is a binary operator that simplifies checking for null values. It is used to assign a default value to a variable when the value is null.
class Program

{

static void Main(string[] args)

{

string name = null;

string myname = name ?? "abc";

Console.WriteLine(myname);

Console.ReadLine();

}

}


22. What is an array?

An array is collection of similar data types.

23. Difference between Abstract classes and interfaces

The abstract keyword is used to create abstract classes. It can not be instantiated and can not be used as base class , not sealed class.

Abstract classes can have implementations for some of its members but the interface can not have implementation for any of its members.

Interface can not have fields where as as abstract class can have fields .

A class can inherit from multiple interfaces at the same time , where as a class cannot inherit from multiple classes at the same time.

Abstract class members can have access modifiers where as an interface members can not have access modifiers.

24. Difference between Abstract class and Sealed Class?

abstract means a class can be used as base class
sealed means class can not be used as base class

25. What is Enums?
Enums- If a program use set of integral numbers, consider replacing them with enums , which makes the program more readable, maintainable. these are strongly typed constants.

26. Difference between implicit and explicit conversion?

Implicit conversion- It is done by compiler when there is no loss of information if the conversion is done .

for example- Converting an int to float will not loose any data.

Explicit Conversion- For example- when we convert a float into int , we loose the fractional part and also a possibility of overflow exception.In this case , explicit conversion is required. We can use cast operator.

27. What is lambda Expression?

lambda Expressions- Anonymous methods => is called lambda operator. for example- to find an employees id with id=1

you can use lambda expression-

Employee em= listEmployee.Find((Employee em)=>em.id == 1);

28. Static member and static method-

Static member- when a class member is declared with static keyword is called static member. If I create 3 objects of a class, I will have 3 sets of instance members in the memory, where as there will be one copy of static member, no matter how many instances of class are created.

Static method:
Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.

 Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.

Static methods cannot be overridden, they can however be hidden using the 'new' keyword. Mostly overriding methods means you reference a base type and want to call a derived method. Since static's are part of the type 

Static method some cases we have specific method we do not need to create object of class
We do not need to create object all the time. blueprint we can avoid allocate the memory in our application by not need to create an object

29. What is Structs?
Structs is a value type where class is a value type. Struct are stored on stack where classes are stored on heap.

30. what does Type and Type member mean?
Classes, Structs, delegates, enums and interfaces are called as types and fields, properties , constructors and methods that normally reside in the type are called type members .

31. what are access modifiers?
Private - Only within the containing class 
Public - Anywhere 
Protected -  Within the containing type and type derived from the containing type 
Internal - A member with an internal modifier is available anywhere within the containing assembly  

32. What are attributes?
Attributes allows you to add declarative to your programs. For example-obselete 

33. what is Dictionary?
A dictionary is the collection of key value pair.
When we create a dictionary , we have to specify the type for key and value.

For example-
using System;
using System.Collections.Generic;
namespace Dictionary
{
   public  class Program
    {
        private static void Main(string[] args)
        {
            Customer c1 = new Customer()
            {
            id = 100,
            name = "krtishma",
            salary = 20000
        };
 Customer c2 = new Customer()
        {
            id = 101,
        name = "hari",
            salary = 300000
           };
`    Customer c3 = new Customer()
        {
            id = 103,
        name = "Reami",
            salary = 400000
             };
          Dictionary<int, Customer> diccustomer = new Dictionary<int, Customer>();
            diccustomer.Add(c1.id, c1);
            diccustomer.Add(c2.id, c2);
            diccustomer.Add(c3.id, c3)
    Customer cust;
            if (diccustomer.TryGetValue(111, out cust))
            {
                Console.WriteLine("ID ={0} Name ={1} salary ={2}", cust.id, cust.name, cust.salary);

            }
            else {
                Console.WriteLine("key not found");
            
            }
            Customer customer103 = diccustomer[103];
            //instead of key value pair we are using var
            foreach (KeyValuePair<int, Customer> CustomerKEyvaluepair in diccustomer)
            {
                Console.WriteLine("ID ={0}", CustomerKEyvaluepair.Key);
                Customer cus = CustomerKEyvaluepair.Value;
                Console.WriteLine("ID={0}name ={1} Salary ={2}", cus.id, cus.name, cus.salary);
 }
            foreach (Customer cus in diccustomer.Values)
            {
                Console.WriteLine("ID ={0} Name ={1} salary ={2}", cus.id, cus.name, cus.salary);
            
            }
            foreach (int key in diccustomer.Keys)

            {
                Console.WriteLine(key);
                
                // Console.WriteLine("ID ={0}", CustomerKEyvaluepair.Key);
                //Customer cus= CustomerKEyvaluepair.Value;
                //Console.WriteLine("ID={0}name ={1} Salary ={2}",cus.id,cus.name,cus.salary);


            }
public class Customer
        { 
        public int id { get; set; }
            public string name { get; set; }
            public int salary { get; set; }
}
        
        
33. What is list?
List is generic collection class can be used to create a collection of any type. we can sort a list , reverse a list, contains, start with different methods we can use..
public  class Program
    {
        private static void Main(string[] args)
        {

            Customer c1 = new Customer()
            {
            id = 100,
            name = "krtishma",
            salary = 20000

        };


        Customer c2 = new Customer()
        {
            id = 101,
        name = "hari",
            salary = 300000
            
            };

            List<Customer> customers = new List<Customer>(2);
            customers.Add(c1);
            customers.Add(c2);
           Console.WriteLine("are salary greater than 5900",customers.TrueForAll(x => x.salary > 4000));
            //if (customers.Contains(c2))
            if(customers.Exists(cus=>cus.name.StartsWith("p")))
            {
                Console.WriteLine("");

            }
            else {
                Console.WriteLine("");
            
            }

HOW TO RESIZE AN ARRAY- 
array.resize(ref arrayname, 7);


public bool method(string color)
return ( color.tolower()== "green" ) ? true: false 




            
       
























No comments:

Post a Comment

Please let me know if you have any doubts.

Key concepts in Pipeline

 1. Agent- To build your code or deploy your software using azure pipelines, you need at least one agent. Two types of agent- Microsoft host...