HI WELCOME TO SIRIS
Showing posts with label dtt. Show all posts
Showing posts with label dtt. Show all posts

Difference Between Constant and ReadOnly and Static

Constant and ReadOnly keyword are used to make a field constant which value cannot be modified. Static keyword is used to make members static that can be shared by all the class objects. In this article, I am going to explain the difference among these three.

Constant

Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.
  1. public const int X = 10;
A const field is a compile-time constant. A constant field or local variable can be initialized with a constant expression which must be fully evaluated at compile time.
  1. void Calculate(int Z)
  2. {
  3. const int X = 10, X1 = 50;
  4. const int Y = X + X1; //no error, since its evaluated a compile time
  5. const int Y1 = X + Z; //gives error, since its evaluated at run time
  6. }
You can apply const keyword to built-in value types (byte, short, int, long, char, float, double, decimal, bool), enum, a string literal, or a reference type which can be assigned with a value null.
  1. const MyClass obj1 = null;//no error, since its evaluated a compile time
  2. const MyClass obj2 = new MyClass();//gives error, since its evaluated at run time
Constants can be marked as public, private, protected, internal, or protected internal access modifiers.
Use the const modifier when you sure that the value a field or local variable would not be changed.

ReadOnly

A readonly field can be initialized either at the time of declaration or with in the constructor of same class. Therefore, readonly fields can be used for run-time constants.
  1. class MyClass
  2. {
  3. readonly int X = 10; // initialized at the time of declaration
  4. readonly int X1;
  5.  
  6. public MyClass(int x1)
  7. {
  8. X1 = x1; // initialized at run time
  9. }
  10. }
Explicitly, you can specify a readonly field as static since, like constant by default it is not static. Readonly keyword can be apply to value type and reference type (which initialized by using the new keyword) both. Also, delegate and event could not be readonly.
Use the readonly modifier when you want to make a field constant at run time.

Static

The static keyword is used to specify a static member, which means static members are common to all the objects and they do not tied to a specific object. This keyword can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.
  1. class MyClass
  2. {
  3. static int X = 10;
  4. int Y = 20;
  5. public static void Show()
  6. {
  7. Console.WriteLine(X);
  8. Console.WriteLine(Y); //error, since you can access only static members
  9. }
  10. }

Key points about Static keyword

  1. If the static keyword is applied to a class, all the members of the class must be static.
  2. Static methods can only access static members of same class. Static properties are used to get or set the value of static fields of a class.
  3. Static constructor can't be parameterized. Access modifiers can not be applied on Static constructor, it is always a public default constructor which is used to initialize static fields of the class.
What do you think?
I hope you will enjoy the tips while programming with C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Understanding Boxing and Unboxing in C#

Boxing and unboxing are the most important concepts you always get asked in your interviews. Actually, it's really easy to understand, and simply refers to the allocation of a value type (e.g. int, char, etc.) on the heap rather than the stack.

Boxing

Implicit conversion of a value type (int, char etc.) to a reference type (object), is known as Boxing. In boxing process, a value type is being allocated on the heap rather than the stack.

Unboxing

Explicit conversion of same reference type (which is being created by boxing process); back to a value type is known as unboxing. In unboxing process, boxed value type is unboxed from the heap and assigned to a value type which is being allocated on the stack.

For Example
  1. // int (value type) is created on the Stack
  2. int stackVar = 12;
  3.  
  4. // Boxing = int is created on the Heap (reference type)
  5. object boxedVar = stackVar;
  6.  
  7. // Unboxing = boxed int is unboxed from the heap and assigned to an int stack variable
  8. int unBoxed = (int)boxedVar;

Real Life Example

  1. int i = 10;
  2. ArrayList arrlst = new ArrayList();
  3.  
  4. //ArrayList contains object type value
  5. //So, int i is being created on heap
  6. arrlst.Add(i); // Boxing occurs automatically
  7.  
  8. int j = (int)arrlst[0]; // Unboxing occurs

Note

  1. Sometimes boxing is necessary, but you should avoided it if possible, since it will slow down the performance and increase memory requirements.
    For example, when a value type is boxed, a new reference type is created and the value is copied from the value type to the newly created reference type. This process takes time and required extra memory (around twice the memory of the original value type).
  2. Attempting to unbox a null causes a NullReferenceException.
    1. int? stackVar = null;
    2. // Boxing= Integer is created on the Heap
    3. object boxedVar = stackVar;
    4.  
    5. // NullReferenceException
    6. int unBoxed = (int)boxedVar; //Object reference not set to an instance of an object.
  3. Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.
    1. int stackVar = 12;
    2. // Boxing= Integer is created on the Heap
    3. object boxedVar = stackVar;
    4.  
    5. // InvalidCastException
    6. float unBoxed = (float)boxedVar; //Specified cast is not valid.
What do you think?
I hope you will enjoy the tips while programming with C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Understanding Type Casting or Type Conversion in C#

Type Casting or Type Conversion is a mechanism to convert one data type value to another one. Type conversion is possible if both the data types are compatible to each other; otherwise you will get an InvalidCastException.

Different Types of Type Casting or Type Conversion

  1. Implicit conversion

    Implicit conversion is being done automatically by the compiler and no data will be lost. It includes conversion of a smaller data type to a larger data types and conversion of derived classes to base class. This is a safe type conversion.
    1. int smallnum = 654667;
    2. // Implicit conversion
    3. long bigNum = smallnum;
    1. class Base
    2. {
    3. public int num1 { get; set; }
    4. }
    5.  
    6. class Derived : Base
    7. {
    8. public int num2 { get; set; }
    9. }
    10.  
    11. class Program
    12. {
    13. static void Main(string[] args)
    14. {
    15. Derived d = new Derived();
    16. //Implicit Conversion
    17. Base b = d;
    18. }
    19. }
  2. Explicit conversion

    Explicit conversion is being done by using a cast operator. It includes conversion of larger data type to smaller data type and conversion of base class to derived classes. In this conversion information might be lost or conversion might not be succeed for some reasons. This is an un-safe type conversion.
    1. long bigNum = 654667;
    2. // Explicit conversion
    3. int smallnum = (int)bigNum;
    1. class Base
    2. {
    3. public int num1 { get; set; }
    4. }
    5.  
    6. class Derived : Base
    7. {
    8. public int num2 { get; set; }
    9. }
    10.  
    11. class Program
    12. {
    13. static void Main(string[] args)
    14. {
    15. Base b = new Base();
    16. //Explicit Conversion
    17. Derived d = (Derived)b;
    18. }
    19. }
  3. User-defined conversion

    User-defined conversion is performed by using special methods that you can define to enable explicit and implicit conversions. It includes conversion of class to struct or basic data type and struct to class or basic data type. Also, all conversions methods must be declared as static.
    1. class RationalNumber
    2. {
    3. int numerator;
    4. int denominator;
    5.  
    6. public RationalNumber(int num, int den)
    7. {
    8. numerator = num;
    9. denominator = den;
    10. }
    11.  
    12. public static implicit operator RationalNumber(int i)
    13. {
    14. // Rational Number equivalant of an int type has 1 as denominator
    15. RationalNumber rationalnum = new RationalNumber(i, 1);
    16. return rationalnum;
    17. }
    18.  
    19. public static explicit operator float(RationalNumber r)
    20. {
    21. float result = ((float)r.numerator) / r.denominator;
    22. return result;
    23. }
    24.  
    25. }
    26. class Program
    27. {
    28. static void Main(string[] args)
    29. {
    30. // Implicit Conversion from int to rational number
    31. RationalNumber rational1 = 23;
    32.  
    33. //Explicit Conversion from rational number to float
    34. RationalNumber rational2 = new RationalNumber(3, 2);
    35. float d = (float)rational2;
    36. }
    37. }

What is the Upcasting and Downcasting?

There are two more casting terms Upcasting and Downcasting. basically these are parts of Implicit conversion and Explicit conversion.
Implicit conversion of derived classes to base class is called Upcasting and Explicit conversion of base class to derived classes is called Downcasting.
  1. class Base
  2. {
  3. public int num1 { get; set; }
  4. }
  5.  
  6. class Derived : Base
  7. {
  8. public int num2 { get; set; }
  9. }
  10.  
  11. class Program
  12. {
  13. static void Main(string[] args)
  14. {
  15. Derived d1 = new Derived();
  16. //Upcasting
  17. Base b1 = d1;
  18.  
  19. Base b2 = new Base();
  20. //Downcasting
  21. Derived d2 = (Derived)b2;
  22. }
  23. }
What do you think?
I hope you will enjoy the tips while programming with C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.