C# virtual vs override

Virtual vs Override

Virtual means making another version of same method in a child class, simply check for newer implementations before calling but abstract method is guaranteed to be overridden in all derived classes. In programming terminology it means that it can modify a method, property, indexer or event declaration and allow it to be overridden. A method cannot be overridden in a derived class unless it is declared as virtual or abstract. For abstract class no implementation is required in the base class because it will be redefined in the derived class.

When a virtual method is called on a reference, the actual type of the object that the reference refers to is used to decide which method implementation to use. When a method of a base class is overridden in a derived class, the version in the derived class is used.

Example: Using override

using System;
namespace HelloWorld
{
 class Hello 
 {
    static void Main() 
    {
       Base b = new Derived();
       b.SomeMethod();

       Derived d = new Derived();
       d.SomeMethod();
    }
 }

public class Base {
     public virtual void SomeMethod()
     {
        Console.WriteLine("From base class"); 
     }
 }

public class Derived: Base {
     public override void SomeMethod()
     {
        Console.WriteLine("From derived class"); 
     }
 }
}

Output:
From derived class
From derived class

Example: Using New

using System;
namespace HelloWorld
{
 class Hello 
 {
    static void Main() 
    {
       Base b = new Derived();
       b.SomeMethod();

       Derived d = new Derived();
       d.SomeMethod();
    }
 }

public class Base {
     public virtual void SomeMethod()
     {
        Console.WriteLine("From base class"); 
     }
 }

public class Derived: Base {
     public new void SomeMethod()
     {
        Console.WriteLine("From derived class"); 
     }
 }
}

Output:
From base class
From derived class

Using the new keyword instead of override, the method in the derived class doesn’t override the method in the base class.
If you don’t specify new or override, the compiler will give a warning but the result output will be same as new.

Base b = new Derived();
Here I am creating the instance of Derived class but stored the reference in base. This is valid because Derived class is inherited from base. Derived class can perform all the operations that a base class can do but Base class will not be able to perform the operations of Derived class. Therefore you cannot reverse the declaration like Derived d = new Base().

When non-virtual method is called, the compiler already knows the actual method but for virtual methods the compiler has to lookup from down to up the hierarchy.

An overriding property declaration may include the sealed modifier. The use of this modifier prevents a derived class from further overriding the property. The accessors of a sealed property are also sealed.

C# Collection of reserved keywords

Keywords

A
abstract as
B

base
bool
break
byte

C

case
catch
char
checked
class
const
continue

D

decimal
default
delegate
do
double

E

else
enum
event
explicit
extern

F

false
finally
fixed
float
for
foreach

G

goto

I

if
implicit
in
int
interface
internal
is
lock
longnamespace
Main() – this is the method where your program starts running. When the program is first loaded it will look for the Main method.

N

new
null

O

object
operator
out
override

P

params
private
protected
—–
public
The public keyword exposes members to other classes.

using System;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Panda p1 = new Panda ("Pan Dee");
            Panda p2 = new Panda ("Pan Dah");
            
            Console.WriteLine(p1.Name);
            Console.WriteLine(p2.Name);

        }
    }
    
    public class Panda
    {
        //instance field
        public string Name;
        
        
        //Constructor
        public Panda (string n)
        {
            //Assign the instance field
            Name = n;
            
        }
    }
}

If instance field was declared private the program class will not be able to access it.

R

readonly
ref
return

S

sbyte
sealed
short
sizeof
stackalloc
Sealed
– Class cannot be inherited anymore
Static
– Static class cannot be instantiated, cannot use the new keyword, there is no instance variable. Contains only static members and is sealed.

static member – is callable when no instance of the class is created, not associated with an instance of the class

class SomeClass {
    public int InstanceMethod() { return 1; }
    public static int StaticMethod() { return 42; }
}


SomeClass instance = new SomeClass();
instance.InstanceMethod();   //Fine
instance.StaticMethod();     //Won't compile

SomeClass.InstanceMethod();  //Won't compile
SomeClass.StaticMethod();    //Fine

– You need to initiate your class to call InstanceMethod
– You cannot invoke non static method from static method
string
struct
switch

T

this
throw
true
try
typeof

U

uint
ulong
unchecked
unsafe
ushort
using – reserved word to instruct the compiler to include a namespace. eg using System; Using statement ensures that an object is disposed of when it goes out of scope.

V

virtual
void – keyword means that the method we are about to describe does not return anything, the method will not return anything.
volatile

W

while

Contextual keywords

A

add
ascending
async
await

B

by
descending
dynamic

E

equals

F

from

G

get
global
group

I

in
into

J

join

L

let

N

nameof operator
The nameof operator returns the name of any symbol (type, member, variable, and
so on) as a string:

int count = 123;
string name = nameof (count); // name is "count"
O

on
orderby

P

partial

R

remove

S

select
set

V

value
var

W

when
where

Y

yield

C# Identifiers and Keywords

Identifiers and Keywords

Collection
Set of objects grouped together
Contextual keywords
Can be used as identifiers. With contextual keywords, ambiguity cannot arise within the context in which they are used.
Link to Collections of reserved and contextual words
Identifiers
Are names that programmers choose for their classes, methods, variables, and so on.
An identifier must be a whole word, essentially made up of Unicode characters starting with a letter or underscore. C# identifiers are case-sensitive. By convention,
parameters, local variables, and private fields should be in camel case (e.g., myVariable), and all other identifiers should be in Pascal case (e.g., MyMethod).
Keywords
Are names that mean something special to the compiler. Most keywords are reserved, which means that you can’t use them as identifiers.
If the identifier conflicts with reserved keyword, you can add @ prefix.

class @class {...}
Namespace
Is a place where particular names have meaning.
Strongly Typed
Datatype of the object is known and available in the system
eg

public int SumNum(int a , int b)
{
	return a+b;
}

Calling the function

int result = SumNum(10+20);

Will show error if you call

int result = SumNum(10+"20");