Parameter passing in C#

1. Value Types

Notice that the values live inside the box which will not be the case for reference types. Also, the assignment operation copies the value inside of the box, this is important to compare with reference types.

Quiz: What is the result of the WriteLine statement? 

Answer: 5 

2. Reference Types

Variables that hold reference types actually hold a reference to a location in memory (on the heap). So assignment operations copy the address. Notice this is still consistent with diagram #1, the copy operation copies the value inside of the box.

Quiz: What is the result of the WriteLine statement?

Answer: hello world

3. Immutable Reference Types

Immutable reference types like strings behave just like regular reference types except they don’t provide a way to change their value.

Quiz: What is the result of the WriteLine statement?

Answer: hello

4. Value Types Passed by Value

Passing a variable to a function by value is equivilant to instantiating a new variable and assigning it to the first (well, ignoring scope issues and such). Notice that the diagram below is nearly identical to diagram #1.

Quiz: What is the result of the WriteLine statement?

Answer: 5, same as #1

5. Reference Types Passed by Value

In #4 I said passing a variable to a function by value is equivilant to instantiating a new variable and assigning it to the first. Is that still true of reference types? Yup. And did you notice there’s an implicit assignment statement when passing by value? As you’ll see shortly there won’t be when passing by reference.

Quiz: What is the result of the WriteLine statement?

Answer: hello world

 6. Value Types Passed by Reference

Passing by reference doesn’t involve an implicity copy, instead it instantiates the inner variable to the address in memory of the outer variable. Then all references to the inner variable are implicitly dereferenced for you and voila, magically you’re changing the value of the outer variable.

Quiz: What is the result of the WriteLine statement?

Answer: 10, and notice how different the diagram and results are than #1 and #4.

7. Reference Types Passed by Reference

Really this is no different than value types passed by reference (#6), except calling sb.Append() from an inner variable is dereferenced once to get to the outer variable and again because the outer variable is itself a pointer.

By the way, when you get to the section in Jon’s article called:

“Sidenote: what is the difference between passing a value object by reference and a reference object by value?”

Please read it carefully, it’s an extremely good point. It can be sumed up by comparing the final assignment statement above (Reference Types Passed by Reference) to the final assignment statement in in diagram #5 (Reference Types Passed by Value). It’s a subtle, but important difference.

Oh and the quiz, what is the value of the Console.WriteLine in #7?

Answer: NullReferenceExceptinon – Object reference not set to an instance of an object



What are the best movies about Geeks/Programmers/Hackers. (for inspiration)

what is new in csharp 3.0

Here is a point wise summary of features introduced newly in C# 3.0

Implicitly Typed Local Variables

  • Local variables can be declared as type ‘var’ which means compiler to determine the actual type based on the data by which its is initialized.
  • var i = 10; // i is created of type int
  • var name = “MyName” ; // name is created of type string
  • can only be used when declared and initialized in same statement.
  • Cannot be initialized to null.
  • Cannot be used as class members.
  • Mostly used to store anonymous types as in LINQ based programming.

Object & Collection Initializers

  • Allow assigning values to any accessible members or properties of a type at the time of initiation without invoking the constructor with parameters.
  • The default constructor gets executed before assigning the values.
  • E.g. Coordinate c1 = new Coordinate {x=1 , y=2};
  • Used in LINQ query expressions along with anonymous types.
  • Collection Initializers use Object Initializers to specify multiple elements of collection without calling Add method multiple times.

Extension Methods

  • Allows adding new methods to existing types without modifying the existing type.
  • Are special kind of static methods but are called as if they are instance methods.
  • The first parameter passed to Extension methods specifies to which type they operate on preceded by ‘this’ keyword.
  • They cannot access the private variables of type which they are extending.
  • Extension Methods need to defined in a non-nested and non-generic static class.
  • Instance methods take priority over extension methods in case they have same signature.

Anonymous Types

  • Are of class types which can have only public read-only properties as their members. No other class members like methods are allowed.
  • They are of reference types and are derived from ‘Object’ class.
  • Internally compiler gives them the name but its not accessible by application code.
  • They have a method scope.
  • Can be initiated directly e.g. new { property1=1, property2=”Hello World”};

Lambda Expressions

  • Very similar to anonymous methods introduced in C# 2.0.
  • Its an inline expression or statement block which can be used to pass arguments to method call or assign value to delegate.
  • All lambda expression use lambda operator => where the left side denotes result and right contains statement block or expression.

Auto-Implemented Properties

  • Helps in simplifying property declaration in cases where there is no custom logic required in accessors methods.
  • E.g. public int Price {get; set;};
  • Internally compiler creates an anonymous field for assigning val

When should I use == and when should I use Equals?

Explanation 1:
The Equals method is just a virtual one defined in System.Object, and overridden by whichever classes choose to do so. The == operator is an operator which can be overloaded by classes, but which usually has identity behaviour.

For reference types where == has not been overloaded, it compares whether two references refer to the same object – which is exactly what the implementation of Equals does in System.Object.

Value types do not provide an overload for == by default. However, most of the value types provided by the framework provide their own overload. The default implementation of Equals for a value type is provided by ValueType, and uses reflection to make the comparison, which makes it significantly slower than a type-specific implementation normally would be. This implementation also calls Equals on pairs of references within the two values being compared.

However, the main difference between the two types of comparison in normal use (where you’re unlikely to be defining your own value types very often) is polymorphism. Operators are overloaded, not overridden, which means that unless the compiler knows to call the more specific version, it’ll just call the identity version. To illustrate that, here’s an example:

using System;

public class Test
	static void Main()
        // Create two equal but distinct strings
        string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
        string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
        Console.WriteLine (a==b);
        Console.WriteLine (a.Equals(b));
        // Now let's see what happens with the same tests but
        // with variables of type object
        object c = a;
        object d = b;
        Console.WriteLine (c==d);
        Console.WriteLine (c.Equals(d));

The results are:


The third line is False because the compiler can only call the non-overloaded version of == as it doesn’t know that the contents of c and d are both string references. As they are references to different strings, the identity operator returns false.

So, when should you use which operator? My rule of thumb is that for almost all reference types, use Equals when you want to test equality rather than reference identity. The exception is for strings – comparing strings with == does make things an awful lot simpler and more readable butyou need to remember that both sides of the operator must be expressions of type string in order to get the comparison to work properly.

For value types, I’d normally use == for easier-to-read code. Things would get tricky if a value type provided an overload for == which acted differently to Equals, but I’d consider such a type very badly designed to start with.

Explanation 2:

For Value Type: == and .Equals() method usually compare two objects by value.

For Example:

int x = 10;

int y = 10;

Console.WriteLine( x == y);


Will display:




For Reference Type: == performs an identity comparison, i.e. it will only return true if both references point to the same object. While Equals() method is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent.

For Example:

StringBuilder s1 = new StringBuilder(“Yes”);

StringBuilder s2 = new StringBuilder(“Yes”);

Console.WriteLine(s1 == s2);


Will display:



In above example, s1 and s2 are different objects hence “==” returns false, but they are equivalent hence “Equals()” method returns true. Remember there is an exception of this rule, i.e. when you use “==” operator with string class it compares value rather than identity.

 When to use “==” operator and when to use “.Equals()” method?

For value comparison, with Value Tyep use “==” operator and use “Equals()” method while performing value comparison with Reference Type

Few Software Principles


The Law of Demeter for functions requires that a method M of an object O may only invoke the methods of the following kinds of object

O itself,  M’s parameters, any objects created/instantiated, within M O’s direct component objects

       In particular, an object should avoid invoking methods of a member object returned by another method. For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as “use only one dot”. That is, the code “a.b.Method()” breaks the law where “a.Method()” does not. There is disagreement as to the sufficiency of this approach


         The open/closed principle states “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification, that is, such an entity can allow its behaviour to be modified without altering its source code

>>> Fragile base Class Problem :

        It is a fundamental architectural problem of object-oriented programming systems where base classes (superclasses) are considered “fragile” because seemingly safe modifications to a base class, when inherited by the derived classes, may cause the derived classes to malfunction. The programmer cannot determine whether a base class change is safe simply by examining in isolation the methods of the base class.

Debugging Resource


<> Debugging
<> Exception Handling Articles
<> .Net Localization/Internationlization. Refer the [Blogs (i18n)] as well – 
<> All about File Formats/File Extensions/Unicode Character Set and related resouces/Tools –