Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

virtual vs override keyword in c#

 

# virtual keyword :- The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class.For example, this method can be overridden by any class that inherits it:

 

   public virtual double Area()

    {

        return x * y;

    }

 

#You cannot use the virtual modifier with the static, abstract, private, or override modifiers.

 

# override keyword :- The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or event of base class into derived class.

 

enum keyword in c#

 


# enum keyword :- In C#,For define enumeration type we used enum keyword, an enum can assign the constant names to a group of numeric integer values.Enum is a value type data type. 

Enumeration types can be define directly inside a namespace,class, structure. 

Enum Properties:-

  • Enum used to give a name to each constant so that constant integer can be refered by its name.
  • By default, the first members of an enum have the value 0 and value of each succesive member is increased by 1.
  • Members of enum is also know as enumration list.
  • Enum contains its own value and can not inherit or can not pass to inheritance.
  • An Explicit cast is neccessary to convert from enum to integral type.   
Example:- Default Enum Values

using System; 

namespace ConsoleApplication

{

    class Program

    {

        enum WeekDays

        {

            Monday,     // 0

            Tuesday,    // 1

            Wednesday,  // 2

            Thursday,   // 3

            Friday,     // 4

            Saturday,   // 5

            Sunday      // 6

        }

 

        static void Main(string[] args)

        {

            Console.WriteLine(WeekDays.Monday);           //output: Monday

            Console.WriteLine(WeekDays.Tuesday);           //output: Tuesday

            Console.WriteLine(WeekDays.Wednesday);      //output: Wednesday

            Console.WriteLine(WeekDays.Thursday);         //output: Thursday

            Console.WriteLine(WeekDays.Friday);             //output: Friday

            Console.WriteLine(WeekDays.Saturday);         //output: Saturday

            Console.WriteLine(WeekDays.Sunday);           //output: Sunday

 

        }

    }

}


Example:- Assign Values to Enum Members

using System; 

namespace ConsoleApplication

{

    class Program

    {

        enum Categories

        {

            Electronics = 1,

            Food = 5,

            Automotive = 6,

            Arts = 10,

            BeautyCare = 11,

            Fashion = 15,

            WomanFashion = 15

        } 

        static void Main(string[] args)

        {

            Console.WriteLine(Categories.Electronics);

            Console.WriteLine(Categories.Food);

            Console.WriteLine(Categories.Automotive);

            Console.WriteLine(Categories.Arts);

            Console.WriteLine(Categories.BeautyCare);

            Console.WriteLine(Categories.Fashion);

            Console.WriteLine(Categories.WomanFashion); 

        }

    }

}


Conversion:- An Explicit cast is neccessary to convert from enum to integral type.   

         using System;

namespace ConsoleApplication

{

    class Program

    {

        enum WeekDays

        {

            Monday,     // 0

            Tuesday,    // 1

            Wednesday,  // 2

            Thursday,   // 3

            Friday,     // 4

            Saturday,   // 5

            Sunday      // 6

        }

 

        static void Main(string[] args)

        {

            Console.WriteLine(WeekDays.Friday); //output: Friday

            int day = (int)WeekDays.Friday; // enum to int conversion

            Console.WriteLine(day); //output: 4

 

            var wd = (WeekDays)5; // int to enum conversion

            Console.WriteLine(wd);//output: Saturday 

        }

    }

}

Keyword in C#

 

Keywords :- C# contains reserved words that have special meaning for the compiler. These reserved words are called "keywords". Keywords cannot be used as an identifier (name of a variable, class, interface, etc.).

Keywords in C# are distributed under the following categories:

#Modifier Keywords:-Modifiers allow or prevent certain parts of programs from being modified by other parts.

abstract,const,readonly,new,virtual,override,sealed,static.

#Access Modifier Keywords:-Access modifiers are applied to the declaration of the class, method, properties, fields, and other members. They define the accessibility of the class and its members.

private,public,protected,internal.

#Contextual keywords:- A contextual keyword is used to provide a specific meaning in the code, but it is not a reserved word in C#. Some contextual keywords, such as partial and where, have special meanings in two or more contexts.

async,await,yield,var,dynamic,partial

#Statement Keywords:-Statement keywords are related to program flow.

if,else,while,switch,for, foreach,in,throw, try,catch, finally.

#Parameter Keywords:-These keywords are applied to the parameters of a method.

params,ref,out,in

#Namespace Keywords:-

using, .operator , :: operator.

var vs dynamic keyword in c#

    
# Diff between var and dynamic keyword.
In C#, variables must be declared with the data type. These are called explicit typed variables.
Example: Explicitly Typed Variable
int i = 100;// explicitly typed variable
Note:- explicit means precisely and clearly expressed(here i is a variable of integer data type)
 
C# 3.0 introduced var keyword to declare method level variables without specifying a data type explicitly.var is called implicit typed local variable.
Example: Implicitly Typed Local Variable
var j = 100; // implicitly typed local variable
 
Note:- Implicitly-typed variables must be initialized at the time of declaration; otherwise C# compiler would give an error: 
var i; // Compile-time error
 

In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time. The dynamic type variable is created using dynamic keyword.

Example:-

 
    class Program
    {
        dynamic i;
 
        static void Main(string[] args)
        {
            dynamic j=100;
        }
    }
 
 var vs dynamic
  • var is a statically typed variable. It results in a strongly typed variable, in other words the data type of these variables are inferred at compile time. This is done based on the type of value that these variables are initialized with.var type of variables are required to be initialized at the time of declaration or else they encounter the compile time error: Implicitly-typed local variables must be initialized.
  • dynamic are dynamically typed variables. This means, their type is inferred at run-time and not the compile time in contrast to var type.dynamic type variables need not be initialized when declared.
 
Example:- 
class Program
    {
        //Used as a Field
        dynamic i;               
        static void Main()
        {           
            //Implicit Type Local Variable
              var a=10;
            //Nullable<int> b = null;
            //Local Variable
            //Explicit Typed             
              int b=20;
            //Dynamic Type
              dynamic c=30;
            Console.WriteLine("Value of A:" +a);
            Console.WriteLine("Value of B:" + b);
            Console.WriteLine("Value of B:" + c);
        }
    }
 


Constant Vs ReadOnly in C#

 


# const vs readonly in c#


Constant:- The Constant refer to fix values that the program may not alter during its execution.These fixed values are also called literals.

  

 Example:-

    class Program

    {

       const double pi = 3.14159;    // Can be Used as field 

        const double pi;              // Error- Initialization must, outherwise compilation error occur


         public void Print()

        {

            const double pi = 3.14159;  //:- Can be Used as a local variable  

            Console.WriteLine("value of PI: " + pi);

        } 

        static void Main(string[] args)

        {

            Program obj = new Program();

            obj.Print();

        }

    }


Types of Constant

  • Integer Constant
  • Float Constant
  • Character Constant
  • String Constant
  • Enumeration Constant

 

Note:- Hence it is necessary that you assign a value to a constant variable/fields at the time of its declaration.The const keywords can be used before a fields and a local variable.The const field values will be evaluated during the compile time in c#.


ReadOnly:- Read-only fields in c# can be created by using readonly keyword. In c#, the readonly fields can be initialized either at the time of declaration or in a constructor. The readonly field values will be evaluated during the run time in c#.

 Example 1:-

 

   class Program
 
    {
 
        readonly string first_Name = "John";
        readonly string last_Name; //Initialization is not neccessary
 
        public void Print()
 
        {
            readonly string first_Name = "John";  // Can not be used as a local variable
 
            Console.WriteLine("Value of Name:" + first_Name);
 
        }
 
        static void Main(string[] args)
 
        {
 
            Program obj = new Program();
 
            obj.Print();
 
        }
 
    }


 Example 1:- Initialize using readonly using constructor


    class Age

    {

        private readonly int _year;

        Age(int year)

        {

            _year = year;

        }

   

        public static void Main()

        {

            Age obj = new Age(2022);

            Console.WriteLine("Age=" +obj._year);

        }

    }


We can assign a value to a readonly field only in the following contexts:-


  • When the variable is initialized in the declaration.

  • In an instance constructor of the class that contains the instance field declaration.

  • In the static constructor of the class that contains the static field declaration.

New Keyword in C#

 

# new keyword 

1.Instance Creation:- The new operator creates a new instance of a type.To create a new instance of a type, you typically invoke one of the constructors of that type using the new operator.


2.Method Hiding:-You can also use the new keyword as a member declaration modifier. When used as a declaration modifier, the new keyword explicitly hides a member that is inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base class version.


Example:-

    class BaseClass

    {

        public void Print()

        {

            Console.WriteLine("I am in BaseClass");

        }

    }

 

    class DerivedClass : BaseClass

    {

        public new void Print()      //Method Hidding

        {

            Console.WriteLine("I am in DerivedClass");

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            DerivedClass obj = new DerivedClass();     //Instance Creation

            obj.Print();

        }

    }