Operators

Below is the list of operators used is C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApp
{
    class Operators
    {
        //Arithmetic: + - * / %
	//Assignment: = += -= /= %= ++ -- &= ^= != <>=
	//Comparision: == != > = <=
	//Logical operators: && || !
        //Bitwise operators: * | ^ <> ~
    }
}

#operators

Access Levels

Below is the example to understand the access modifier in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApp
{
    public class AccessLevels
    {
        public AccessLevels() { 
        
        }
        public int intPublic; //unrestricted access.
        protected int intProtected;//own or derived class.
        internal int intInternal;//own assembly.
        protected internal int intProtectedInternal;//own assembly or derived.
        private int intPrivate;//own class only.

        //All are accessible in same class.
        public void AccessibleInSameClass() {
            intPublic = 0;
            intProtected = 0;
            intInternal = 0;
            intProtectedInternal = 0;
            intPrivate = 0;
        }
    }

    //Private members are not accessible in derived class.
    public class DerivedAccessLevels : AccessLevels {
        public void AccessibleLevels() {
            intPublic = 0;
            intProtected = 0;
            intInternal = 0;
            intProtectedInternal =0;
        }
    }

    //Only Public, Protected Internal And Internal are accessible in another class.
    public class AnotherClass {
        public void fnAccess(AccessLevels objAccessLevels) {
            objAccessLevels.intPublic = 0;
            objAccessLevels.intInternal = 0;
            objAccessLevels.intProtectedInternal = 0;
        }
    }
}

#access-modifier

Objects in C#

(Almost) Everything is an object is .net and C#. We all know that int, char, string, date, double etc are the primitive data types. But all these data types are derived from system.object.

To understand this lets take an example of int data type. We all know that int is derived from System.Int32; but we can declare the variable of int type using below mentioned two ways

int i = new int();
int j = 0;

where first option is like abject instance creation. When we use the . (dot) operator on i then it will give us different methods like .ToString(), .Equals() for object equality, .GetType() to get type. Hence this proves that all these primitives data types also derived from object (system.object) base class.

datatype

 

#object

Value Type and Reference Type

Value Type:

  • Small type that have their values allocated on the stack in memory.
  • Cannot be null; must always contain data.
  • When passed in method (by val), they are coped as new objects.So the original  value will never change only the copy will change.
  • Cost is low on performance and memory because values are small.
  • Derived from system.valuetype and are sealed (it cannot be inherited).

Reference Type:

  • Can consume significant resources but have more features.
  • Can be null and reference to heap-based (.Net managed) objects.
  • When passed in methods (by ref) only a reference to object is passed. Changes to reference data change the source.
  • No wasted resource because a copy of the object is not made.
  • Cost is an issue with performance and memory because references need to be managed by .Net and must be garbage collected.

 

#reference-type, #value-type

Logging Exceptions in Window’s Event Log

When we develop an application we do the exception logging using various ways. For example, logging exceptions in database, writing in text files, sending emails and etc.

In this article we will see how we can log the exceptions in window’s event logs and how to read the same.

To log exception in windows event log, you first need to import the System.Diagnostics name space to get the access of classes required to log the exceptions.

Below is the simple code which is logging the “divide by zero” exception.

 try
        {
            decimal a, b, result;
            a = "10.0";
            b = "0.0";
            result = a / b;
        }
        catch (Exception err)
        {
            // Write the information to the event log.
            // Register the event source if needed.
            if (!EventLog.SourceExists("DivideByZeroApp"))
            {
                // This registers the event source and creates the custom log,
                // if needed.
                EventLog.CreateEventSource("DivideByZeroApp", "ProseTech");
            }

            // Open the log. If the log doesn't exist,
            // it will be created automatically.
            EventLog log = new EventLog("ProseTech");
            log.Source = "DivideByZeroApp";
            log.WriteEntry(err.Message, EventLogEntryType.Error);

        }

When you open the Windows event log you will get the exception source as “DivideByZeroApp” and on double click of that exception actual exception logged using Exception.Message property.

To read the exception from windows event log, below is the code.

 // For maximum performance, join all the event
 // information into one large string using the
 // StringBuilder.
 System.Text.StringBuilder sb = new System.Text.StringBuilder();
 EventLog log = new EventLog("ProseTech");
 foreach (EventLogEntry entry in log.Entries)
 {
 // Write the event entries to the StringBuilder.
 if (entry.Source == "DivideByZeroApp")
 {
   sb.Append("Entry Type:");
   sb.Append(entry.EntryType.ToString());
   sb.Append("Message:");
   sb.Append(entry.Message);
   sb.Append("Time Generated:");
   sb.Append(entry.TimeGenerated);
   sb.Append("====================================");
 }
 }

#logging-exceptions, #windows-event-log

Code Refactoring – Part 3

Making Conditions Easier to Read: There are many ways to do this, we will discuss on few out of them

1) Decompose Conditional: It means though conditions can be read easily even if they are complex in nature but can be difficult in future to read by another developer so break them in the form of method.

In first article, we have seen the below example

if((order.getTotal() > 99 && (stock.CheckStatus(order.getItem()) > order.getQuantity())) || _balance > 4000){
        Console.WriteLine(“Everything is fine.”);
}

and we have organised it by replacing the temporary variables.

This can be form as per below

if(checkOrderCustomerStatus()){
         Console.WriteLine(“Everything is fine.”);
}

public bool checkOrderCustomerStatus(){
     if((order.getTotal() > 99 && (stock.CheckStatus(order.getItem()) > order.getQuantity())) || _balance > 4000){
         return true;
     }
     return false;
}

2) Consolidate Conditional Expression: If you have code like below where you are checking multiple conditions and returning the common output then you can club those together.

if _balance > 0
return true;

if_isEmployee
return true;

Then what you can do, you can create a common method which will check these conditions and return the output.

Public bool Validate(){
  if(_balance > 0 || _isEmployee){
   return true;
  }
  else {
   return false;
  }
}

3)Consolidate Duplicate Conditional Fragments: It deals with the duplicate code, for example assume that you are performing some conditional checks, if condition meet then you are doing some calculation and the assigning the calculated value to a variable and then value you are passing to a function and same code you have return multiple time, then you can take out that code out and write only once.

#code-refactoring, #conditional-refactoring

Code Refactoring – Part 2

Move Method Refactoring:  Move method can be apply with help of below steps

1) Scan the code

2) Check the superclass/subclass

3) Create the new method and rename if necessary

4) Copy the code

5) Replace the original call

Code smell for move method are

>> Feature envy: Method is more related to another class than the class in which it is defined.

>> Inappropriate intimacy: Two classes are not doing more than just calling each others properties and method to server the purpose, so it is better to apply the move method refactoring by looking into the code.

>> Shotgun surgery: This we can notice when we apply the code changes, for example when we make the changes in class A then we need to make some changes in class B and then in class C and so on.

Extract Class Refactoring: As we see that as the project is growing class is also growing with the new properties and methods, even though those are related to that class but can be split into another class and then use in the parent class.

Code smell: large class

Example: Customer class with Address.

Inline Class Refactoring: This refactoring is apply only when we lets say when we have applied the move method, move fields and move class refactoring on a class and there hardly something left, so it will be better to move that content into the another class which we see more related to it.

 

 

 

#code-refactoring, #code-smell, #move-method, #move-method-refactoring, #refactoring