Sunday, 22 July 2012

I wonder Why ?

I wonder Why ?

#1 We have "string" and "String" in C# when both does the same thing ?

Answer : Answer is fairly simple. string is an alias of String. Hows that ?. To achieve type safety, Microsoft has designed the Managed languages such that they can communicate with each other.

For the entire framework we have base types such as System.String and thus their code specific alias such as string in C# and String in VB. When we compile the program in C# it actually refers to System.String(Kinda how alias is suppose to work right)

There are plenty of other alias too
    object     : System.Object    
    string      : System.String      
    bool        : System.Boolean   
    byte        : System.Byte
    sbyte       : System.SByte
    short       : System.Int16
    ushort     : System.UInt16
     int          : System.Int32
    uint         : System.UInt32
    long        : System.Int64
    ulong      : System.UInt64
    float        : System.Single
    double     : System.Double
    decimal   : System.Decimal
    char         : System.Char

#2 We use Stringbuilders over Strings ?

Answer: One word "MUTABLE". If we are writing a program and we have a lot of strings we want to manipulate we better go for Stringbuilders rather using the Strings.

Suppose we want to concatenate two strings.

            string a = "Hello";
            string b = " World";

            string c = a + b;

What happens is "a" is created and "Hello" is stored in it. Then "b" is created and " World" is stored.
Then "c" is created and a new instance of a is created and added with another new instance of b and and the concatenated value is stored in c. LOSS of good memory.

In case of StringBuilder we have .Append fucntion which when used, uses the same memory location to change the value. No new instance. Hence the word "Mutable"

#3 We use tilde operator ?

Answer: This little operator, tilde (~) operator is used as an Unary Operator otherwiser known as bitwise NOT operator.

What is that ? Look at this peice of code.

Here the output will always be equal as tilde operator performs the 2's Compliment on the number.

As per 2's compliment - ~ <number> = (- <number> ) - 1  

#4 We cannot inherit Structures ? (Sorry I ran outta "Why" facts)

Answer: I searched this in the internet and found the answer. The answer is "You cannot inherit a sealed type". Why I am saying this ? Because, if you create a structure and try to inherit it in your class and build the application then you will see the error. "Man !! I should have first checked it in Visual Studio."

No comments:

Post a Comment