Saturday, August 29, 2020

Reference Types and Value Types

Value Types

  • Value type are the variables which are stored in its own memory location.
  • Value types are stored in stack according to the order it is created.
Only c will be changed to 7.


Reference Types 

  • Reference types does not stored its value within its own memory location. Instead of that , it stores a pointer/address/reference where the actual value is stored.
  • Reference types are stored in heap. But the variable is stored in stack and data is stored on the heap. 

Both d.hp and f.hp will be changed to 100.

 



Tuesday, August 25, 2020

Upcasting and Downcasting

  •  Upcasting: conversion from a derived class to a base class
  •  All objects can be implicitly converted to a base class reference.  
  •       Shape shape = circle;   // Shape is base class and circle is derived class	
    
  • Downcasting: conversion from a base class to a derived class 
  • Downcasting requires a cast.
  •       Circle circle= circle;   // Shape is base class and circle is derived class	
  • Casting can throw an exception if the conversion is not successful. We can use the as keyword to prevent this. If conversion is not successful, null is returned. 
  •       Circle circle = shape as Circle;
          if (circle != null)
  • We can also use the is keyword
  • if (shape is Circle) {
    var circle = (Circle) shape;
    }

Access Modifiers

  •  In C# we have 5 access modifiers: 
    • Public
    • Private
    • Protected
    • Internal
    • Protected Internal
  • A class member declared with public is accessible everywhere. 
  • A class member declared with private is accessible only from inside the class.
  • A class member declared with protected is accessible for containing class and the derived types of the containing class. 
  • A class member declared with internal is accessible only for current assembly.
  • A class member declared with protected internal is accessible for current assembly and derived types of the containing class.

Monday, August 24, 2020

Properties

  •  A property is a class member that encapsulate a getter/setter for accessing a filed.  
  • As a best practice, we must declare fields as private and create public properties to provide access to them. 
  • A property encapsulates a get and a set method.
  •     public class Customer
        {
            private string _name;
            public string Name
            {
                get { return _name; }
                set { _name = value; }
            }
        }
    
  • Inside the get/set methods we can have some logic.
  •     public class Person
        {
            public DateTime BirthDate { get; set; }
            public int Age
            {
                get
                {
                    var timespan = DateTime.Today - BirthDate;
                    var years = timespan.Days / 365;
                    return years;
                }
            }
        }
    
  • If you don’t need to write any specific logic in the get or set method, it’s more efficient to create an auto-implemented property. An auto-implemented property encapsulates a private field behind the scene. So you don’t need to manually create one. The compiler creates one for you.
  •     public class Person
        {
            public DateTime BirthDate { get; set; }
        }
    
  • Auto-implemented properties are required to specify both get and set, so if you want an auto-implemented property to be read-only, you must use private setters. 
  •     public class Person
        {
            public DateTime BirthDate { get; private set; }
        }
    

Friday, August 21, 2020

Read only and Constants Fields

Readonly
  • When a field is declared with readonly, it needs to be initialized either during declaration or in a constructor.
  •  
        public class Const_V_Readonly
        {
            public readonly int Readonly_Value;
    
            public Const_V_Readonly()
            {
                Readonly_Value = 3;  
            }
        }
    
  • A value can be assigned only once to readonly fileds.
  • We use the readonly modifier to improve the robustness of our code. It prevents from accidentally overwriting the value of a field, which can result in an unexpected state.
  • When use static modifier for the readonly fields, it needs to be initialized either during declaration or in a static constructor. 
  •  
        public class Const_V_Readonly
        {
            public static readonly int Readonly_Value;
    
    	//Access modifiers are not allowed on static constructors
            static Const_V_Readonly()
            {
                Readonly_Value = 3;
            }
        }
  • If consider "Const_V_Readonly" class in AssemblyA , AssemblyB references AssemblyA and uses these values in code. When AssemblyA is compiled, readonly values are like a ref to a memory location. The value is not baked into AssemblyB's IL. This means that if the memory location is updated, AssemblyB gets the new value without recompilation. So if "Readonly_Value" is updated to 30, you only need to build AssemblyA. All clients do not need to be recompiled. 
  • So if you have a constant that may change or when in doubt, use a readonly.


Constants 
  • A const keyword is used to declare constant fields and constant local.
  • The value of the constant field is the same throughout the program or in other words, once the constant field is assigned the value of this field is not be changed. 
        public class Const_V_Readonly
        {
            public const int Constant_Value = 2;
        }
  • The constant field should be initialized on the declaration. (Can not intialize it in a constructor or method)
  • If consider "Const_V_Readonly" class in AssemblyA and AssemblyB references AssemblyA and uses these values in code. When AssemblyA is compiled,  const value is like a find-replace, the value 2 is 'baked into' the AssemblyB's IL. This means that if we update Constant_Value to 20 in the future. AssemblyB would still have 2 till we recompile it.
  • So if you are confident that the value of the constant won't change use a const.

Wednesday, August 19, 2020

Constructors

  •  Constructor is a method that is called when an instance of a class is created. 
  •  Usage of a constructor is to put an object in an early state (To initialize some of the class fields in a class). 
  •  Constructor can be declared as below.
        public class Customer
        {
           //Default Constructor
            public Customer()
            {
    
            }
        }

  • If we don't define a default constructor or parameterless constructor, C# compiler automatically will create it when an instance of a class is created. 
        public class Customer
        {
    	public bool IsMarried;
    	public string Age;
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                var customer = new Customer();
                Console.WriteLine(customer.IsMarried);
                Console.WriteLine(customer.Age);
                Console.Read();
            }
        }
    	
    	Output
    	False
    	0

  • We can also define a constructor with one or more parameter which is called parameter constructor.
        public class Customer
        {
    
    public string Name;
    //Parameter Constructor public Customer(string name) { this.Name = name; } }

  • Constructors can be overloaded. Overloading means creating a method with the same name and different signatures. Signature is what uniquely identify a method. That includes return type, name, parameter type , no of input parameters and order of the parameters.
        public class Customer
        {
            public Customer(){}
            public Customer(string name){}
            public Customer(string name, int Age){}
        }
  • As a best practice, when we have a list of objects inside a class, always the list should be initialized in the constructor or on the declaration. Otherwise it will give an exception.
        public class Order
        {
        }
    
        public class Customer
        {
            public string Name;
            public int Age;
            public List<Orders>;
    
            public Customer()
            {
            }
            public Customer(string name) 
            {
                this.Name = name;
            }
            public Customer(string name, int age)
            {
                this.Name = name;
                this.Age = age;
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                var customer = new Customer();
                var order = new Order();
                customer.orders.Add(order);
                Console.Read();
            }
        }

  • So we should initialize the list of order inside the constructor. But the problem is, when we use other parameter constructors , list will be set to null again. To overcome this, We can pass control from one constructor to the other by using the this keyword.
        public class Customer
        {
            public string Name;
            public int Age;
            public List orders;
    
            public Customer()
            {
                orders = new List();
            }
            public Customer(string name) :this()
            {
                this.Name = name;
            }
            public Customer(string name, int age) : this(name)
            {
                this.Name = name;
                this.Age = age;
            }
        }
  • But still this way is little ugly and hard to maintain. So you should only define a constructor when you really have to initialize some fields and etc. 
Constructors Inheritance

  • When creating an object of a type that is part of an inheritance hierarchy, base class constructors are always executed first. They are not inherited to the derived class and need to define explicitly. 
  •  
        public class Vehicle
        {
            public Vehicle()
            {
                Console.WriteLine("Vehicle is being initialized..");
            }
        }
    
        public class Car : Vehicle
        {
            public Car()
            {
                Console.WriteLine("Car is being initialized..");
            }
        }
    
        public class Program
        {
            static void Main(string[] args)
            {
                var obj = new Car();
                Console.Read();
            }
        }
        
        	
    
    OutPut
    Vehicle is being initialized..
    Car is being initialized..
  • We can use the base keyword to pass control to a base class constructor.
  •  
        public class Vehicle
        {
            private readonly string _registrationNumber;
    
            public Vehicle(string registrationNumber)
            {
                this._registrationNumber = registrationNumber;
                Console.WriteLine("Vahicle is being initialized.. Registration No : " + registrationNumber);
    } } public class Car : Vehicle { public Car(string registrationNumber) :base(registrationNumber) { Console.WriteLine("Car is being initialized.. Registration No : "+ registrationNumber); } } public class Program { static void Main(string[] args) { var obj = new Car("CAS-5276"); Console.Read(); } } OutPut Vahicle is being initialized.. Registration No : CAS-5276
    Car is being initialized.. Registration No : CAS-5276

Saturday, August 15, 2020

Classes and Objects in C#

 Classes

A building block of an application. 










Anatomy of a class is,

1. Data (Represented by fields)

2. Behavior (Represented by methods/functions)










Declaring a class










Class Members

1. Instance - Accessible from an object
         
          var person = new Person();
          person.Introduce();

2. Static - Accessible from the class

         Console.WriteLine(); // Console is the class and WriteLine is a static method. 

    No need to create a object of Console class by using new operator in order to call WriteLine method. 

Objects

Object is a blue print of a class. Also called an instance of a class. It has an identity, attributes and behavior. 











Creating an Object

To create objects, we use "new" operator. By using objects, we can access class fields and methods. 







A Simple Class