Showing posts with label C# Fundamental. Show all posts
Showing posts with label C# Fundamental. Show all posts

boxing and unboxing time calcumate

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 10000; i++)
            {
                box();
            }
            sw.Stop();
            Console.WriteLine("Box = " + sw.Elapsed.ToString());
            Stopwatch sw1 = new Stopwatch();
            sw1.Start();
            for (int j = 0; j < 10000; j++)
            {
                unbox();
            }
            sw1.Stop();
            Console.WriteLine("Box = " + sw1.Elapsed.ToString());
            Console.ReadLine();
        }
        private static void box()
        {
            int i = 123;
            object j = i;
        }
        private static void unbox()
        {
            int i = 123;
            int j = i;
        }
    }
}

Why C# doesn’t supports multiple inheritance?

Why C# doesn’t supports multiple inheritance?

Its good to know that  C# Supports Multiple Inheritance . But i  wrote  my  title that it  doesn’t. Yes  it doesn’t support by Implementation inheritance but supports using Interface  Implementation.  Sounds confused??  have a look at it…
Basic Inheritance

Two types of Inheritance:
1.    Implementation Inheritance: in which class inherits one class and implement/override its methods and properties for example Control object in which System.Windows.Forms.Textbox,System.Windows.Forms.Button both inherits their self from control class. But provides different functionality
2.    Interface inheritance: in which a class inherits from Interface. For example IDisposable. It just inherits definition not implementation. Any type which does interface inheritance it means that it will provide defined functionality called as “Contract”.
Multiple Inheritance:
A class derives from more than one class it is called Multiple inheritance
Multiple inheritance allows a class to take on functionality from multiple other classes, such as allowing a class named StudentMusician to inherit from a class named Person, a class named Musician, and a class named Worker. This can be abbreviated StudentMusician : Person, Musician, Worker.
Ambiguities arise in multiple inheritance, as in the example above, if for instance the class Musician inherited from Person and Worker and the class Worker inherited from Person. There would then be the following rules:
StudentMusician: Person, Musician, Worker
Musician : Person, Worker
Worker: Person
If a compiler is looking at the class StudentMusician it needs to know whether it should join identical features together, or whether they should be separate features. For instance, it would make sense to join the “Age” features of Person together for StudentMusician. A person’s age doesn’t change if you consider them a Person, a Worker, or a Musician. It would, however, make sense to separate the feature “Name” in Person and Musician if they use a different stage name than their given name. The options of joining and separating are both valid in their own context and only the programmer knows which option is correct for the class they are designing.
Debate
There is debate as to whether multiple inheritance can be implemented simply and without ambiguity. It is often criticized for increased complexity and ambiguity, as well as versioning and maintenance problems it can cause (often summarized as the diamond problem).[1] Detractors also point out multiple inheritance implementation problems such as not being able to explicitly inherit from multiple classes and the order of inheritance changing class semantics. There are languages that address all technical issues of multiple inheritance, but the main debate remains whether implementing and using multiple inheritance is easier than using single inheritance and software design patterns.

Multiple Inheritance arises Diamond Problem


programming languages with multiple inheritance and knowledge organization, the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override it), and B and C have overridden that method differently, then via which class does it inherit: B, or C?
For example, a class Button inherits from both classes Rectangle (for appearance) and Mouse (for mouse events), and classes Rectangle and Mouse both inherit from the Object class. Now if the equals method is called for a Button object and there is no such method in the Button class but there is an over-ridden equals method in both Rectangle and Mouse, which method should be called?
It is called the “diamond problem” because of the shape of the class inheritance diagram in this situation. Class A is at the top, both B and C separately beneath it, and D joins the two together at the bottom to form a diamond shape.
C# Supports Multiple Inheritances by Interfaces only
http://kiranpatils.wordpress.com/2008/03/10/why-c-doesn%E2%80%99t-supports-multiple-inheritance/ 
 
http://www.codeproject.com/KB/cs/cs_interfaces.aspx
NOTE: lots of help got from wikipedia
Happy Inheritance!!



















How to store a single quote (') in a character variable in c#.

char ch='\'';
that is single cote \ single cote single cote.

String.join() method

You want to combine strings in your C# program using the string.Join static method. This allows you to easily divide parts of an output string with commas or other delimiters. string

Use string.Join

Here we see a basic example of how you can combine strings in an array or List into a new single string with dividing characters in it. The example that follows will produce the output with separating commas.
Program that joins strings [C#]

using System;

class Program
{
    static void Main()
    {
 string[] arr = { "one", "two", "three" };
 Console.WriteLine(string.Join(",", arr)); // "string" can be lowercase, or
 Console.WriteLine(String.Join(",", arr)); // "String" can be uppercase
    }
}

Output

one,two,three
one,two,three
Description of the example code.
Static method. Here we note that string.Join in C# is a static method, meaning it does not need to be called on an instance of string. It concatenates strings together with a separator string in between them.

HTML example

Here we see how you can use string.Join to concatenate strings of HTML. Often with HTML you need a separating tag or element, such as a <br/> tag or horizontal rule. Join solves this problem elegantly because it doesn't insert the separating tag at the end.
Program that joins HTML strings [C#]

using System;

class Program
{
    static void Main()
    {
 // Problem: combine these words into lines in HTML
 string[] dinosaurs = new string[] { "Aeolosaurus",
     "Deinonychus", "Jaxartosaurus", "Segnosaurus" };

 // Solution: join with break tag.
 string html = string.Join("<br/>\r\n", dinosaurs);
 Console.WriteLine(html);
    }
}

Output

Aeolosaurus<br/>
Deinonychus<br/>
Jaxartosaurus<br/>
Segnosaurus
Description of the example code. There is a string[] array declared at the beginning of the code. Those strings are concatenated with Join into four lines of markup in HTML, separated by the BR tag.

string.Join versus append

String.Join is different from appending many strings together in a loop, such as with StringBuilder, because it does not insert the delimiter or separator at the end of the operation. It only inserts the delimiter in between the strings.

Rewrite StringBuilder

Here we see how you can replace confusing code that appends strings in loops with much simpler string.Join code. The string.Join method is often much faster in addition to being simpler. The two methods below, CombineA and CombineB, have the same output.
 

using System;
using System.Text;

class Program
{
    static void Main()
    {
 string[] catSpecies = { "Aegean", "Birman", "Main Coon", "Nebulung" };
 Console.WriteLine(CombineA(catSpecies));
 Console.WriteLine(CombineB(catSpecies));
    }

    /// <summary>
    /// Combine strings with commas.
    /// </summary>
    static string CombineA(string[] arr)
    {
 return string.Join(",", arr);
    }

    /// <summary>
    /// Combine strings with commas.
    /// </summary>
    static string CombineB(string[] arr)
    {
 StringBuilder builder = new StringBuilder();
 foreach (string s in arr)
 {
     builder.Append(s).Append(",");
 }
 return builder.ToString().TrimEnd(new char[] { ',' });
    }
}

Output

Aegean,Birman,Main Coon,Nebulung
Aegean,Birman,Main Coon,Nebulung
Description of the example code. As noted, the two methods CombineA and CombineB both concatenate each string into a single string with separators. The species of cats are outputted as a single string. The final method shown above, CombineB, has to use the ToString() and TrimEnd() methods to convert the StringBuilder into the result.
ToString UsageTrimEnd, Removing Trailing Chars

Parameters

You can specify four parameters on string.Join, with the last two being the startIndex and the count. This overload is rarely useful in my experience, but could simplify some code.
msdn.microsoft.comExceptions

Exceptions

String.Join can throw three different exceptions: ArgumentNullException, ArgumentOutOfRangeException, and OutOfMemoryException. The first two exceptions are possible quite often, and you should be ready for them. The following example shows one possible exception.
ArgumentNullExceptionArgumentOutOfRangeExceptionOutOfMemoryException
Program that throws exception on Join [C#]

using System;

class Program
{
    static void Main()
    {
 try
 {
     string bug = string.Join(null, null); // Null arguments are bad
 }
 catch (Exception ex)
 {
     Console.WriteLine(ex);
 }
    }
}

Output

System.ArgumentNullException: Value cannot be null.
Parameter name: value
Description of the example code. This code demonstrates what happens when you call string.Join with null parameters. It will throw the ArgumentNullException. Depending on your application, this must be dealt with.

Join List

In real-world programs, the List collection is used frequently and it often contains strings. You can use string.Join to concatenate these strings quickly. You have to call ToArray() on your List and pass it as the second parameter to string.Join. Alternatively, you can use the generic version of string.Join; please see the distinct article.
Join String List
Program that joins on List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 // List of cities
 List<string> cities = new List<string>();
 cities.Add("New York");
 cities.Add("Mumbai");
 cities.Add("Berlin");
 cities.Add("Istanbul");

 // Join strings into one CSV line
 string line = string.Join(",", cities.ToArray());
 Console.WriteLine(line);
    }
}

Output

New York,Mumbai,Berlin,Istanbul
Description of the example code. The Main method first creates a List of strings, and then converts the List into a string[] array using ToArray(). string.Join returns all the strings combined into one with separators.

Benchmark

Here we test the general performance of string.Join. I wanted to see the ballpark numbers for string.Join to ensure that it doesn't cause a severe slowdown. We see that string.Join performs well and often better than loops. Please see the figures at the top of this article.
Data used in benchmark

string[] arr = { "one", "two", "three", "four", "five" };

Methods that were benchmarked [C#]
    1000000 iterations were tested.

static string CombineA(string[] arr)
{
    return string.Join(",", arr);
}

static string CombineB(string[] arr)
{
    var builder = new System.Text.StringBuilder();
    foreach (string s in arr)
    {
 builder.Append(s).Append(",");
    }
    return builder.ToString(); // Has ending comma [difference]
}

Results

string.Join:                 157 ms [faster]
StringBuilder Append method: 270 ms

Required Join method results

Input:  one
 two
 three
Output: one*two*three
Description of benchmarked code. The two methods shown above, CombineA and CombineB, compare string.Join to a StringBuilder loop. They return different strings: CombineA does not have a comma at the end of its result, while CombineB does. Using TrimEnd to remove the comma makes CombineB slower.

Summary

Here we saw several examples of string.Join in the C# language, using comma-separated values and HTML. Finally I established that string.Join has excellent performance for common usages. We also explored the exceptions you can raise with string.Join.

Value type and reference type

http://www.albahari.com/valuevsreftypes.aspx

First, What Are Structs?

Put simply, structs are cut-down classes.  Imagine classes that don’t support inheritance or finalizers, and you have the cut-down version: the struct.  Structs are defined in the same way as classes (except with the struct keyword), and apart from the limitations just described, structs can have the same rich members, including fields, methods, properties and operators.  Here’s a simple struct declaration:
struct Point
{
   private int x, y;             // private fields

   public Point (int x, int y)   // constructor
  
{
         this.x = x;
         this.y = y;
   }

   public int X                  // property
  
{
         get {return x;}
         set {x = value;}
   }

   public int Y
   {
         get {return y;}
         set {y = value;}
   }
}    


Value and Reference Types

There is another difference between structs and classes, and this is also the most important to understand.  Structs are value types, while classes are reference types, and the runtime deals with the two in different ways.  When a value-type instance is created, a single space in memory is allocated to store the value.  Primitive types such as int, float, bool and char are also value types, and work in the same way.  When the runtime deals with a value type, it's dealing directly with its underlying data and this can be very efficient, particularly with primitive types.
With reference types, however, an object is created in memory, and then handled through a separate reference—rather like a pointer.  Suppose Point is a struct, and Form is a class.  We can instantiate each as follows:

Point p1 = new Point();         // Point is a *struct*
Form f1 = new Form();           // Form is a *class*

In the first case, one space in memory is allocated for p1
Iin the second case, two spaces are allocated: one for a Form object and another for its reference (f1).  It's clearer when we go about it the long way:
 
Form f1;                        // Allocate the reference
f1 = new Form();                // Allocate the object

If we copy the objects to new variables:
Point p2 = p1;
Form f2 = f1;

p2, being a struct, becomes an independent copy of p1, with its own separate fields.

 But in the case of f2, all we’ve copied is a reference, with the result that both f1 and f2 point to the same object.

This is of particular interest when passing parameters to methods.  In C#, parameters are (by default) passed by value, meaning that they are implicitly copied when passed to the method.  For value-type parameters, this means physically copying the instance (in the same way p2 was copied), while for reference-types it means copying a reference (in the same way f2 was copied).  Here is an example:

Point myPoint = new Point (0, 0);      // a new value-type variable
Form myForm = new Form();              // a new reference-type variable
Test (myPoint, myForm);                // Test is a method defined below

void Test (Point p, Form f)
{
      p.X = 100;                       // No effect on MyPoint since p is a copy
      f.Text = "Hello, World!";        // This will change myForm’s caption since
                                       // myForm and f point to the same object
      f = null;                        // No effect on myForm
}

Assigning null to f has no effect because f is a copy of a reference, and we’ve only erased the copy.
We can change the way parameters are marshalled with the ref modifier.  When passing by “reference”, the method interacts directly with the caller’s arguments.  In the example below, you can think of the parameters p and f being replaced by myPoint and myForm:

Point myPoint = new Point (0, 0);      // a new value-type variable
Form myForm = new Form();              // a new reference-type variable
Test (ref myPoint, ref myForm);        // pass myPoint and myForm by reference

void Test (ref Point p, ref Form f)
{
      p.X = 100;                       // This will change myPoint’s position
      f.Text = “Hello, World!”;        // This will change MyForm’s caption
      f = null;                        // This will nuke the myForm variable!
}

In this case, assigning null to f also makes myForm null, because this time we’re dealing with the original reference variable and not a copy of it.


Memory Allocation

The Common Language Runtime allocates memory for objects in two places: the stack and the heap.  The stack is a simple first-in last-out memory structure, and is highly efficient.  When a method is invoked, the CLR bookmarks the top of the stack.  The method then pushes data onto the stack as it executes.  When the method completes, the CLR just resets the stack to its previous bookmark—“popping” all the method’s memory allocations is one simple operation!
The heap can be pictured as a random jumble of objects.  Its advantage is that it allows objects to be allocated or deallocated in a random order. The heap requires the overhead of a memory manager and garbage collector to keep things in order.
To illustrate how the stack and heap are used, consider the following method:

void CreateNewTextBox()
{
      TextBox myTextBox = new TextBox();             // TextBox is a class
}

In this method, we create a local variable that references an object.  The local variable is stored on the stack, while the object itself is stored on the heap:
The stack is always used to store the following two things:
  • The reference portion of reference-typed local variables and parameters (such as the myTextBox reference)
  • Value-typed local variables and method parameters (structs, as well as integers, bools, chars, DateTimes, etc.)
The following data is stored on the heap:
  • The content of reference-type objects.
  • Anything structured inside a reference-type object.

Memory Disposal

Once CreateNewTextBox has finished running, its local stack-allocated variable, myTextBox, will disappear from scope and be “popped” off the stack.  However, what will happen to the now-orphaned object on the heap to which it was pointing?  The answer is that we can ignore it—the Common Language Runtime’s garbage collector will catch up with it some time later and automatically deallocate it from the heap.  The garbage collector will know to delete it, because the object has no valid referee (one whose chain of reference originates back to a stack-allocated object).[1]  C++ programmers may be a bit uncomfortable with this and may want to delete the object anyway (just to be sure!) but in fact there is no way to delete the object explicitly.  We have to rely on the CLR for memory disposal—and indeed, the whole .NET framework does just that!
However there is a caveat on automatic destruction.  Objects that have allocated resources other than memory (in particular “handles”, such as Windows handles, file handles and SQL handles) need to be told explicitly to release those resources when the object is no longer required.  This includes all Windows controls, since they all own Windows handles!  You might ask, why not put the code to release those resources in the object’s finalizer?  (A finalizer is a method that the CLR runs just prior to an object’s destruction).  The main reason is that the garbage collector is concerned with memory issues and not resource issues.  So on a PC with a few gigabytes of free memory, the garbage collector may wait an hour or two before even getting out of bed!
So how do we get our textbox to release that Windows handle and disappear off the screen when we’re done with it?  Well, first, our example was pretty artificial.  In reality, we would have put the textbox control on a form in order to make it visible it in the first place.  Assuming myForm was created earlier on, and is still in scope, this is what we’d typically do:
myForm.Controls.Add (myTextBox);
As well as making the control visible, this would also give it another referee (myForm.Controls). This means that when the local reference variable myTextBox drops out of scope, there’s no danger of the textbox becoming eligible for garbage collection.  The other effect of adding it to the Controls collection is that the .NET framework will deterministically call a method called Dispose on all of its members the instant they’re no longer needed.  And in this Dispose method, the control can release its Windows handle, as well as dropping the textbox off the screen.
All classes that implement IDisposable (including all Windows Forms controls) have a Dispose method.  This method must be called when an object is no longer needed in order to release resources other than memory.  There are two ways this happens:
 - manually (by calling Dispose explicitly)
 - automatically: by adding the object to a .NET container, such as a Form, Panel, TabPage or UserControl.  The container will ensure that when it’s disposed, so are all of its members.  Of course, the container itself must be disposed (or in turn, be part of another container).
In the case of Windows Forms controls, we nearly always add them to a container – and hence rely on automatic disposal.
The same thing applies to classes such as FileStream—these need to be disposed too.  Fortunately, C# provides a shortcut for calling Dispose on such objects, in a robust fashion: the using statement:
using (Stream s = File.Create ("myfile.txt"))
{
   ...
}
This translates to the following code:
Stream s = File.Create ("myfile.txt");
try
{
   ...
}
finally
{
   if (s != null) s.Dispose();
}
The finally block ensurse that Dispose still gets executed should an exception be thrown within the main code block.
What about in WPF?
Most of the elements in WPF don’t wrap unmanaged handles requiring explicit disposal. So you can mostly ignore the disposal with WPF!

A Windows Forms Example

Let's look a couple more types you’ll come across often in Windows Forms applications.  Size is a type used for representing a 2-dimensional extent and Font, as you would expect, encapsulates a font and its properties.  You can find them in the .NET framework, in the System.Drawing namespace. The Size type is a struct—rather like Point, while the Font type is a class.  We'll create an object of each type:
Size s = new Size (100, 100);          // struct = value type
Font f = new Font (“Arial”,10);        // class = reference type
and we’ll also create a form.  Form is a class in System.Windows.Forms namespace, and is hence a reference type:
Form myForm = new Form();
To set the form's size and font, we can assign the objects s and f to the form via its properties:
myForm.Size = s;
myForm.Font = f;

Don't get confused by the double usage of the identifiers Size and Font: now they are referring to members of myForm and not the Size and Font classes.  This double usage is acceptable in C# and is applied extensively throughout the .NET framework.
Here's what it now looks like in memory:
As you can see, with s, we've copied over its contents, while in the case of f, we've copied over its reference (resulting in two pointers in memory to the same Font object).  This means that changes made via s will not affect the form, while changes made via f, will[2].
In-Line Allocation
Previously we said that for value-typed local variables, memory is allocated on the stack.  So does that mean the newly copied Size struct is also allocated on the stack?  The answer is no, because it’s not a local variable!  Instead, it’s stored in a field of another object (in this case a form) that’s allocated on the heap.  Therefore, it must, too, be allocated on the heap.  This mode of storage is called "in-line". 

Fun with Structs

We've made a slightly simplifying assumption in the diagrams in that Size and Font are depicted as fields in the Form class.  More accurately, they are properties, which are facades for internal representations we don’t get to see.  We can imagine their definitions look something like this:
class Form
{
      // Private field members
      Size size;
      Font font;

      // Public property definitions
      public Size Size
      {
            get    { return size; }
            set    { size = value; fire resizing events }
      }
      public Font Font
      {
            get    { return font;  }
            set    { font = value; }
      }
}
By using properties, the class has an opportunity to fire events when the form’s size or font changes.  It provides further flexibility in that other size-related properties, such as ClientSize (the size of a control’s internal area without title bar, borders, or scroll bars) can work in tandem with the same private fields.
But there is a snag.  Suppose we want to double the form’s height, through one of its properties.  It would seem reasonable to do this :
myForm.ClientSize.Height = myForm.ClientSize.Height * 2;
or more simply:
myForm.ClientSize.Height *= 2;
However, this generates a compiler error:
Cannot modify the return value of 'System.Windows.Forms.Form.ClientSize' because it is not a variable
We get the same problem whether we use Size or ClientSize.  Let’s look at why.
Imagine ClientSize as a public field rather than a property.  The expression myForm.ClientSize.Height would then simply reach through the membership hierarchy in a single step and access the Height member as expected.  But since ClientSize is a property, myForm.ClientSize is first evaluated (using the property’s get method), returning an object of type Size.  And because Size is a struct (and hence a value-type) what we get back is a copy of the form’s size.  And it’s this copy whose size we double!  C# realizes our mistake, and generates an error rather than compiling something that it knows won’t work.  (Had Size been defined instead as a class, there would have been no problem, since ClientSize’s get accessor would have returned a reference, giving us access to the form’s real Size object.)
So how then do we change the form’s size?  You have to assign it a whole new object:
myForm.ClientSize = new Size
  (myForm.ClientSize.Width, myForm.ClientSize.Height * 2);
There’s more good news in that with most controls we usually size them via their external measurements (Size rather than ClientSize) and for these we also have ordinary integer Width and Height properties that we can get and set!
You might wonder if they could they have saved all this bother by defining Size as a class rather than a struct.  But if Size was a class, its Height and Width properties would probably have been made read-only to avoid the complication of having to raise events whenever their values changed (so that the control can know to resize itself).  And as read-only properties, you would be forced to go about changing them by creating a new object—so we’d be back to square one!























Data types in c#

Predefined C# value types

  • sbyte: Holds 8-bit signed integers. The s in sbyte stands for signed, meaning that the variable's value can be either positive or negative. The smallest possible value for ansbyte variable is -128; the largest possible value is 127.
  • byte: Holds 8-bit unsigned integers. Unlike sbyte variables, byte variables are not signed and can only hold positive numbers. The smallest possible value for a byte variable is 0; the largest possible value is 255.
  • short: Holds 16-bit signed integers. The smallest possible value for a short variable is -32,768; the largest possible value is 32,767.
  • ushort: Holds 16-bit unsigned integers. The u in ushort stands for unsigned. The smallest possible value of an ushort variable is 0; the largest possible value is 65,535.
  • int: Holds 32-bit signed integers. The smallest possible value of an int variable is -2,147,483,648; the largest possible value is 2,147,483,647.
  • uint: Holds 32-bit unsigned integers. The u in uint stands for unsigned. The smallest possible value of a uint variable is 0; the largest possible value is 4,294,967,295.
  • long: Holds 64-bit signed integers. The smallest possible value of a long variable is 9,223,372,036,854,775,808; the largest possible value is 9,223,372,036,854,775,807.
  • ulong: Holds 64-bit unsigned integers. The u in ulong stands for unsigned. The smallest possible value of a ulong variable is 0; the largest possible value is 18,446,744,073,709,551,615.
  • char: Holds 16-bit Unicode characters. The smallest possible value of a char variable is the Unicode character whose value is 0; the largest possible value is the Unicode character whose value is 65,535.
  • float: Holds a 32-bit signed floating-point value. The smallest possible value of a float type is approximately 1.5 times 10 to the 45th power; the largest possible value is approximately 3.4 times 10 to the 38th power.
  • double: Holds a 64-bit signed floating-point value. The smallest possible value of a double is approximately 5 times 10 to the 324th; the largest possible value is approximately 1.7 times 10 to the 308th.
  • decimal: Holds a 128-bit signed floating-point value. Variables of type decimal are good for financial calculations. The smallest possible value of a decimal type is approximately 1 times 10 to the 28th power; the largest possible value is approximately 7.9 times 10 to the 28th power.
  • bool: Holds one of two possible values, true or false. The use of the bool type is one of the areas in which C# breaks from its C and C++ heritage. In C and C++, the integer value 0 was synonymous with false, and any nonzero value was synonymous with true. In C#, however, the types are not synonymous. You cannot convert an integer variable into an equivalent bool value. If you want to work with a variable that needs to represent a true or false condition, use a bool variable and not an int variable.

Predefined C# reference types


  • string: Represents a string of Unicode characters. It allows easy manipulation and assignment of strings. Strings are immutable, meaning that once it is created it can't be modified. So when you try to modify a string, such as concatenating it with another string, a new string object is actually created to hold the new resulting string.
  • object: Represents a general purpose type. In C#, all predefined and user-defined types inherit from the object type or System.Object class.

Fundamental

http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx

What is type safe?

Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable.
Some simple examples:
// Fails, Trying to put an integer in a string
String one = 1;
// Also fails.
int foo = "bar";
This also applies to method arguments, since you are passing explicit types to them:
int AddTwoNumbers(int a, int b)
{
    return a + b;
}
If I tried to call that using:
int Sum = AddTwoNumbers(5, "5");