Tech 'n' Tech Books


C# Tips and C# FAQs


What is C#?

C# (pronounced C-Sharp) is a new programming language introduced with the Microsoft .NET framework and is no doubt the language of choice in .NET environment. It was first created in the late 1990's as part of Microsoft’s whole .NET strategy. It is a whole new language free of backward compatibility curse and a whole bunch of new, exciting and promising features. It is an Object Oriented Programming language, which at its core, has similarities with Java, C++ and VB.
In fact, C# combines the power & efficiency of C++, simple & clean OO design of Java, and code simplification of Visual Basic. Like Java, C# also does not allow multiple inheritance and use of pointers (in safe and managed code) while it does provide garbage memory collection at runtime, type and memory access checking. But, contrary to java, C# keeps the different useful concepts of C++ like operator overloading, enumerations, pre-processor directives, pointers (in unmanaged and un-safe code), function pointers (in the form of delegates), also promises to have template support (with the name of generics) in next versions. Like VB it also supports the concepts of properties (context sensitive accessor to fields).
In addition to this, C# comes up with some new/exciting features like reflections, attributes, marshalling, remoting, threads, streams, data access with ADO.NET, etc. C# programming language is designed from the scratch keeping in mind the Microsoft.Net environment. MS.Net (and thus C#) programs runs on top of the Common Language Runtime (CLR), which provides the runtime support to them.

Sample C# Application

Using System
Class Sample
{
public static void main()
{
Console.WriteLine (“Hello World”)
}
}

What are Jagged Arrays in C#?

A special type of array is introduced in C#. A Jagged Array is an array of an array in which the length of each array index can differ.
Example: A Jagged Array can be used is to create a table in which the lengths of the rows are not same. This Array is declared using square brackets ( [ ] ) to indicate each dimension.
The following code demonstrates the creation of a two-dimensional jagged array.
Class Jagged
{
public static void Main()
{
int [][] jagged=new int [3][];
jagged[0]=mew int[4]
jagged[1]=mew int[3]
jagged[2]=mew int[5]
int I;
‘Storing values in first array
for (I=0;I<4;I++)
jagged[0][I]=I;
‘Storing values in second array
for( I=0;I<3;I++)
jagged[1][I]=I;
‘Storing values in third array
for(I=0;I<5;I++)
jagged[2][I]=I;
‘Displaying values from first array
for (I=0;I<4;I++)
Console.WriteLine(jagged[0][I])
‘Displaying values from second array

for (I=0;I<3;I++)
Console.WriteLine(jagged[1][I])

‘Displaying values from third array
for(I=0;I<5;I++)
Console.WriteLine(jagged[2][I])
}
}
Run the code to see the output.

What is the difference between "Value Types" and "Reference Types"?

Many programming languages provide built-in data types such as integers and floating-point numbers. These are copied when they are passed in to arguments i.e. they are passed "By Value". In .NET terms, these are called Value Types".
The RunTime supports two kinds of Value Types:
1 Built-in value types
The .NET Framework defines built-in value types such as System.Int32 and System.Boolean which correspond and are identical to primitive data types used in programming languages.
2 User-defined value types
The language you are using will provide functionality to define your own Value Types. These user defined Types derive from System.ValueType. If you want to define a Type representing a value that is a complex number (two floating-point numbers), you might choose to define it as a value type. Why? Because you can pass the Value Type efficiently "By Value". If the Type you are defining could be more efficiently passed "By Reference", you should define it as a class instead. Variables of Reference Types are referred to as objects. These store references to the actual data.
The following are the Reference Types:
  • class
  • interface
  • delegate
This following are the "built-in" Reference Types:
  • object
  • string 

How to download a file to disk in C#

All you have to do is to use these two lines to download a file from the internet and save it to your drive.
string URL="http://www.yourdomain.com/file1.zip";
string DestinationPath="C:\file1.zip";
System.Net.WebClient Client = new WebClient();
Client.DownloadFile(URL,DestinationPath);


How to Convert a string numeric value of an Enum to an enumerated object?

You can use the Parse method of the Enum object.
Say, this is the enum defined:
enum Colors {Red=1, Green=2, Blue=4} 

string mystring="Red";

Colors myEnum=(Colors)Enum.Parse(typeof(Colors),mystring);
Console.WriteLine("My Color is : {0}", myEnum.ToString());

How do I have an object notify me of any changes in real time?

Events provide a generally useful way for objects to signal state changes that may be useful to clients of that object. In order to support this, you need to create an event of type EventHandler with the name <property name>Changed. Then, in the property setter of the object, after you store the value (or do whatever you have to do to ensure that getting the value will return the new value), fire the event.
The event model in the .NET Framework is based on having an event delegate that connects an event with its handler. To raise an event, two elements are needed:
  • A class that holds the event data.
  • This class must derive from the base class EventArgs.
A delegate that points to a method that provides the response to the event.
Example:
public delegate void EventHandler(Object sender, EventArgs e);
public event EventHandler DataChangedEventHandler;

How do I implement function pointers in C#?

Delegates provide the functionality of function pointers in C#. Here is an example that illustrates both:
Function pointer example:
typedef int (*FUNC_PTR)(void *, void *);

int Compare(void* a, void* b) { ... }

int CallFunction(void* a, void*b)
{
    FUNC_PTR myFunc = Compare;
   
    for (i = left+1; i <= right; i++)
        if (myFunc(v[i], v[left]) < 0)

}
Equivalent delegate example:
public delegate int FUNC(object x, object y);
public int Compare(object x, object y) { ... }
public void sort()
{
    CMP_Func myFuncObj = new FUNC(Compare);
    ...
    if (myFuncObj(x, y) < 0)
        System.Console.WriteLine("Object X is less than Object Y");
    else if (myFuncObj(x, y) = 0)
        System.Console.WriteLine("Object X equals Object Y");
    else
        System.Console.WriteLine("Object X is greater than Object Y");
}

How do I use a class developed by VC++6.0 in C#?

A full length tutorial on how this can be done is beyond the scope of this answer. However here is a background:
C# supports calling unmanaged code. Depending on the type of C++ project, you may be able to call it using COM Interop or PInvoke.
1. Platform Invocation Service:
Platform Invoke Services acts as a bridge between the managed and unmanaged code. They enable the managed code to call the functions which are being exposed by the dynamic link libraries such as Win32 API’s and custom DLL’s.
Supply a DllImport attribute. Declare the methods in your .NET code as static extern. Do not implement the methods as they are implemented in your unmanaged code, you’re just providing declarations for method signatures.
2. COM Interop Services:
This enables the managed code to interact with the COM objects. One way is you use the Type Library Import utility shipped with SDK. tlbimp COMobject.dll /out:.NETobject.dll or reference the COM library from Visual Studio in your project.
You can reference the Microsoft’s MSDN site for detailed examples and tutorials.

How to dynamically instantiate a class based on a string being the class name?

You can do it using reflection-
Reflection is the process by which a program can read its own metadata. A program is said to reflect on itself, extracting metadata from its assembly and using that metadata either to inform the user or to modify its own behavior.
You can invoke the Cos() of the System.Math class by first getting the Type information for the System.Math class:
Type mathType = Type.GetType("System.Math");
With that type information, you can dynamically load an instance of that class by using a static method of the Activator class.
The Activator class contains four methods, all static, which you can use to create objects locally or remotely or to obtain references to existing objects. One of them is CreateInstance:
Object theObj = Activator.CreateInstance(mathType); 

Does any one have an example of how to create an ArrayList of objects?

It's like adding any other item to an ArrayList, and then retrieving that. For example, if you wanted to add a Hashtable to an ArrayList, then you would do this:
// An array list. 
ArrayList arrayList = new ArrayList(); 

// Add hashtables.
for (int index = 0; index < 10; index++)
{
    // Add a hashtable.
    arrayList.Add(new Hashtable());
}

How do I get type information on an object?

You can get type information using reflection-
Reflection is the process by which a program can read its own metadata. A program is said to reflect on itself, extracting metadata from its assembly and using that metadata either to inform the user or to modify its own behavior.
All .NET assemblies contain type information which describes the structure of every internal and external type. Many methods in the .NET base class libraries require you to pass in type information for a given item. When you need to obtain type information for a given method invocation, you have numerous approaches.
First, all types inherit the public System.Object.GetType() method:
// obtain type information from a variable.
MyType c = new MyType();
Type t = c.GetType();
GetTypeInfo(t);
Or simply use:
// obtain type information via typeof.
GetTypeInfo(typeof(MyType));