Saturday, 25 February 2017

Detailed explanation of Value Types and Reference Types


          

Detailed explanation of Value Types and Reference Types

1.      What are the categories of data types in C#?

  • ·         Data types are categorized into 2 types in C#.  They are value types and reference types.

2.       What are the differences between values types and reference types? Explain with example where ever necessary.           

·         Value types are stored in Stack and reference types are stored in Heap.


Lets create an example class to explain various things in detailed.


Memory allocation for value types and reference Types
Memory allocation for value types and reference Types

Below example is to explain what’s object and what is the reference.

Class obj = new Class();

new Class() // constructor call to create an object which stays in heap.

Class obj // This is declaration of reference variable which can hold the address of Class.

However for our comfort we call obj in the above code as object instead of reference.

Comments are added for method TestValueAndRefTypes in class Practical to explain what happens in memory after execution of each line of code.

 public void TestValueAndRefTypes()
 {
            Practical objPrac= new Practical();
           
            
  Let’s see what happens in memory after above line of code runs.

·         When the Above code runs Object is created for Practical class in Heap and it’s address is assigned to the reference variable ObjPrac.
·         As ObjPrac is local to the method. This pointer stays in Stack and pointing to the Object created in Heap.

·         ObjPrac will hold memory for below 3 variables in the Heap.

              TestA, TestB and ObjectCls which are its properties.

·         Even though TestA is int it resides in Heap as it’s actually under object. TestB which is string is also stored in Heap. ObjectCls object is created in Heap as expected and it’s reference also stays in Heap.


            int valA = 10; // valA variable gets placed in Stack memory.

            string valB = "ValB"; // valB gets placed in Heap.

        }

Now let’s see how the copying happens in values types and reference types

with examples

Copying reference variables

// Value Types
int a = 1;
int b = a; // Value of a is  copied to be.
b = 2;   // As a and b be are independent changing b should not impact a value.
           
Output:

 
Output of When one value type is copied to another

Copying of Reference types


 Console.WriteLine("\n Test Copying of Class Object");

 TestValueAndRef objTestFirst = new TestValueAndRef();
 objTestFirst.XXX = 10;
 objTestFirst.YYY = "Original";           

 TestValueAndRef ObjTestCopy = objTestFirst;

 // Address of objTestFirst is copied to ObjTestCopy

// Now modify the values of Copy
ObjTestCopy.XXX = 20;
ObjTestCopy.YYY = "Modified";
Console.WriteLine("objTestFirst.XXX :{0} \n,objTestFirst.YYY : {1}", objTestFirst.XXX, objTestFirst.YYY);
Console.WriteLine("End : Test Copying of Class Object");

Output:

 
When Reference Type variables are copied
When Reference types variables are copied

Copying of String variable 

String acts like value type though it’s a reference type.
Example for Copying String variables

string RefB = "RefB";

·         One object is created in heap for RefB.

string RefC = RefB;

·         If String acts like ref type address of RefB should be copied to RefC
And if Recf Changes, RefB should change to maintain the same value as RefC
But that doesn't happen. Only value is copied to RefC and Change to RefC doesn't
impact RefB.

RefC = "RefC";
  Console.WriteLine("RefC ={0}", RefC);
  Console.WriteLine("RefB ={0}", RefB);
           
Output.

 
Whe one string copied to another
When one string copied to another

3.      What do you mean by string is immutable?


·         String is immutable means once variable is assigned with some value, it cannot be changed.

              Example: String is Immutable

       string RefB = "RefB"; // One object is created in heap for RefB
       RefB = "New" + RefB;
           
             Instead of changing the value in the existing Object,new Object is created in heap for string,
             Every time you try to assign/change a the value of it.

             Though it  can't be seen here that’s how things happen internally.
             

4.      What is StringBuilder ? What is necessity for StringBuilder in C#?


·         As string is immutable as string value changes in the program more number of objects are created in the memory which is memory overhead. This can be overcome with StringBuilder
which maintains only one Object and if value changes for the Object, new object will not be created. Hence StringBuilder should be alternative for String when string likely to have more changes.

              Example for StringBuilder:


           StringBuilder sbStr = new StringBuilder();
            sbStr.Append("Test1");
            sbStr.Append("Test2");
            sbStr.Append("Test3");
            Console.WriteLine("String Builder Value:{0}",sbStr);

Output:
           
 
String Builder Example
StringBuilder Example

Copying of  StringBuilder

String Builder is a reference type and it behaves as expected unlike string which acts like value type.
StringBuilder sbStr = new StringBuilder();     
sbStr.Append("Test1");
sbStr.Append("Test2");
sbStr.Append("Test3");
           
// Copying of StringBuilder
StringBuilder newSBStr = sbStr;
newSBStr.Append("New Value added");

Output:
Copying One String Builder to Another
Output :Copying One String Builder to Another



5.      What is Boxing and Unboxing?

·         Converting Value types to reference type is called Boxing and converting the boxed reference value to value type is called Unboxing.

6.      When is the memory of value type and reference types released?

·         As value types are stored in Stack and actually releases the memory one variable gets out of scope.
·         For example a variable declared inside a method loses it’s memory which is stack immediately after exaction of that method.But references types which are stored in the heap doesn’t release memory even after being out of scope. The memory of these objects which are heap will be flushed or released by garbage collector which runs automatically at certain intervals to claim the unused objects memory.


                                                                                 

Monday, 20 February 2017

Important notes on Access specifiers in C#


                         Everything about access specifiers.



To use any class can be public, private etc. we should be using corresponding namespace. Everything we talk about here is in assumption that Namespace is already used and dll is already added to the program.         

Public class:


There is no limit for Public class on where it can be accessed.

Within the assembly if you are accessing in the different namespace, namespace of the public class should be added.

If accessing outside the assembly, dll or assembly of class should be added to
the project and namespace also should be added.


Internal class :

Internal Class can be accessed only with in the assembly.
[*Namespace should be used if working in different namespace*]

Below are some important Questions


1.    What is default specifier for Class?
 
ANS: Internal
      
2.   What is default specifier for Method?
        A: Private is the default access specifier.
      
3.   What is default specifier for Interface?
        A: Default Access specifier is public for members in Interface.
      
4.  Can an Interface have private members?
        A: Interface can not have private Members

5.  What is default specifier for Constructor?
       A: Public is the default access specifier for constructor.
      
6.  What if we create a private constructor?
        A: Private constructs blocks us from creating an object.protection-level issues comes up when trying to create an object.
      
7.  Can we have a private class?
        A: Yes .we can have a private class .
        But a class directly under namespace can be only Public or Internal.

8.  What is the necessity of nested class?[Out of scope of this article.]
      
9.  Can a derived class have a bigger scope than its base class?

        Ans: No.Base class should always have higher access scope.

10. Can we call Base class protected method from the derived class with base class object?
         Ans: Base class protected Method cannot be called with the even with the base class  object In the derived class.

        Protected Method or field can be called only with the derived class object in the derived Class.




Run time polymorphism. Necessity for Virtual,Override and New



                       Virtual,Override and NEW


1. What is the meaning of 'DerivedClass_B.X()' hides inherited member 'BaseClass_A.X()'. Use the new keyword if hiding was intended?

Ans: Visual studio gives this warning as precaution when in future if you
we have same method in both the classes.C# compilers just warns because it thinks that
We have put our effort to write a method in derived class and if we really want to hide to it keep hidden use new ..Compiler will stop worrying about it.

2. Why does base class method is called when below code is executed?
             
BaseClass_A ObjBaseX = new DerivedClass_B();
ObjBaseX.X();

Ans:

Lets start with the basics... When an object is created it just gets some space.

If Derived class object references to derived class object like

BaseClass_A ObjBaseX = new DerivedClass_B();
           
and if a method is called like

ObjBaseX.X();

Method written for Base class will be called.

Methods are not instance specific. Object's won't have copies of methods of their own'
           
 As methods won't contain any data,they are just set of lines of code.


 * So now it's clear why C# compiler gives warning. It wants to know if method written in derived class is intentional or accidental.
 
  For that we have we need to mention virtual in the base class method
  If derived class method is to be given top priority keep Override.
  If derived class method has nothing to do with base class Keep New.
 





Example Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InheritanceAndPolymorphism
{
    class Program
    {
        static void Main(string[] args)
        {

            //// Base class methods.
            BaseClass_A objBase = new BaseClass_A();
            objBase.X();
            objBase.Y();
            objBase.Z();

            BaseClass_A ObjBaseX = new DerivedClass_B();
            ObjBaseX.X();
            ObjBaseX.Y();
            ObjBaseX.Z();

            Console.ReadLine();
        }

        interface IStudent
        {
            BaseClass_A GetStudent();
            int GetInt();
        }
    }

       


    class BaseClass_A
    {
        public void X()
        {
            Console.WriteLine("BaseClass_A Method_X");
        }
        public virtual void Y()
        {
            Console.WriteLine("BaseClass_A Method_Y");
        }
        public virtual void Z()
        {
            Console.WriteLine("BaseClass_A Method_Z");
        }
    }
    class DerivedClass_B : BaseClass_A
    {

        public void X()
        {
            Console.WriteLine("");
        }
        public override void Y()
        {
            Console.WriteLine("DerivedClass_B Method_Y");
        }
        public new void Z()
        {
            Console.WriteLine("DerivedClass_B Method_Z");
        }
    }
}