Sunday, April 20, 2014

C# ref parameter

One of the most vague point in C.#NET is passing argument by reference, or shortly by ref.
Though it is very simple idea in passing arguments to function:


  • If argument is passed by reference then it represents link to the source data (Pointer in C).
    This is true for structures and classes.
  • Otherwise for a class copy of link is passed. And for a struct copy of whole struct is passed (except class property objects).

Take an example without ref:

 class Cat
 {
     public string Name {get;set;}
 }

 class Program
    {
        static void Main(string[] args)
        {
            var catOscar = new Cat { Name = "Oscar" };
            ChangeCatToSimba(catOscar);

            Console.WriteLine("Cat name: " + catOscar.Name);
            Console.ReadKey();
        }

        // By default copy of reference is passed (without ref keyword)
        // Same as copy of Pointer can be passed in C language
         private static void ChangeCatToSimba(Cat cat)
        {
            // reassign source will do nothing with Oscar
            cat = new Cat { Name = "Simba" };
        }
    }

And here is example with ref:
class Program
    {
        static void Main(string[] args)
        {
            var catOscar = new Cat { Name = "Oscar" };
            ChangeCatToSimba(ref catOscar);

            Console.WriteLine("Cat name: " + catOscar.Name);
            Console.ReadKey();
        }

        // Ref takes memory address reference to cat object
        private static void ChangeCatToSimba(ref Cat cat)
        {
            // reassign source
            cat = new Cat { Name = "Simba" };
        }
    }


In the first example (without ref) result is "Oscar". In the second example reassigning occurs and result is "Simba".

Sunday, April 13, 2014

HTML 5 Data-* Attribute

Data-* attribute is special novelty in HTML 5 that can be used for own purposes.

For example, we can use our own data-author, data-title, data-text, data-car-model attributes (anything starting with data-) and it will be valid HTML. Custom data attribute can be used on any element:

<span data-author>Miguel de Cervantes Saavedra</span>
<span data-title>Don Quixote</span>


One of the big architecture flaw appears: there is no namespace!
And I predict there will be lots of conflicts, especially when one famous javascript framework will use same data- designation as another framework, or it will conflict with you own clear attribute names.
Microsoft already uses data-* attributes in ASP.NET MVC for validation.