Passing Reference Type by Reference

Suppose this is our class Person, having an string property name FullName.

        class Person
        {
            public string FullName { get; set; }

        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            UnderstandingPassbyValandRef();
        }
     
        private void UnderstandingPassbyValandRef()
        {
            Person myPOriginal = new Person();
            myPOriginal.FullName = "Nishant Rana";

            PassByValue(myPOriginal);
            MessageBox.Show(myPOriginal.FullName);
            // Output : “Nishant Rana PassByVal”
            
            PassByRef(ref myPOriginal);
            MessageBox.Show(myPOriginal.FullName);
            // Output : “Srihari Radhakrishnan”

            this.Close();
        }
       

 
 
  • Here copy of the reference, which points to myPOriginal is passed to the method.So it is possible for the method to change the contents of Person.
  • However by using the new operator inside the method makes the variable pVal reference a new Person object. Thus any changes after that will not affect the orignal person myPOriginal object.
         
  •   private void PassByValue(Person pVal)
            {
                pVal.FullName = "Nishant Rana PassByVal";
                pVal = new Person();
                pVal.FullName = "Arvind Singh";
            }
 
 
 
  • Here actual reference is passed to the method.
  • All of the changes that take place inside the method affect the original person object.    
         
  •   private void PassByRef(ref Person pRef)
            {
                pRef.FullName = "Nishant Rana PassByRef";
                pRef = new Person();
                pRef.FullName = "Srihari Radhakrishnan";
            }

 

Bye..

New features in C# language

Auto-Implemented Properties

Suppose this is our Person class with two properties First Name and Last Name.

public class Person
    {
        private string firstName;
        private string lastName;
        public string FirstName
        {
            get
            {
                return firstName;
            }
            set
            {
                firstName= value;
            }
        }  
        public string LastName
        {
            get
            {
                return lastName ;
            }
            set
            {
                lastName = value;
            }

        }
    }

 

Here we are not putting any extra logic while using get and set blocks for the properties, so the above code could be written as following using Auto-Implemented Properties.

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

    }

 

Things to remember :-

Both get and set accessor are required.

To make it read only we can declare set accessor as private

 public string LastName { get; private set; }
 
 

Object Initializers 

To initialize our Person object normally we would be writing the following code

  Person person = new Person();
  person.FirstName = “Nishant”;
  person.LastName = “Rana”;

 

However now we could do this in much simpler manner

Person person = new Person() { FirstName = “Nishant”, LastName = “Rana” };

 

Using Object initializers we can assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.

 

 

 

Extension Methods

Using Extension methods we can add methods to existing types without creating a new derived type, recompiling or modifying the original type.

Suppose this is how we have defined our Person class with one method named GetFirstName.

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

        public string GetFirstName()
        {
            return FirstName;
        }
    }

 

Now we will add method to this existing Person Type named GetLastName

 public static class PersonExtension
    {
        public static string GetLastName(this Person p)
        {
            return p.LastName;
        }
    }

Here we need to follow these rules

  • We need to declare our class as static.
  • We need to define the method as static and the first parameter is preceded by this keyword and specifies which type the method operates on.

Now the code that calls both these methods. GetLastName function would be called as if it was an instance method and not an static one.

   Person person = new Person() { FirstName = “Nishant”, LastName = “Rana” };
   string firstName = person.GetFirstName();
   string lastName = person.GetLastName();
           
 
 

Collection Initializers

Here instead of writing the following code to intialize the collection

   List<Person> lstPerson = new List<Person>();
   Person person1 = new Person() { FirstName = “Nishant”, LastName = “Rana” };
   Person person2 = new Person() { FirstName = “Ashutosh”, LastName = “Pandey” };
            lstPerson.Add(person1);
            lstPerson.Add(person2);
we could use the following syntax, without making use of add method
 
List<Person> lstPerson=new List<Person>()
            { 
                {new Person { FirstName=“Nishant”, LastName=“Rana”}},
                {new Person {FirstName =“Ashutosh”, LastName=“Pandey”}}                
            };

 

 

Implicitly type local variables

Now we can declare variables using var keyword (implicitly) without explicitly defining their type.

 string FullName = “Nishant Rana”;
or
var FullName = “Nishant Rana”;
 
 
var myStringArray = new[] { “a”, “b”, “c” };
 
The above two lines of code are equivalent.
Here compiler infer the type of variable from the expression on the right side. It could be built-in type, user-defined type, anonymous type or any other type defined in .NET framework.
 
 

Anonymous Types

Anonymous types are class types that contain one or more public read only properties.

var v = new { FirstName = “Nishant”, LastName = “Rana” };

The above line of code creates a anonymous class having two public read only properties named FirstName and LastName.

Things to remember :-

  • The compiler gives name to the anonymous types but our application won’t be able to access it.
  • It cannot be cast to any type except “Object’”.

Anonymous methods and Lambda expressions

Suppose this is our simple delegate

 public delegate void MySimpleDelegate();

 

And this is the function which it points to

  public void MySimpleFunction()
        {
            Response.Write(“Simple function”);
        }

 

And this is how we would be using the delegate

  MySimpleDelegate mySimpleDelegate = MySimpleFunction;
   mySimpleDelegate();

 

Now here instead of defining the MySimpleFunction separately we can make use of anonymous methods

  MySimpleDelegate mySimpleDelegate = delegate
            {
                Response.Write(“Simple function”);
            };
mySimpleDelegate();

 

Infact we can also use lambda expression over here

MySimpleDelegate mySimpleDelegate = () => Response.Write(“Simple function”); 
mySimpleDelegate();
 
 
Here       ()           –>  no input parameter
and        =>          –> lamda operator
 
 
 
Optional parameters
 

We can declare an optional parameter by specifying default value as a part of declaration

public void GetTotal(int a = 0, int b = 0)
        {
            MessageBox.Show((a + b).ToString());
        }

We can call the above method in any of the following way

 
            GetTotal(1, 1);
            GetTotal(1);
            GetTotal();

 

Named Arguements

Name the arguments to be passed
            GetTotal(a: 1, b: 2);
            GetTotal(b:2, a: 1);
This will throw error named argument must appear after fixed arugments have been specified
 
           GetTotal(a:1, 2);

Dynamic Type

New dynamic type that allows us to do things that are resolved during run time.

         dynamic dString = GetName(“a”,”b”);
         dynamic dInt = 12;

 

Bye.

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..

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

Understading Delegates

What are delegates?
Delegates are object that refer to an method. Normally we refer to objects, however referring to an object isn’t any different from referring a method they too have physical location in memory.

Why use delegate?
One delegate can be used to call different methods during runtime of a program by simply changing the method to which the delegate refers.
and Delegates Support Events.

delegate ret-type name(paramerter-list);
e.g. delegate string MyDelegate();

The MyDelegate can call any method whose return type is string and accepts no parameter. It can be instance method or a static method.

delegate string MyDelegate(String s);
class Program
{
static string GetNameLower(String s)
{
return s.ToLower() ;
}
static string GetNameUpper(string s)
{
return s.ToUpper();
}
static void Main(string[] args)
{
MyDelegate myD = new MyDelegate(GetNameLower); //or myD=GetNameLower
string s1 = myD(“Hi Nishant”);
Console.WriteLine(s1);
myD = new MyDelegate(GetNameUpper); //or myD=GetNameUpper
string s2 = myD(“Hi Nishant”);
Console.WriteLine(s2);
}
}

Understanding Multicasting

We can have chain of methods that will be called automatically when a delegate is invoked.
For this we will use += operator to add methods to chain and -= to remvove a method.
If delegate returns value than value returned by the last method becomes the return value of entire deleagation invocation. Thus a delegate making use of multicasting will have void as return type.

delegate void MyDelegate();
class Program
{
static void GetNameLower()
{
Console.WriteLine(“GetNameLower Called”);
}
static void GetNameUpper()
{
Console.WriteLine(“GetNameUpper Called”);
}
static void Main(string[] args)
{
MyDelegate myD = GetNameLower;
myD +=GetNameUpper;
myD(); //invoking the delegate
}

Understanding Static keyword in C#

Static keyword can be applied to
Class, field, method, properties, operator, event and constructors.
Static member belongs to the class and not to any object of the class.
They can be used without creating the instance of the class.

For e.g. Static Void Main()
It is called by the operating system on program execution
To access the static member we’ll use

ClassName.staticmember

When a variable is declared as static internally what happens is that all the instances of the class share the same static variable. A static variable is initialized when its class is loaded. If not
initialized explicitly then
it is initialized to zero for numeric variable
null in case of object references
false for boolean

StaticMethod they can only contain static member and call other static method.
If we need to access them than it can be done through the object of that class

class Game
{
string getGameName()
{
……………….
}
public static void getNameThroughStatic(Game g)
{
g.getGameName(); // accessing static method
}
}

When to use them?
Well we can use them when we need to maintain information applicable to the entire class

suppose we have a class Employees there we can have a static count variable to keep track of no of employees.

class Employees
{
static in count=0;
public Employees()
{
count++;
}

~Employees
{
count–;
}

}

What are Static Constructor?
They can be used to initialize the static variables.
They are called automatically and before the instance constructor (if called any).

for above class
static Employees() // no other access modifiers for them
{}

What are static Classes?
A class whose objects can’t be created and which can only have static members. They can’t be inherited as well.
They can have static constructor

Why use static Classes?
It can be used to group related static method.