What Are Access Modifier and Access Level C#?

 

Access Modifier

Access Level

private

The type or member can only be accessed by code in the same class.

protected

The type or member can only be accessed by code in the same class or in a derived class.

internal

The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal

The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

public

The type or member can be accessed by any other code in the same assembly or another assembly that references it.

OOPS - What are Delegates? When and how to use Delegates?

Delegates are same are function pointers in C++, but the only difference is that they are type safe, unlike function pointers.

Delegates are required because they can be used to write much more generic type-safe functions.

A delegate is a type that represents references to methods.

When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type.

 

Code Snippet:

 


public delegate void Del(string message);

// Create a method 1 for a delegate. 
public static void DelegateMethod_1(string message)
{
  System.Console.WriteLine(message);
}

// Create a method 2 for a delegate. 
public static void DelegateMethod_2(string message)
{
  System.Console.WriteLine(message+" !!!");
}

// Instantiate the delegate for method 1.
Del handler = DelegateMethod_1;
// Call the delegate.
handler("Hello World");
//output: Hello World

// Instantiate the delegate for method 2.
Del handler = DelegateMethod_2;
// Call the delegate.
handler("Hello World");
//output: Hello World !!!

 

Programming Scenario:

If we want to execute methods at runtime based on usage then in that situation we can use Delegate.

For Example:

Consider you want to build control preference selector and based on its usage/ where this control is used. we want to save data in different databases.

In this situation will write control to accept/configure name of method which used to save data based on usage/databases where you want to save data.

Once we have function name which should be invoked then will use Delegate to point to configured method. Whenever this is any action on delegate for updating data it will invoke method pointed. 


OOPS - What is Interface?

An Interface is an abstract class which has only public abstract methods, and the methods only have the declaration and not the definition.
These abstract methods must be implemented in the inherited classes.

 

An interface contains only the signatures of methodspropertiesevents or indexers.

A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoApplication
{
 interface MyInterface
 {
  void SetTutorial(int pID, string pName);
  String GetTutorial();
 }

 class MyTutorial : MyInterface
 {
  protected int TutorialID;
  protected string TutorialName;

  public void SetTutorial(int pID, string pName)
  {
   TutorialID = pID;
   TutorialName = pName;
  }

  public String GetTutorial()
  {
   return TutorialName;
  }

  static void Main(string[] args)
  {
   MyTutorial pTutor = new MyTutorial ();

   pTutor.SetTutorial(1,".Net by Guru99");

   Console.WriteLine(pTutor.GetTutorial());

   Console.ReadKey();
  }
 }
}

OOPS - What is Abstract Class?

Abstract classes that cannot be instantiated, and are frequently either partially implemented, or not at all implemented.

 

Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. 

 

Abstract class may implement an unlimited number of interfaces, but may inherit from only one abstract (or any other kind of) class.


What is difference between interface and abstract class?

 

  Interface Abstract
 
Interfaces have all the methods having only declaration but no definition.
In an abstract class, we can have some concrete methods. 

 

 In an interface class, all the methods are public. 
An abstract class may have private methods.
  An Interface contains only the signatures (no code definition) of methodspropertiesevents or indexers.

Abstract modifier indicates that the thing being modified has a missing or incomplete implementation.

An abstract class can provide complete, default code and/or just the details that have to be overridden.

Access Specifier  In C#, Interface cannot have access specifier for functions. It is public by default. In C#, an abstract class can have access specifier for functions.
Instantiation Interface is absolutely abstract and cannot be instantiated. An abstract class cannot be instantiated.
Implemetation

In C#, an interface can only have a signature, not the implementation.

A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.

An abstract class can provide complete implementation.

An abstract class must provide implementation for all interface members.

An abstract class that implements an interface might map the interface methods onto abstract methods

Speed The interface is comparatively slow. An abstract class is fast.
Fields

Interface cannot have fields.

A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.

An abstract class can have defined fields and constants.


An abstract class may contain abstract methods and accessors.

Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.

Methods
Interface has only abstract methods.

An abstract class can have non-abstract methods.

An abstract method is implicitly a virtual method.

Abstract method declarations are only permitted in abstract classes.

Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no curly braces ({ }) following the signature.

It is an error to use the static or virtual modifiers in an abstract method declaration.

Property Interface contains the property declaration and the class contains the implementation.

Use the abstract modifier in a property (or method) declaration to indicate that the method or property does not contain implementation.

Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.

It is an error to use the abstract modifier on a static property.

An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.

Inheritance An interface can inherit from one or more base interfaces.  
Multiple inheritance A class may inherit several interfaces. A class may inherit only one abstract class.
Base Class When a base type list contains a base class and interfaces, the base class must come first in the list. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes.
Derived Class   A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
Sealed   It is not possible to modify an abstract class with the sealed modifier because the two modifers have opposite meanings.
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
Defines Interfaces are used to define the peripheral abilities of a class. An abstract class defines the core identity of a class and there it is used for objects of the same type.

 


OOPS - What is Inheritance?

Inheritance is the ability to create a class from another class, the "parent" class, extending the functionality and state of the parent in the derived, or "child" class. It allows derived classes to overload methods from their parent class. Inheritance is one of the pillars of object-orientation.


OOPS - What is Polymorphism?

 

 

 

 

Overloading

Overriding

Polymorphism:

Compile Time Polymorphism

Run Time Polymorphism

Binding:

Early / Static  Binding

Late / Dynamic Binding

Function Parameters:

Functions with same name and different parameters.

Functions in the extended class with same name and same parameters as in the base class, but with different behaviors.

Code Snippet:

 public class A
 {
 public void Print(int x)
 {
  Console.WriteLine("Parent Method");
 }
 }
 public class B : A
 {
 public void child()
 {
  Console.WriteLine("Child Method");
 }
 public void Print(float x)
 {
  Console.WriteLine("Overload child method");
 }
 public void Print(string str)
 {
  Console.WriteLine("Overload child method  " + str);
 }
 }

//Lets execute code
B b= new  B();
b.Print(10);
//Output- Parent Method
b.Print(10.20);
//Output-Overriding child method
b.Print("Hello");
//Output-Overriding child method Hello

public class A
 {
 public virtual void Print()
 {
  Console.WriteLine("Parent Method");
 }
 }
 public class B : A
 {
 public void child()
 {
  Console.WriteLine("Child Method");
 }
 public override void Print()
 {
  Console.WriteLine("Overriding child method");
 }
 }

  //Lets execute code
  A a = new A();
  a.Print();
  //Output- Parent Method
  a = new B();
  a.Print();
  //Output-Overriding child method

OOPS - What is Abstraction?

Abstract Classes and Methods

Data abstraction is the process of hiding certain details and showing only essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces (which you will learn more about in the next chapter).

The abstract keyword is used for classes and methods:

  • Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).

  • Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the derived class (inherited from).

An abstract class can have both abstract and regular methods:

abstract class Animal 
{
  public abstract void animalSound();
  public void sleep() 
  {
    Console.WriteLine("Zzz");
  }
}

From the example above, it is not possible to create an object of the Animal class:

Animal myObj = new Animal(); // Will generate an error (Cannot create an instance of the abstract class or interface 'Animal')

To access the abstract class, it must be inherited from another class. Let's convert the Animal class we used in the Polymorphism chapter to an abstract class.

Remember from the Inheritance chapter that we use the : symbol to inherit from a class, and that we use the override keyword to override the base class method.

Example

// Abstract class
abstract class Animal
{
  // Abstract method (does not have a body)
  public abstract void animalSound();
  // Regular method
  public void sleep()
  {
    Console.WriteLine("Zzz");
  }
}

// Derived class (inherit from Animal)
class Pig : Animal
{
  public override void animalSound()
  {
    // The body of animalSound() is provided here
    Console.WriteLine("The pig says: wee wee");
  }
}

class Program
{
  static void Main(string[] args)
  {
    Pig myPig = new Pig(); // Create a Pig object
    myPig.animalSound();  // Call the abstract method
    myPig.sleep();  // Call the regular method
  }
}

Try it Yourself »


What Is Difference Between Overloading And Overriding?

 

 

 

 

 

Overloading

Overriding

Polymorphism:

Compile Time Polymorphism

Run Time Polymorphism

Binding:

Early / Static  Binding

Late / Dynamic Binding

  Method overloading is creating a method with the same name within the same class having different signatures. In method overriding, we change the method definition in the derived class that changes the method behavior.
Function Parameters:

Functions with same name and different parameters.

Functions in the extended class with same name and same parameters as in the base class, but with different behaviors.

Code Snippet:

 public class A
 {
 public void Print(int x)
 {
  Console.WriteLine("Parent Method");
 }
 }
 public class B : A
 {
 public void child()
 {
  Console.WriteLine("Child Method");
 }
 public void Print(float x)
 {
  Console.WriteLine("Overload child method");
 }
 public void Print(string str)
 {
  Console.WriteLine("Overload child method  " + str);
 }
 }

//Lets execute code
B b= new  B();
b.Print(10);
//Output- Parent Method
b.Print(10.20);
//Output-Overriding child method
b.Print("Hello");
//Output-Overriding child method Hello

public class A
 {
 public virtual void Print()
 {
  Console.WriteLine("Parent Method");
 }
 }
 public class B : A
 {
 public void child()
 {
  Console.WriteLine("Child Method");
 }
 public override void Print()
 {
  Console.WriteLine("Overriding child method");
 }
 }

  //Lets execute code
  A a = new A();
  a.Print();
  //Output- Parent Method
  a = new B();
  a.Print();
  //Output-Overriding child method

 


OOPS - Structs vs Classes

 

 

  

Struct

Class

Definition: A Struct is a value type if it holds the data within its own memory allocation. A Class is reference type -contains a pointer to another memory location that holds the data.

Speed

Structs stored on the Stack causes additional overhead but faster retrieval.  
Inheritance Structs cannot be inherited.  
Includes:
  • All numeric data types

  • Boolean , Char, and Date

  • All structures, even if their members are reference types

  • Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong

  • String

  • All arrays, even if their elements are value types

  • Class types, such as Form

  • Delegates

Holds Actual Data: Yes No
Pointer to another memory location: No Yes
Example: Char, Integer Class, Object, String
Memory Allocation: On stack or in-line in structure On heap
Data Storage: Structs directly store their data in the struct Classes store a reference to a dynamically allocated object
When to use: Structs are useful for small data structures Classes are useful for large data structures
Peformance: Structs can affect performance Performance of class is very good
Constructor Memory Allocation: A struct constructor simply returns the struct value itself (copy), and this value is then copied as necessary Class constructors are invoked with the new operator, but that does not allocate memory on the heap
Multiple References: With structs, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other. Value of each veriable might have different value. With classes, multiple variables may have a reference to the same object
Inheritance: Structs do not support user-specified inheritance, and they implicitly inherit from type object Class supports inheritance