Translate

Saturday, March 16, 2013

Public, Private and Static constructors

Here are some gotchas which we need to watch out while using public and private constructor. 
Found a really good and simple article on Code Project: 
http://www.codeproject.com/Articles/7011/An-Intro-to-Constructors-in-C

Short notes from the article

Public Constructor

Note: If we do not provide initializer referring to the base class constructor then it executes the no parameter constructor of the base class.
Note one thing here: we are not making any explicit call to the constructor of base class neither by initializer nor by thebase keyword, but it is still executing. This is the normal behavior of the constructor.

Private Constructor 

Private constructors, the constructors with the "private" access modifier, are a bit special case. It is because we can neither create the object of the class, nor can we inherit the class with only private constructors. But yes, we can have the set of public constructors along with the private constructors in the class and the public constructors can access the private constructors from within the class through constructor chaining.
It is possible to have the class with only the private constructors. But yes as I said, such class can neither be instantiated nor be inherited. If we try to inherit the class with only private constructors then we will get the same error as above. Also recall, once you provide constructor from your side the compiler will not add the no-parameter public constructor to your class.
Well, one of the usage scenarios of such class could be – when you have only static members in the class and you don't need to instantiate it.

What is the need of private constructor, a great answer can be found at :  
http://stackoverflow.com/questions/920045/what-is-the-need-of-private-constructor-in-c


For example if you have a class that should only be created through factory methods. Or if you have overloads of the constructor, and some of them should only be used by the other constructors. Probably other reasons as well =)

Static Constructor 

Notes for Static Constructors:

  1. There can be only one static constructor in the class.
  2. The static constructor should be without parameters.
  3. It can only access the static members of the class.
  4. There should be no access modifier in static constructor definition.
What is the use of static constructor ? 
An amazing answer could be found at: 

A static constructor is useful for initializing any static fields associated with a type (or any other per-type operations) - useful in particular for reading required configuration data into readonly fields, etc.
It is run automatically by the runtime the first time it is needed (the exact rules there are complicated (see "beforefieldinit"), and changed subtly between CLR2 and CLR4). Unless you abuse reflection, it is guaranteed to run at most once (even if two threads arrive at the same time).

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
Static constructors have the following properties:
  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created
    or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write
    entries to this file.
  • Static constructors are also useful when creating wrapper classes for
    unmanaged code, when the constructor
    can call the LoadLibrary method.

Friday, March 15, 2013

Why Static Class and Guidelines to use one

Question is how to prevent classes from getting instantiated and getting derived from.
  1. Have a class with private constructor 
  2. Make sure that the class is marked as sealed. 
  3. Even though we do both the class can still have instance members as a part of it, which can be used as a type to declare a variable of sealed class type, which would be useless of course. 
So in C# 2.0 the concept of static class was introduced, to prevent a class from getting instantiated one can just mark the class as static, some of the restrictions for the static classes are listed below:
You cannot have a instance property or method in a static class. The code mentioned below may not compile:
public static class MobileDevice
    {
        //This should be static too
        int broadcastBand;

        //This should be static too       
        [DllImport("user32.dll")]
        extern int DeviceIOControl(string guid);
       
        public static int BroadCastBand
        {
            get
            {
                return broadcastBand;
            }
        }

        public static int DeviceID
        {
            get
            {
                return DeviceIOControl("49ECA277-65F7-446b-9206-4C09580DDD88");
            }
        }
    }

The correct version of the class will be :
public static class MobileDevice
    {
        static int broadcastBand;
       
        [DllImport("user32.dll")]
        static extern int DeviceIOControl(string guid);
       
        public static int BroadCastBand
        {
            get
            {
                return broadcastBand;
            }
        }

        public static int DeviceID
        {
            get
            {
                return DeviceIOControl("49ECA277-65F7-446b-9206-4C09580DDD88");
            }
        }
    }
If we try to use the class by considering a static class as a type then compiler would complain: 'Cannot declare a variable of static type'
class Program
    {
        static void Main(string[] args)
        {
            MobileDevice buart = null; //'Cannot declare a variable of static type
            Console.WriteLine(MobileDevice.DeviceID);  //works
        }
    }
Also static class cannot be marked as Sealed or Abstract.

Static Class Guidelines 

http://msdn.microsoft.com/en-us/library/79b3xss3%28v=vs.80%29.aspx


Difference between Singleton and Static Class:


Singleton Pattern


Singleton Pattern: 

By having multiple reference on the web, I thought that There's no one better than Jon Skeet who could explain to me. Here's the link to the amazing article:  http://csharpindepth.com/Articles/General/Singleton.aspx

Below are some of the notes which I am scribbling from the above article to make my understanding intact: 

Standards in Service Interoperability and WSDL

Friday, November 16, 2012

Difference between ReadOnly and Constants

Was confused about the difference between ReadOnly and Constants in C#. Found this useful post in StackOverflow: 

what-is-the-difference-between-const-and-readonly

Thanks
Dibyendu

Thursday, May 31, 2012

Wednesday, November 16, 2011

Monday, March 28, 2011

Stop Using Mocks

Read the Article to get good know how of what to write in a test and also a robust test case.

Stop Using Mocks

Thanks
Dibyendu

Tuesday, January 11, 2011

Some CSS Gotchas

Was going through CSS tutorials on w3schools, jotted down few points. Hope it helps as a reference:


Do not leave spaces between the property value and the units! "margin-left:20 px" (instead of "margin-left:20px") will work in IE, but not in Firefox or Opera.

Do NOT start an ID name with a number! It will not work in Mozilla/Firefox.

Do NOT start a class name with a number! This is only supported in Internet Explorer.

If the link to the external style sheet is placed after the internal style sheet in HTML , the external style sheet will override the internal style sheet!

If the name of a font family is more than one word, it must be in quotation marks, like font-family: "Times New Roman".

If you do not specify a font size, the default size for normal text, like paragraphs, is 16px (16px=1em).


If you do not specify a font size, the default size for normal text, like paragraphs, is 16px (16px=1em).

When setting the style for several link states, there are some order rules:

* a:hover MUST come after a:link and a:visited
* a:active MUST come after a:hover


Explanation of the different parts:

* Margin - Clears an area around the border. The margin does not have a background color, it is completely transparent
* Border - A border that goes around the padding and content. The border is affected by the background color of the box
* Padding - Clears an area around the content. The padding is affected by the background color of the box
* Content - The content of the box, where text and images appear

In order to set the width and height of an element correctly in all browsers, you need to know how the box model works.

Important: When you specify the width and height properties of an element with CSS, you are just setting the width and height of the content area. To know the full size of the element, you must also add the padding, border and margin.

The total width of the element in the example below is 300px:
width:250px;
padding:10px;
border:5px solid gray;
margin:10px;

Let's do the math:
250px (width)
+ 20px (left and right padding)
+ 10px (left and right border)
+ 20px (left and right margin)
= 300px
Imagine that you only had 250px of space. Let's make an element with a total width of 250px:
Example
width:220px;
padding:10px;
border:5px solid gray;
margin:0px;
The total width of an element should always be calculated like this:

Total element width = width + left padding + right padding + left border + right border + left margin + right margin

The total height of an element should always be calculated like this:

Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin


None of the border properties will have ANY effect unless the border-style property is set!

The "border-width" property does not work if it is used alone. Use the "border-style" property to set the borders first.

The display property specifies if/how an element is displayed, and the visibility property specifies if an element should be visible or hidden.

Hiding an element can be done by setting the display property to "none" or the visibility property to "hidden". However, notice that these two methods produce different results:

visibility:hidden hides an element, but it will still take up the same space as before. The element will be hidden, but still affect the layout.

display:none hides an element, and it will not take up any space. The element will be hidden, and the page will be displayed as the element is not there:

Changing the display type of an element changes only how the element is displayed, NOT what kind of element it is. For example: An inline element set to display:block is not allowed to have a block element nested inside of it.

Positioning: The CSS positioning properties allow you to position an element. It can also place an element behind another, and specify what should happen when an element's content is too big.
Elements can be positioned using the top, bottom, left, and right properties. However, these properties will not work unless the position property is set first. They also work differently depending on the positioning method.


Try the code below for various cursor types:

Mouse over the words to change the cursor.

<html>
<body>
<p>Mouse over the words to change the cursor.</p>
<span style="cursor:auto">auto</span><br />
<span style="cursor:crosshair">crosshair</span><br />
<span style="cursor:default">default</span><br />
<span style="cursor:e-resize">e-resize</span><br />
<span style="cursor:help">help</span><br />
<span style="cursor:move">move</span><br />
<span style="cursor:n-resize">n-resize</span><br />
<span style="cursor:ne-resize">ne-resize</span><br />
<span style="cursor:nw-resize">nw-resize</span><br />
<span style="cursor:pointer">pointer</span><br />
<span style="cursor:progress">progress</span><br />
<span style="cursor:s-resize">s-resize</span><br />
<span style="cursor:se-resize">se-resize</span><br />
<span style="cursor:sw-resize">sw-resize</span><br />
<span style="cursor:text">text</span><br />
<span style="cursor:w-resize">w-resize</span><br />
<span style="cursor:wait">wait</span><br />
</body>
</html>

Thursday, November 25, 2010

Regular Expressions --> Revisiting

Trying to brush up my regex, for this I came across couple of articles which helped me to grasp the concepts:

Part 1

Part 2