Friday, February 22, 2013

Struct is mutable?? Think again !!


Struct is value type defined in .Net and is actually mutable (means if I change member variable of struct it really get changed and do not
create new copy). Same thing is not true about String.
for ex, String str = "Hello";
str = str + "John";
The above operation would create new copy of string str and store in it "Hello John". Hence strings are immutable.

In case of struct,
struct rectangle
{
private int length;
public int Length
{
get
{
return length;
}
set
{
length = value;
}
}
private int width;
public int Width
{
get
{
return width;
}
set
{
width = value;
}
}

public void display()
{
Console.WriteLine("Length= {0} Width = {1}",length,width);
}
        }

public static void Main()
        {

            rectangle r = new rectangle();
            r.Length = 10;
            r.Width = 20;
            r.display();
            //Length= 10 Width = 20

            r.Length = 400;
            r.display();
            //Length= 400 Width = 20
         
           //Here actual struct variable (r) is modified and displayed.


            List Room = new List();
            Room.Add(new rectangle { Length = 5, Width = 10 });

           
            foreach (rectangle item in Room)
            {
                item.display();
            }

            //Length= 5 Width = 10

            //Room[0].Length = 20;   //error
            Room[0] = new rectangle { Length = 20, Width = Room[0].Width };

            foreach (rectangle item in Room)
            {
                item.display();
            }
            //Length= 20 Width = 10

            rectangle[] walls = new rectangle[2];

            walls[0] = new rectangle { Length = 10, Width = 30 };

            walls[0].display();

            //Length= 10 Width = 30
           
            walls[0].Length = 40;

            walls[0].display();
            //Length= 40 Width = 30
         
        }

So, if a struct is part of collection class (List), it is not possible to directly change
properties of struct variable, we have to use workaround as shown below

//Room[0].Length = 20;   //error
               Room[0] = new rectangle { Length = 20, Width = Room[0].Width }; // work around

In case of struct part of Array[], we can modify properties of struct as normal variable.

So this is the case where actual struct variable can not modified.

Monday, February 18, 2013


Try hands on LINQ http://www.wiziq.com/online-tests/41952-linq-test-1

Basic c# quiz http://www.wiziq.com/online-tests/43860-c-basic-quiz

Thursday, October 14, 2010

Sunday, August 1, 2010

Sunday, July 4, 2010

Test your C sharp skills - 1

http://www.wiziq.com/online-tests/14096-csharp-your-skills-1

Extension methods in c#

Extension methods in c#

This feature has been added to c# 3.0. Have a look at it.


An extension method is a new language feature of C# starting with the 3.0 specification. Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

Using extension methods, you can declare methods that appear to augment the public interface, or contract, of a type. At first glance, they may appear to provide a way to extend classes that are not meant to be extended. However, it’s very important to note that extension methods cannot break encapsulation. That’s because they’re not really instance methods at all and thus cannot crack the shell of encapsulation on the type they are extending.

An Extension Method is defined by several rules:

· The method is defined in a non-generic static class that is not nested.

· The method itself is static.

· The first parameter of an Extension Method is preceded by the modifier this. This parameter is called an “instance parameter” and can only appear as the first parameter of the method.

· No other parameter modifiers (ref, out, etc…) are allowed with the modifier this. As a result, a value type can’t be passed by reference to an Extension Method.

· The instance parameter cannot be a pointer type.

· The method must be public, internal or private: it's a stylistic choice to declare them public, but not a requirement!

· Extension Methods are in a namespace which is in scope.

· If your method successfully matches all these points, you can safely say that it’s an Extension Method!

Here is an example of creating Extension method that adds ConvertToUpper() method to already existing Framework class String.

namespace ExtensionMethods

{

public static class Tools

{

public static string ConvertToUpper(this string str)

{

return str.ToUpper();

}

}

}

Here is the use of extension method in actual program.

namespace ExtensionMethods

{

class Program

{

static void Main(string[] args)

{

String s = "My document";

Console.WriteLine(s.ConvertToUpper());

}

}

}

Notice that the static class containing extension method (here, class Tools) and the class using the extension method (here class Program) both are in same namespace.

· If your Extension Method is in another namespace (or another DLL), you will need a using statement to import the content of this namespace and make the call of your method possible

using ExtensionMethods;

namespace anothernamespace

{

class newprogram

{

static void Main()

{

String s = "New document";

Console.WriteLine(Tools.ConvertToUpper(s));

}

}

}

· If you're extending a 3rd party class and in a later version they introduce a new method with the same signature, you won't easily know that the meaning of your calling code has changed. If the new method is very similar to your extension, but with subtly different boundary conditions (or whatever) then this could lead to some very tricky bugs. It's relatively unlikely to happen though.

There is little restriction on Extension methods:

1. Extension methods cannot be used to override existing methods.

2. An extension method with the same name and signature as an instance method will not be called.

3. The concept of extension methods cannot be applied to fields, properties or events.

So caution: Use extension methods sparingly....overuse can be a bad thing.