Understanding Constructors (C#)


What is constructor?

Constructor is a special type of function member of a class. It is used to initialize the instance variables of the object.

Person myPerson=new Person();

Here the new operator is used to allocate the memory needed to store the data of the object.

Now suppose this is how we have defined our Person class.

  public class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }  
   

( here we have used Automatic Properties feature of C# 3.0 to declare our properties FirstName and LastName)

Here in our class we haven’t defined a constructor but we are still able to create instance variables of the Person Object using following line of code

Person p = new Person();
 

The reason it is possible is because we don’t have to explicitly declare constructor for a class, C# automatically provides a default parameterless constructor for that class. The default constructor will initialize any fields of the class to their zero-equivalent values.

We can also write our own constructors, the things to remember are

  • They don’t have a return type.
  • Their name should be same as the name of the class.
  • Should contain a parameter list, which could be left empty.

Now the question is why would we be writing our own constructors?

Well the reason is because constructors can be used to pass initial values for an object’s fields at the time when an object is being instantiated.

For our above Person class

instead of the following code 

    Person p = new Person();
    p.FirstName = "Nishant";
    p.LastName = "Rana";

 

we can do the same in single line of code

Person p = new Person("Nishant", "Rana");
 

The constructor would be defined in the following manner

 public Person(string fname, string lname)
          {
              FirstName = fname;
              LastName = lname;
          }

One thing we have to remember is that if we are defining our own Parameterized constructor the default constructor would be eliminated.

We won’t be able to create person class object using default constructor.

i.e. Person p=new Person(); // it won’t compile.

In this case then we need to explicitly write a default constructor.

public Person()
        { 

        }

bye..

Delegate, Anonymous Methods and Lambda Expressions in C#


Delegate acts as a function pointer.

We define the function to which the delegate can point to in this manner

// Delegate which will point to a method which has no parameter and returns nothing

public delegate void MySimpleDelegate();

// Delegate which will point to a method which takes string as parameter and returns string as well

public delegate string MyComplexDelegate(string message);

 

Now comes our two function to which delegates would be pointing 

public void SimpleDelegate(){

MessageBox.Show(“My Simple Delegate”);

}  

public string ComplexDelegate(string name){

MessageBox.Show(name);

return “Hi “ + name;

} 

// We have created an instance of our MySimpleDelegate

// which would be referencing SimpleDelegate function

MySimpleDelegate myD = SimpleDelegate;

// when we call the delegate it calls the method which it is pointing to

myD();

// Same thing with our MyComplexDelegate

MyComplexDelegate myAD = AnotherDelegate;

myAD(“Hello”);

 

// If we know that our function SimpleDelegate() and ComplexDelegate(string name)

// wouldn’t be called by any other code other than the delegate itself we can

// make use of anonymous method i.e. method with no name

// Here again we have done the same thing but used anonymous method

// because we aren’t going to use it anywhere else

MySimpleDelegate myD = delegate

{

MessageBox.Show(“Simple Delegate”);

};

myD();

MyComplexDelegate myAD = delegate(String name)

{

MessageBox.Show(name);

return “Hi “ + name;

};

myAD(“Hello”);

// Now let’s shorten our code further using lambda expression

// () -> no input parameter

// => -> lambda operator

// MessageBox.Show(“Simple delegate”) -> statement block

MySimpleDelegate myD = () => MessageBox.Show(“Simple delegate”);

myD();

//(String name) -> explicitly typed parameter

MyComplexDelegate myAD = (String name) => { MessageBox.Show(name); return name; };

myAD(“Hello”);

 

Bye.

 

Nice website for C# developer


Hi,
Do check out this very very useful web-site for c# developer for understanding
multi threading and it has got some wonderful tools like

QueryExpression – which has an user interface similar to query analyzer using which we can query oracle, sql server and other databases. It is also very light weight.

And
LinqPad for practicing the Linq syntax.

http://www.albahari.com/index.html

Creating custom application exception C#


Hi,

There are times when we are creating a custom class and the class needs to have it’s own application specific exception which can be thrown so that calling program can be aware of the error condition.

Say we have a class named BillingUpdate which has a condition that the billing amount should never be less than 10,000.

Say it has a function which accepts billing amount in one of it’s methods as a parameter and we need to make the user of this function aware of the condition that it can’t take billing amount less than 10000.

In this case what we can do is

create a custom class BillingException which inherits SystemException class

// creating a custom class that inherits from SystemException.
class BillingException :SystemException
{
// overloading the constructor for passing the message associated with the exception
public BillingException(string message)
: base(message)
{
}
}

Now to use this exception class we can do the following

public void GetBillingAmount(decimal billingAmount)
{
if(billingAmount < 10000M)
{
throw new BillingException(“Billing amount can’t be less than 10000”);
}
}

And the calling code can do something like this

BillingUpdate billingUpdate = new BillingUpdate();
try
{
billingUpdate.GetBillingAmount(9000M);
}
catch(
BillingException ex)
{
MessageBox.Show(ex.Message);
}

Bye

Events in C#


We’ll take a simple and useful scenario to make our understanding of Events as clear as possible.
First of all copy and paste the code below. We’ll try understanding the code than.

using System;
public class ResultDeclarationEventArgs : EventArgs
{
private string message;
public ResultDeclarationEventArgs(string message)
{
this.message = message;
}
public string Messsage
{
get
{
return message;
}
}
}
public delegate void ResultHandler(object sender, ResultDeclarationEventArgs e);
public class Kid
{
private int percentage;
public event ResultHandler onResultDeclaration;
public int Percentage
{
set
{
percentage = value;
if(percentage > 80)
{
ResultDeclarationEventArgs myREA = new ResultDeclarationEventArgs( ” I got Distinction”);
onResultDeclaration(this, myREA);
}
if(percentage > 60 && percentage < 80)
{
ResultDeclarationEventArgs myREA = new ResultDeclarationEventArgs(” I got FirstClass”);
onResultDeclaration(this, myREA);
}
if(percentage > 40 && percentage < 60)
{
ResultDeclarationEventArgs myREA = new ResultDeclarationEventArgs(” I got SecondClass”);
onResultDeclaration(this, myREA);
}
if(percentage < 40)
{
ResultDeclarationEventArgs myREA = new ResultDeclarationEventArgs(” Sorry I failed “);
onResultDeclaration(this, myREA);
}
}
}
}
public class Mom
{
public Mom(Kid myKid)
{
myKid.onResultDeclaration += new ResultHandler(GiveMsgToMom);
}
void GiveMsgToMom(object sender, ResultDeclarationEventArgs e)
{
Console.WriteLine(e.Messsage);
}
}

public class Dad
{
public Dad(Kid myKid)
{
myKid.onResultDeclaration += new ResultHandler(GiveMsgToDad);
}
void GiveMsgToDad(object sender, ResultDeclarationEventArgs e)
{
Console.WriteLine(e.Messsage);
}
}

class myDemo
{
public static void Main()
{
Kid kid = new Kid();
Mom mom = new Mom(kid);
Dad dad = new Dad(kid);
Console.WriteLine(“Please enter the percentage of the Kid”);
string percentage = Console.ReadLine();
kid.Percentage = Convert.ToInt32(percentage);
}
}

The scenario is something like this First there is a class named Kid. It has a field called Percentage and declares an event OnResultDeclaration. It is of type ResultHandler. ResultHandler is a delegate. public delegate void ResultHandler(object sender, ResultDeclarationEventArgs e);
It can point or refer to any method which has return type void and takes as parameter an object and ResultDeclarationEventArgs.
Object will give the name of the sender who has called this eventhandler and ResultDeclarationEventArgs is to pass any information regarding the event.

ResultDeclarationEventArgs is a class that derives from EventArgs class. It has a message field which will contain the message the Kid class, which has the event OnResultDeclaration, would like to convey to the class (e.g. Mom, Dad) which are interested in that event.
For this reason, we have our event handlers(method) inside Mom and Dad class which have the same signature as defined by the event.
void GiveMsgToMom(object sender, ResultDeclarationEventArgs e)
void GiveMsgToDad(object sender, ResultDeclarationEventArgs e)
Than we register these eventHandler to the events.
myKid.onResultDeclaration += new ResultHandler(GiveMsgToDad);
myKid.onResultDeclaration += new ResultHandler(GiveMsgToDad);

Kid class will check for the percentage passed in and accordingly set’s the message.
Whatever message is set is than displayed in the Event handler inside Mom and Dad class using e.Message

%d bloggers like this: