Delegates in C#. An Overview

A delegate is a type that refers to a static method or an instance method, and then used to call this method.

Following code explains how to create and use a delegate.

Steps involved are

1)Define the delegate type to specify its signature.
2)Declaring the Delegate Variable
3)Initializing the Delegate Variable with reference to any function
4)Calling the function

public class Program
 {
    //Defining the Delegate type
    public delegate double ProcessDelegate(int param1, int param2);

    public static double Multiply(int param1, int param2)
       {
            return param1 * param2;
       }

    public static double Divide(int param1, int param2)
       {
            return param1 / param2;
       }

    public static void Main(string[] args)
     {
        
public static void Main(string[] args)
{
  //Declaring the Delegate Variable
  ProcessDelegate processDelegate;

//Initializing Delegate Variable with reference to Multiply function
  processDelegate = new ProcessDelegate(Multiply);

  double result;
  result = processDelegate(6, 3);   // Calling the Delegate
  Console.WriteLine(result);

//Initializing the Delegate Variable with reference to Divide function            
  processDelegate = new ProcessDelegate(Divide);

  result = processDelegate(6, 3);   // Calling the Delegate
  Console.WriteLine(result);

  //Initializing the Delegate Variable with reference to Sum function
  Addition testClass = new Addition();
  processDelegate = new ProcessDelegate(testClass.Sum);

  result = processDelegate(6, 3);   // Calling the Delegate
  Console.WriteLine(result);

  Console.ReadKey();
 }

}

    public class Addition
    {
        public double Sum(int a, int b)
        {
            return a + b;
        }
    }

Note:- Signature of the delegate and function should match for a delegate to refer to a function

Custom Exceptions in C# – Best Practices

In .net, exceptions are objects of type Exception which are nothing but Run time errors  and Exception handling is the mechanism to handle these run time errors.If exceptions are not handled, by default, the program execution will  be terminated.Exception handling is done with the try-catch block.

                        

image 

Figure displays the Exception hierarchy in .NET. System.Exception is the base class of all exceptions.All predefined exceptions in .net are derived from System.SystemException.

Note: Initial idea was classes derived from System.SystemException would indicate exceptions thrown by CLR and classes derived from System.Applicationexception would indicate  exceptions thrown by the application.Unfortunately this policy was not reinforced and the rule was violated at various places.

For eg. System.Reflection.TargetInvocationException is an exception thrown by CLR but it is derived from System.ApplicationException.   System.SystemException class was also left open for programmers to derive from it and create custom exceptions which defeated the entire purpose of these classes.

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

        [Serializable]
        public class CustomExc : System.Exception
        {
            public CustomExc(string errorMessage)
                : base(errorMessage)
            {

            }


            public CustomExc(string errorMessage, 
                System.Exception innerExc)
                : base(errorMessage, innerExc)
            {

            }

            protected CustomExc(SerializationInfo si, 
                StreamingContext sc)
                : base(si, sc)
            {

            }

            public CustomExc()
                : base()
            {
            }
        }

   Points to be noted while creating custom exception

     1.Inherit from System.Exception rather than Application.Exception while creating the exception class.

     2.Provide all 4 overloads for the constructor

    • public Exception()
    • public Exception(string message)
    • protected Exception(SerializationInfo info, StreamingContext context)
    • public Exception(string message, Exception innerException)

     3.Custom exceptions needs to be marked with the Serializable attribute because the base class implements  the  ISerializable interface.

Creating XML file in C# made easy

Before we start just a brief introduction about XML files and how it differs from HTML.
XML is a format for storing and transporting data whereas HTML is used to display data.
I.e. XML is designed to be read by machines and HTML by human beings.
HTML has fixed set of tags. But XML enables users to define their own tags. Hence XML is also a standard for creating markup languages. This is done with the help of DTDs (Data Type Definition) or Schemas. DTDs define the structure of data in the XML file. All permissible tags and attribute are defined in the DTD file and the actual XML file has to be validated against the DTD.

We are creating a simple XML file with the basic nodes.

The file will have

1. XML Declaration
2. XML Comments
3. XML Document Type
4. Root Node
5. Child node with Attribute
6. Child node with Inner Childs

Note: System.XML namespace provides all the types for creating and manipulating XML.

CODE

XmlDocument xmlDoc;
XmlNode xmlNode;
XmlElement xmlRootElement;
XmlElement xmlChildElement;
XmlElement xmlInnerChildElement;
XmlText xmlText;
XmlDeclaration xmlDeclatation;
XmlDocumentType xmlDocumentType;

string outputFileName;

try
{

 xmlDoc = new XmlDocument();

 //Creating the XML Declaration
 xmlDeclatation = xmlDoc.CreateXmlDeclaration("1.0", "", "yes");
 xmlDoc.AppendChild(xmlDeclatation);

 //Adding Comment Line after Declration
 xmlNode = xmlDoc.CreateNode(XmlNodeType.Comment, "DDD", "DDD");
 xmlNode.Value = "Sample XML File";
 xmlDoc.AppendChild(xmlNode);

 //Adding Doctype
 xmlDocumentType = xmlDoc.CreateDocumentType("DocType", null, null, null);
 xmlDoc.AppendChild(xmlDocumentType);
 //Adding the Root Node IDEA_IMPORT_FIELDS
 xmlRootElement = xmlDoc.CreateElement("", "CONCEPTS", "");
 xmlDoc.AppendChild(xmlRootElement);

 //Adding Child with Attribute
 xmlChildElement = xmlDoc.CreateElement("", "Concept1", "");
 xmlText = xmlDoc.CreateTextNode("Introduction to XML");
 xmlChildElement.AppendChild(xmlText);
 xmlChildElement.SetAttribute("Subject", "XML");
 xmlRootElement.AppendChild(xmlChildElement);

 //Adding Child2
 xmlChildElement = xmlDoc.CreateElement("", "Concept2", "");
 xmlText = xmlDoc.CreateTextNode("");
 xmlChildElement.AppendChild(xmlText);
 xmlRootElement.AppendChild(xmlChildElement);

 //Adding Inner Child
 xmlInnerChildElement = xmlDoc.CreateElement("", "Concept3", "");
 xmlText = xmlDoc.CreateTextNode("This is an Inner Child");
 xmlInnerChildElement.AppendChild(xmlText);
 xmlChildElement.AppendChild(xmlInnerChildElement);

 //Saving the XML file
 outputFileName = @"C:\newxml.xml";
 xmlDoc.Save(outputFileName);
}
catch (System.Exception ex)
{
   //MessageBox.Show("Unable to create XML file");

}
finally
{
    xmlDoc = null;
    xmlNode = null;
    xmlRootElement = null;
    xmlChildElement = null;
    xmlChildElement = null;
    xmlText = null;
    xmlDeclatation = null;
}

OUTPUT

<?xml version="1.0" standalone="yes"?>

<!–Sample XML File –>

<!DOCTYPE DocType>

<CONCEPTS>

     <Concept1 Subject="XML">Introduction to XML</Concept1>

     <Concept2>

              <Concept3>This is an Inner Child</Concept3>

     </Concept2>

</CONCEPTS>

Protected Internal Members … Explained

Protected internal accessibility means protected OR internal, not protected AND internal.

“Protected Internal” acts as "Internal" with in the assembly and Protected" across the assembly. It is used in situations were function needs to be accessed by all the classes within the assembly and all derived classes in other assemblies.

1) Inherited classes, those reside in a different assembly

2) Classes those are not derived, but reside in the same assembly

Have access to Protected Internal Members

Follow the link to download a project that explains the Concept

http://www.4shared.com/file/253782212/f0f6ab9e/ProtectedInternal.html

As per the table below, it is clear that Protected Internal means Protected OR Internal

Scenario Protected Internal Protected Internal
Scenario 1 True True True
Scenario 2 False True True
Scenario 3 True False True
Scenario 4 False False False

Refer the Code and the Table Below

Scenario Comments
Scenario 1 Line42 NS1.cs All functions except Private functions of Base Class were accessible
Scenario 2 Line56 NS1.cs Protected , Private functions of Base Class were not accessible

Public, Internal and Protected Internal functions were accessible.

Scenario 3 Line11 NS2.cs Internal , Private functions of Base Class were not accessible.

Public, Protected and Protected Internal functions were accessible.

Scenario 4 Line25 NS2.cs Only Public Functions were accessible.

Follow

Get every new post delivered to your Inbox.