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

Creating Connections to Oracle Databases


  • ' Visual Basic
    Public Sub ConnectToOracle()
    Dim conn As New OracleClient.OracleConnection()
    ' TODO: Modify the connection string and include any
    ' additional required properties for your database.
    conn.ConnectionString = & _
    "Data Source=;Integrated Security=yes"
    Try
    conn.Open()
    ' Insert code to process data.
    Catch ex As Exception
    MessageBox.Show("Failed to connect to data source")
    Finally
    conn.Close()
    End Try
    End Sub

    // C#
    public void ConnectToOracle()
    {
    OracleClient.OracleConnection conn =
    new OracleClient.OracleConnection ();
    // TODO: Modify the connection string and include any
    // additional required properties for your database.
    conn.ConnectionString = "Data Source=" +
    ";Integrated Security=yes";
    try
    {
    conn.Open();
    // Insert code to process data.
    }
    catch (Exception ex)
    {
    MessageBox.Show("Failed to connect to data source");
    }
    finally
    {
    conn.Close();
    }
    }


0 comments  

Creating Connections to ODBC Data Sources


  • ' Visual Basic
    Public Sub ConnectToOdbc()
    Dim conn As New System.Data.Odbc.OdbcConnection
    ' TODO: Modify the connection string and include any
    ' additional required properties for your database.
    conn.ConnectionString = & _
    "FIL=MS Access;DSN=valid data source name"
    Try
    conn.Open()
    ' Insert code to process data.
    Catch ex As Exception
    MessageBox.Show("Failed to connect to data source")
    Finally
    conn.Close()
    End Try
    End Sub

    // C#
    public void ConnectToData()
    {
    System.Data.Odbc.OdbcConnection conn =
    new System.Data.Odbc.OdbcConnection ();
    // TODO: Modify the connection string and include any
    // additional required properties for your database.
    conn.ConnectionString = "FIL=MS Access;DSN=valid data source name";
    try
    {
    conn.Open();
    // Process data here.
    }
    catch (Exception ex)
    {
    MessageBox.Show("Failed to connect to data source");
    }
    finally
    {
    conn.Close();
    }
    }


0 comments  

Creating Connections to Access Databases


  • ' Visual Basic
    Public Sub ConnectToAccess()
    Dim conn As New System.Data.OleDb.OleDbConnection()
    ' TODO: Modify the connection string and include any
    ' additional required properties for your database.
    conn.ConnectionString = & _
    "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" & _
    "C:\Documents and Settings\username\My Documents\dbFile.mdb"
    Try
    conn.Open()
    ' Insert code to process data.
    Catch ex As Exception
    MessageBox.Show("Failed to connect to data source")
    Finally
    conn.Close()
    End Try
    End Sub

    // C#
    public void ConnectToAccess()
    {
    System.Data.OleDb.OleDbConnection conn = new
    System.Data.OleDb.OleDbConnection();
    // TODO: Modify the connection string and include any
    // additional required properties for your database.
    conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
    @"Data source= C:\Documents and Settings\username\" +
    @"My Documents\AccessFile.mdb";
    try
    {
    conn.Open();
    // Insert code to process data.
    }
    catch (Exception ex)
    {
    MessageBox.Show("Failed to connect to data source");
    }
    finally
    {
    conn.Close();
    }
    }


0 comments  

Creating Connections to SQL Server


  • ' Visual Basic
    Public Sub ConnectToSql()
    Dim conn As New SqlClient.SqlConnection
    ' TODO: Modify the connection string and include any
    ' additional required properties for your database.
    conn.ConnectionString = & _
    "integrated security=SSPI;data source=SQL Server Name;" & _
    "persist security info=False;initial catalog=northwind"
    Try
    conn.Open()
    ' Insert code to process data.
    Catch ex As Exception
    MessageBox.Show("Failed to connect to data source")
    Finally
    conn.Close()
    End Try
    End Sub

    // C#
    public void ConnectToSql ()
    {
    System.Data.SqlClient.SqlConnection conn =
    new System.Data.SqlClient.SqlConnection ();
    // TODO: Modify the connection string and include any
    // additional required properties for your database.
    conn.ConnectionString =
    "integrated security=SSPI;data source=SQL Server Name;" +
    "persist security info=False;initial catalog=northwind";
    try
    {
    conn.Open();
    // Insert code to process data.
    }
    catch (Exception ex)
    {
    MessageBox.Show("Failed to connect to data source");
    }
    finally
    {
    conn.Close();
    }
    }

0 comments  

Reading and Writing Text File

Text files provide a common denominator format where both people and programs can read and understand. The .NET Framework includes convenience classes that make reading and writing text files very easy. The following sequence outlines the basic steps necessary to work with text files:

  1. Open the file
  2. Read/Write to the file
  3. Close the file

It's that simple. Listing 1 shows how to write text data to a file.

Writing to a Text File

Listing 1: Writing Text Data to a File: TextFileWriter.cs

using System;
using System.IO;

namespace csharp_station.howto
{
class TextFileWriter
{
static void Main(string[] args)
{
// create a writer and open the file
TextWriter tw = new StreamWriter("date.txt");

// write a line of text to the file
tw.WriteLine(DateTime.Now);

// close the stream
tw.Close();
}
}
}

This program creates a text file when it runs. In the directory where the executable program is located, you'll find a file named date.txt. If you view the contents of this file, you'll see the following textual representation of the date and time when the program last ran:

2/15/2002 8:54:51 PM

The first task in Listing 1 is to open the file. This happens by instantiating a StreamWriter class, which returns an object of type TextWriter. The result could have also been assigned to a StreamWriter instance. The StreamWriter was called with a single parameter, indicating the name of the file to open. If this file doesn't exist, the StreamWriter will create it. The StreamWriter also has 6 other constructor overloads that permit you to specify the file in different ways, buffer info, and text encoding. Here's the line that opens the date.txt file:

TextWriter tw = new StreamWriter("date.txt");

Using the TextWriter instance, tw, you can write text info to the file. The example writes the text for the current date and time, using the static Now property of the DateTime class. Here's the line from the code:

tw.WriteLine(DateTime.Now);

When you're done writing to the file, be sure to close it as follows:

tw.Close();

Reading From a Text File

Listing 2 shows how to read from a text file:

Listing 2: Reading Text Data from a File: TextFileReader.cs

using System;
using System.IO;

namespace csharp_station.howto
{
class TextFileReader
{
static void Main(string[] args)
{
// create reader & open file
Textreader tr = new StreamReader("date.txt");

// read a line of text
Console.WriteLine(tr.ReadLine());

// close the stream
tr.Close();
}
}
}

In Listing 2, the text file is opened in a manner similar to the method used in Listing 1, except it uses a StreamReader class constructor to create an instance of a Textreader. The StreamReader class includes additional overloads that allow you to specify the file in different ways, text format encoding, and buffer info. This program opens the date.txt file, which should be in the same directory as the executable file:

Textreader tr = new StreamReader("date.txt");

Within a Console.WriteLine statement, the program reads a line of text from the file, using the ReadLine() method of the Textreader instance. The Textreader class also includes methods that allow you to invoke the Read() method to read one or more character or use the Peek() method to see what the next character is without pulling it from the stream. Here's the code that reads an entire line from the text file:

Console.WriteLine(tr.ReadLine());

When done reading, you should close the file as follows:

tr.Close();

Summary

This article showed how to write text to a file and read it back out. For more details on additional methods, consult the .NET Frameworks reference on the StreamWriter, StreamReader, TextWriter, and Textreader classes.

0 comments  

Reading Excel files from .NET/C#

First you must declare using namespace


using Microsoft.Office.Interop.Excel;
if the Office Primary Interop Assemblies is installed in your system. If not, you can get it at http://www.microsoft.com/downloads/details.aspx?FamilyId=C41BD61E-3060-4F71-A6B4-01FEBA508E52&displaylang=en

Microsoft has changed the design of Office Primary Interop Assemblies in Office 2003. So if you want to read Excel files from a system with Office 2002 or before, you must use:

   Excel.Application excel = new Excel.Application();

Excel.Workbook theWorkbook = excel.Workbooks.Open(
FileName,,Missing.Value,Missing.Value,Missing.Value,Missing.Value,
Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,
Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value);
You can't use null as parameters, that will cause an exception.

in Office 2003, Excel is just a namespace and everything has a Class postfix:


ApplicationClass excel=new ApplicationClass();

Workbook theWorkbook = excel.Workbooks.Open(
FileName,,Missing.Value,Missing.Value,Missing.Value,Missing.Value,
Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,
Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value);

After you open the workbook, you can use the following codes to get data into your memory:

ws=(Worksheet)wb.Sheets[1];
r=ws.get_Range("B3","K100");
values=(object[,])r.Value2;
the Range.Value2 return a 2-dimension array of object. The first represents rows and the second represents columns. For example, if you want to get the value in B10, which is the 8-th row and the first column is return range r. You can use

v=values[8,1].ToString();
to get the value. You will know many features in Excel COM Model are missing in the .NET imlementation.

Source : http://blog.jumbosoft.com/alvincho/PermaLink,guid,77f86a28-206f-4474-b12b-1fcc6160a286.aspx

0 comments  

Structs Tutorial

This tutorial presents the syntax and usage of structs. It also covers the important differences between classes and structs.

Tutorial

This tutorial includes two examples. The first example shows you how to declare and use structs, and the second example demonstrates the difference between structs and classes when instances are passed to methods. You are also introduced to the following topics:

  • Structs vs. Classes
  • Heap or Stack?
  • Constructors and Inheritance
  • Attributes on Structs

Example 1

This example declares a struct with three members: a property, a method, and a private field. It creates an instance of the struct and puts it to use:

// struct1.cs
using System;
struct SimpleStruct
{
private int xval;
public int X
{
get
{
return xval;
}
set
{
if (value < 100)
xval = value;
}
}
public void DisplayX()
{
Console.WriteLine("The stored value is: {0}", xval);
}
}

class TestClass
{
public static void Main()
{
SimpleStruct ss = new SimpleStruct();
ss.X = 5;
ss.DisplayX();
}
}

Output

The stored value is: 5

Structs vs. Classes

Structs may seem similar to classes, but there are important differences that you should be aware of. First of all, classes are reference types and structs are value types. By using structs, you can create objects that behave like the built-in types and enjoy their benefits as well.

Heap or Stack?

When you call the New operator on a class, it will be allocated on the heap. However, when you instantiate a struct, it gets created on the stack. This will yield performance gains. Also, you will not be dealing with references to an instance of a struct as you would with classes. You will be working directly with the struct instance. Because of this, when passing a struct to a method, it's passed by value instead of as a reference.

Example 2

This example shows that when a struct is passed to a method, a copy of the struct is passed, but when a class instance is passed, a reference is passed.

// struct2.cs
using System;

class TheClass
{
public int x;
}

struct TheStruct
{
public int x;
}

class TestClass
{
public static void structtaker(TheStruct s)
{
s.x = 5;
}
public static void classtaker(TheClass c)
{
c.x = 5;
}
public static void Main()
{
TheStruct a = new TheStruct();
TheClass b = new TheClass();
a.x = 1;
b.x = 1;
structtaker(a);
classtaker(b);
Console.WriteLine("a.x = {0}", a.x);
Console.WriteLine("b.x = {0}", b.x);
}
}

Output

a.x = 1
b.x = 5

Code Discussion

The output of the example shows that only the value of the class field was changed when the class instance was passed to the classtaker method. The struct field, however, did not change by passing its instance to the structtaker method. This is because a copy of the struct was passed to the structtaker method, while a reference to the class was passed to the classtaker method.

Constructors and Inheritance

Structs can declare constructors, but they must take parameters. It is an error to declare a default (parameterless) constructor for a struct. Struct members cannot have initializers. A default constructor is always provided to initialize the struct members to their default values.

When you create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator. If you do not use New, the fields will remain unassigned and the object cannot be used until all the fields are initialized.

There is no inheritance for structs as there is for classes. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class object. A struct can implement interfaces, and it does that exactly as classes do. Here's a code snippet of a struct implementing an interface:

interface IImage
{
void Paint();
}

struct Picture : IImage
{
public void Paint()
{
// painting code goes here
}
private int x, y, z; // other struct members
}

Attributes on Structs

By using attributes you can customize how structs are laid out in memory. For example, you can create what's known as a union in C/C++ by using the StructLayout(LayoutKind.Explicit) and FieldOffset attributes.

using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct TestUnion
{
[FieldOffset(0)]
public int i;
[FieldOffset(0)]
public double d;
[FieldOffset(0)]
public char c;
[FieldOffset(0)]
public byte b1;
}

In the preceding code segment, all of the fields of TestUnion start at the same location in memory.

The following is another example where fields start at different explicitly set locations:

using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct TestExplicit
{
[FieldOffset(0)]
public long lg;
[FieldOffset(0)]
public int i1;
[FieldOffset(4)]
public int i2;
[FieldOffset(8)]
public double d;
[FieldOffset(12)]
public char c;
[FieldOffset(14)]
public byte b1;
}

The two int fields, i1 and i2, share the same memory locations as lg. This sort of control over struct layout is useful when using platform invocation.

Conclusion

Structs are simple to use and can prove to be useful at times. Just keep in mind that they're created on the stack and that you're not dealing with references to them but dealing directly with them. Whenever you have a need for a type that will be used often and is mostly just a piece of data, structs might be a good option.

0 comments  

Collection Classes Tutorial

The foreach statement is a convenient way to iterate over the elements of an array. It can also enumerate the elements of a collection, provided that the collection class has implemented the System.Collections.IEnumerator and System.Collections.IEnumerable interfaces.

Example 1

The following code sample illustrates how to write a collection class that can be used with foreach. The class is a string tokenizer, similar to the C run-time function strtok.

// tokens.cs
using System;
// The System.Collections namespace is made available:
using System.Collections;

// Declare the Tokens class:
public class Tokens : IEnumerable
{
private string[] elements;

Tokens(string source, char[] delimiters)
{
// Parse the string into tokens:
elements = source.Split(delimiters);
}

// IEnumerable Interface Implementation:
// Declaration of the GetEnumerator() method
// required by IEnumerable
public IEnumerator GetEnumerator()
{
return new TokenEnumerator(this);
}

// Inner class implements IEnumerator interface:
private class TokenEnumerator : IEnumerator
{
private int position = -1;
private Tokens t;

public TokenEnumerator(Tokens t)
{
this.t = t;
}

// Declare the MoveNext method required by IEnumerator:
public bool MoveNext()
{
if (position < position =" -1;" f =" new">

Output

This
is
a
well
done
program.

Code Discussion

In the preceding example, the following code is used to Tokens by breaking "This is a well-done program." into tokens (using ' ' and '-' as separators) and enumerating those tokens with the foreach statement:

Tokens f = new Tokens("This is a well-done program.",
new char[] {' ','-'});
foreach (string item in f)
{
Console.WriteLine(item);
}

Notice that, internally, Tokens uses an array, which implements IEnumerator and IEnumerable itself. The code sample could have leveraged the array's enumeration methods as its own, but that would have defeated the purpose of this example.

In C#, it is not strictly necessary for a collection class to inherit from IEnumerable and IEnumerator in order to be compatible with foreach; as long as the class has the required GetEnumerator, MoveNext, Reset, and Current members, it will work with foreach. Omitting the interfaces has the advantage of allowing you to define the return type of Current to be more specific than object, thereby providing type-safety.

For example, starting with the sample code above, change the following lines:

public class Tokens  // no longer inherits from IEnumerable
public TokenEnumerator GetEnumerator() // doesn't return an IEnumerator
public class TokenEnumerator // no longer inherits from IEnumerator
public string Current // type-safe: returns string, not object

Now, because Current returns a string, the compiler can detect when an incompatible type is used in a foreach statement:

foreach (int item in f)  // Error: cannot convert string to int

The disadvantage of omitting IEnumerable and IEnumerator is that the collection class is no longer interoperable with the foreach statements (or equivalents) of other common language runtime-compatible languages.

You can have the best of both worlds — type-safety within C# and interoperability with other common language runtime-compatible languages — by inheriting from IEnumerable and IEnumerator and using explicit interface implementation, as demonstrated in the following example.

Example 2

This sample is equivalent in function to Example 1, but it provides additional type-safety in C# while maintaining interoperability with other languages.

// tokens2.cs
using System;
using System.Collections;

public class Tokens: IEnumerable
{
private string[] elements;

Tokens(string source, char[] delimiters)
{
elements = source.Split(delimiters);
}

// IEnumerable Interface Implementation:

public TokenEnumerator GetEnumerator() // non-IEnumerable version
{
return new TokenEnumerator(this);
}

IEnumerator IEnumerable.GetEnumerator() // IEnumerable version
{
return (IEnumerator) new TokenEnumerator(this);
}

// Inner class implements IEnumerator interface:

public class TokenEnumerator: IEnumerator
{
private int position = -1;
private Tokens t;

public TokenEnumerator(Tokens t)
{
this.t = t;
}

public bool MoveNext()
{
if (position < position =" -1;" f =" new">

0 comments  

Versioning Tutorial

This tutorial demonstrates versioning in C# through the use of the override and new keywords. Versioning maintains compatibility between base and derived classes as they evolve.

The C# language is designed such that versioning between base and derived classes in different libraries can evolve and maintain backwards compatibility. This means, for example, that the introduction of a new member in a base class with the same name as a member in a derived class is not an error. It also means that a class must explicitly state whether a method is intended to override an inherited method, or whether a method is a new method that simply hides a similarly named inherited method.

In C#, methods are by default, not virtual. To make a method virtual, the virtual modifier has to be used in the method declaration of the base class. The derived class can then override the base virtual method by using the override keyword or hide the virtual method in the base class by using the new keyword. If neither the override keyword nor the new keyword is specified, the compiler will issue a warning and the method in the derived class will hide the method in the base class. The following example shows these concepts in action.

Example

// versioning.cs
// CS0114 expected
public class MyBase
{
public virtual string Meth1()
{
return "MyBase-Meth1";
}
public virtual string Meth2()
{
return "MyBase-Meth2";
}
public virtual string Meth3()
{
return "MyBase-Meth3";
}
}

class MyDerived : MyBase
{
// Overrides the virtual method Meth1 using the override keyword:
public override string Meth1()
{
return "MyDerived-Meth1";
}
// Explicitly hide the virtual method Meth2 using the new
// keyword:
public new string Meth2()
{
return "MyDerived-Meth2";
}
// Because no keyword is specified in the following declaration
// a warning will be issued to alert the programmer that
// the method hides the inherited member MyBase.Meth3():
public string Meth3()
{
return "MyDerived-Meth3";
}

public static void Main()
{
MyDerived mD = new MyDerived();
MyBase mB = (MyBase) mD;

System.Console.WriteLine(mB.Meth1());
System.Console.WriteLine(mB.Meth2());
System.Console.WriteLine(mB.Meth3());
}
}

Output

MyDerived-Meth1
MyBase-Meth2
MyBase-Meth3

Code Discussion

Hiding a base class member from a derived class isn't an error in C#. This feature enables you to make changes in the base class without breaking other libraries that inherit this base class. For example, at some point you could have the following classes:

class Base {}
class Derived: Base
{
public void F() {}
}

At some later point, the base class could evolve to add a void method F() as follows:

class Base
{
public void F() {}
}
class Derived: Base
{
public void F() {}
}

Thus, in C#, both the base and derived classes can evolve freely and maintain binary compatibility.

0 comments  

Libraries Tutorial

This tutorial shows how to create and use libraries in C#.

This tutorial demonstrates how to create a managed DLL file by using the necessary compiler options, and how to use the library by a client program.

Example

This example uses the following modules:

  • The DLL library (Functions.dll), which is built from the following source files:

    Factorial.cs: Calculates and returns the factorial of a number.

    DigitCounter.cs: Counts the number of digits in the passed string.

  • The client program (FunctionTest.exe), which uses the DLL, is compiled from the source file FunctionClient.cs. The program displays the factorial of the input arguments.

Building the Library

To build the library, make Functions the current directory and type the following at the command prompt:

csc /target:library /out:Functions.dll Factorial.cs DigitCounter.cs

where:

/target:library Specifies that the output is a DLL and not an executable file (this also stops the compiler from looking for a default entry point).
/out:Functions.dll Specifies that the output file name is Functions.dll. Normally the output name is the same name as the first C# source file on the command line (in this example, Factorial).
Factorial.cs DigitCounter.cs Specifies the files to compile and place in the DLL.

Compiling the Client

To compile the program, make FunctionTest the current directory and type the following at the command prompt:

copy ..\Functions\Functions.dll .
csc /out:FunctionTest.exe /R:Functions.DLL FunctionClient.cs

where:

/out:FunctionTest.exe Specifies that the output file name is FunctionTest.exe.
/R:Functions.DLL Specifies that Functions.DLL must be included when resolving references. This DLL must be located in the current directory or have a fully qualified path.
FunctionClient.cs Specifies the client source code.

This creates the executable file FunctionTest.exe.

File 1 - Factorial.cs

The following code calculates the factorial of the integer passed to the method

// Factorial.cs
// compile with: /target:library
using System;

// Declares a namespace. You need to package your libraries according
// to their namespace so the .NET runtime can correctly load the classes.
namespace Functions
{
public class Factorial
{
// The "Calc" static method calculates the factorial value for the
// specified integer passed in:
public static int Calc(int i)
{
return((i <= 1) ? 1 : (i * Calc(i-1))); } } }

File 2 - DigitCounter.cs

The following code is used to count the number of digit characters in the passed string:

// DigitCounter.cs
// compile with: /target:library /out:Functions.dll /reference:Factorial.dll
using System;

// Declare the same namespace as the one in Factorial.cs. This simply
// allows types to be added to the same namespace.
namespace Functions
{
public class DigitCount
{
// The NumberOfDigits static method calculates the number of
// digit characters in the passed string:
public static int NumberOfDigits(string theString)
{
int count = 0;
for ( int i = 0; i <>

File 3 - FunctionClient.cs

Once you build a library, it can be used by other programs. The following client program uses the classes defined in the library. The basic function of the program is to take each command-line parameter and attempt to compute the factorial value for each argument.

// FunctionClient.cs
// compile with: /reference:Functions.dll,Factorial.dll /out:FunctionTest.exe
// arguments: 3 5 10
using System;
// The following using directive makes the types defined in the Functions
// namespace available in this compilation unit:
using Functions;
class FunctionClient
{
public static void Main(string[] args)
{
Console.WriteLine("Function Client");

if ( args.Length == 0 )
{
Console.WriteLine("Usage: FunctionTest ... ");
return;
}

for ( int i = 0; i < num =" Int32.Parse(args[i]);">

Output

The command line FunctionTest 3 5 10 uses the program FunctionTest to calculate the factorial of the three integers 3, 5, and 10. It also displays the number of digits for each argument.

This run gives the output:

Function Client
The Digit Count for String [3] is [1]
The Factorial for [3] is [6]
The Digit Count for String [5] is [1]
The Factorial for [5] is [120]
The Digit Count for String [10] is [2]
The Factorial for [10] is [3628800]

0 comments  

Properties Tutorial

This tutorial shows how properties are an integral part of the C# programming language. It demonstrates how properties are declared and used.

This tutorial includes two examples. The first example shows how to declare and use read/write properties. The second example demonstrates abstract properties and shows how to override these properties in subclasses.

Example 1

This sample shows a Person class that has two properties: Name (string) and Age (int). Both properties are read/write.

// person.cs
using System;
class Person
{
private string myName ="N/A";
private int myAge = 0;

// Declare a Name property of type string:
public string Name
{
get
{
return myName;
}
set
{
myName = value;
}
}

// Declare an Age property of type int:
public int Age
{
get
{
return myAge;
}
set
{
myAge = value;
}
}

public override string ToString()
{
return "Name = " + Name + ", Age = " + Age;
}

public static void Main()
{
Console.WriteLine("Simple Properties");

// Create a new Person object:
Person person = new Person();

// Print out the name and the age associated with the person:
Console.WriteLine("Person details - {0}", person);

// Set some values on the person object:
person.Name = "Joe";
person.Age = 99;
Console.WriteLine("Person details - {0}", person);

// Increment the Age property:
person.Age += 1;
Console.WriteLine("Person details - {0}", person);
}
}

Output

Simple Properties
Person details - Name = N/A, Age = 0
Person details - Name = Joe, Age = 99
Person details - Name = Joe, Age = 100

Code Discussion

  • Notice the way that the properties are declared, for example, consider the Name property:
    public string Name
    {
    get
    {
    return myName;
    }
    set
    {
    myName = value;
    }
    }

    The Set and Get methods of a property are contained inside the property declaration. You can control whether a property is read/write, read-only, or write-only by controlling whether a Get or Set method is included.

  • Once the properties are declared, they can be used as if they were fields of the class. This allows for a very natural syntax when both getting and setting the value of a property, as in the following statements:
    person.Name = "Joe";
    person.Age = 99;
  • Note that in a property Set method a special value variable is available. This variable contains the value that the user specified, for example:
    myName = value; 
  • Notice the clean syntax for incrementing the Age property on a Person object:
    person.Age += 1;

    If separate Set and Get methods were used to model properties, the equivalent code might look like this:

    person.SetAge(person.GetAge() + 1);
  • The ToString method is overridden in this example:
    public override string ToString()
    {
    return "Name = " + Name + ", Age = " + Age;
    }

    Notice that ToString is not explicitly used in the program. It is invoked by default by the WriteLine calls.

Example 2

The following example shows how to define abstract properties. An abstract property declaration does not provide an implementation of the property accessors. The example demonstrates how to override these properties in subclasses.

This sample consists of three files. In the Properties Sample, these files are compiled into a single compilation but in this tutorial, each file is compiled individually and its resulting assembly referenced by the next compilation:

  • abstractshape.cs: The Shape class that contains an abstract Area property.
  • shapes.cs: The subclasses of the Shape class.
  • shapetest.cs: A test program to display the areas of some Shape-derived objects.

To compile the example, use the command line:

csc abstractshape.cs shapes.cs shapetest.cs

This will create the executable file shapetest.exe.

File 1 - abstractshape.cs

This file declares the Shape class that contains the Area property of the type double

// abstractshape.cs
// compile with: /target:library
// csc /target:library abstractshape.cs
using System;

public abstract class Shape
{
private string myId;

public Shape(string s)
{
Id = s; // calling the set accessor of the Id property
}

public string Id
{
get
{
return myId;
}

set
{
myId = value;
}
}

// Area is a read-only property - only a get accessor is needed:
public abstract double Area
{
get;
}

public override string ToString()
{
return Id + " Area = " + string.Format("{0:F2}",Area);
}
}

Code Discussion

  • Modifiers on the property are placed on the property declaration itself, for example:
    public abstract double Area
  • When declaring an abstract property (such as Area in this example), you simply indicate what property accessors are available, but do not implement them. In this example, only a Get accessor is available, so the property is read-only.

File 2 - shapes.cs

The following code shows three subclasses of Shape and how they override the Area property to provide their own implementation.

// shapes.cs
// compile with: /target:library /reference:abstractshape.dll
public class Square : Shape
{
private int mySide;

public Square(int side, string id) : base(id)
{
mySide = side;
}

public override double Area
{
get
{
// Given the side, return the area of a square:
return mySide * mySide;
}
}
}

public class Circle : Shape
{
private int myRadius;

public Circle(int radius, string id) : base(id)
{
myRadius = radius;
}

public override double Area
{
get
{
// Given the radius, return the area of a circle:
return myRadius * myRadius * System.Math.PI;
}
}
}

public class Rectangle : Shape
{
private int myWidth;
private int myHeight;

public Rectangle(int width, int height, string id) : base(id)
{
myWidth = width;
myHeight = height;
}

public override double Area
{
get
{
// Given the width and height, return the area of a rectangle:
return myWidth * myHeight;
}
}
}

File 3 - shapetest.cs

The following code shows a test program that creates a number of Shape-derived objects and prints out their areas.

// shapetest.cs
// compile with: /reference:abstractshape.dll;shapes.dll
public class TestClass
{
public static void Main()
{
Shape[] shapes =
{
new Square(5, "Square #1"),
new Circle(3, "Circle #1"),
new Rectangle( 4, 5, "Rectangle #1")
};

System.Console.WriteLine("Shapes Collection");
foreach(Shape s in shapes)
{
System.Console.WriteLine(s);
}

}
}

Output

Shapes Collection
Square #1 Area = 25.00
Circle #1 Area = 28.27
Rectangle #1 Area = 20.00

0 comments  

Arrays

This tutorial is divided into the following sections:

  • Arrays in General
  • Declaring Arrays
  • Initializing Arrays
  • Accessing Array Members
  • Arrays are Objects
  • Using foreach with Arrays

Arrays in General

C# arrays are zero indexed; that is, the array indexes start at zero. Arrays in C# work similarly to how arrays work in most other popular languages There are, however, a few differences that you should be aware of.

When declaring an array, the square brackets ([]) must come after the type, not the identifier. Placing the brackets after the identifier is not legal syntax in C#.

int[] table; // not int table[];  

Another detail is that the size of the array is not part of its type as it is in the C language. This allows you to declare an array and assign any array of int objects to it, regardless of the array's length.

int[] numbers; // declare numbers as an int array of any size
numbers = new int[10]; // numbers is a 10-element array
numbers = new int[20]; // now it's a 20-element array

Declaring Arrays

C# supports single-dimensional arrays, multidimensional arrays (rectangular arrays), and array-of-arrays (jagged arrays). The following examples show how to declare different kinds of arrays:

Single-dimensional arrays:

int[] numbers;

Multidimensional arrays:

string[,] names;

Array-of-arrays (jagged):

byte[][] scores;

Declaring them (as shown above) does not actually create the arrays. In C#, arrays are objects (discussed later in this tutorial) and must be instantiated. The following examples show how to create arrays:

Single-dimensional arrays:

int[] numbers = new int[5];

Multidimensional arrays:

string[,] names = new string[5,4];

Array-of-arrays (jagged):

byte[][] scores = new byte[5][];
for (int x = 0; x <>

You can also have larger arrays. For example, you can have a three-dimensional rectangular array:

int[,,] buttons = new int[4,5,3];

You can even mix rectangular and jagged arrays. For example, the following code declares a single-dimensional array of three-dimensional arrays of two-dimensional arrays of type int:

int[][,,][,] numbers;

Example

The following is a complete C# program that declares and instantiates arrays as discussed above.

// arrays.cs
using System;
class DeclareArraysSample
{
public static void Main()
{
// Single-dimensional array
int[] numbers = new int[5];

// Multidimensional array
string[,] names = new string[5,4];

// Array-of-arrays (jagged array)
byte[][] scores = new byte[5][];

// Create the jagged array
for (int i = 0; i < i =" 0;">

Output

Length of row 0 is 3
Length of row 1 is 4
Length of row 2 is 5
Length of row 3 is 6
Length of row 4 is 7

Initializing Arrays

C# provides simple and straightforward ways to initialize arrays at declaration time by enclosing the initial values in curly braces ({}). The following examples show different ways to initialize different kinds of arrays.

Note If you do not initialize an array at the time of declaration, the array members are automatically initialized to the default initial value for the array type. Also, if you declare the array as a field of a type, it will be set to the default value null when you instantiate the type.

Single-Dimensional Array

int[] numbers = new int[5] {1, 2, 3, 4, 5};
string[] names = new string[3] {"Matt", "Joanne", "Robert"};

You can omit the size of the array, like this:

int[] numbers = new int[] {1, 2, 3, 4, 5};
string[] names = new string[] {"Matt", "Joanne", "Robert"};

You can also omit the new operator if an initializer is provided, like this:

int[] numbers = {1, 2, 3, 4, 5};
string[] names = {"Matt", "Joanne", "Robert"};

Multidimensional Array

int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert"} };

You can omit the size of the array, like this:

int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = new string[,] { {"Mike","Amy"}, {"Mary","Albert"} };

You can also omit the new operator if an initializer is provided, like this:

int[,] numbers = { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = { {"Mike", "Amy"}, {"Mary", "Albert"} };

Jagged Array (Array-of-Arrays)

You can initialize jagged arrays like this example:

int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

You can also omit the size of the first array, like this:

int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

-or-

int[][] numbers = { new int[] {2,3,4}, new int[] {5,6,7,8,9} };

Notice that there is no initialization syntax for the elements of a jagged array.

Accessing Array Members

Accessing array members is straightforward and similar to how you access array members in C/C++. For example, the following code creates an array called numbers and then assigns a 5 to the fifth element of the array:

int[] numbers = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
numbers[4] = 5;

The following code declares a multidimensional array and assigns 5 to the member located at [1, 1]:

int[,] numbers = { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} };
numbers[1, 1] = 5;

The following is a declaration of a single-dimension jagged array that contains two elements. The first element is an array of two integers, and the second is an array of three integers:

int[][] numbers = new int[][] { new int[] {1, 2}, new int[] {3, 4, 5}
};

The following statements assign 58 to the first element of the first array and 667 to the second element of the second array:

numbers[0][0] = 58;
numbers[1][1] = 667;

Arrays are Objects

In C#, arrays are actually objects. System.Array is the abstract base type of all array types. You can use the properties, and other class members, that System.Array has. An example of this would be using the Length property to get the length of an array. The following code assigns the length of the numbers array, which is 5, to a variable called LengthOfNumbers:

int[] numbers = {1, 2, 3, 4, 5};
int LengthOfNumbers = numbers.Length;

The System.Array class provides many other useful methods/properties, such as methods for sorting, searching, and copying arrays.

Using foreach on Arrays

C# also provides the foreach statement. This statement provides a simple, clean way to iterate through the elements of an array. For example, the following code creates an array called numbers and iterates through it with the foreach statement:

int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0};
foreach (int i in numbers)
{
System.Console.WriteLine(i);
}

With multidimensional arrays, you can use the same method to iterate through the elements, for example:

int[,] numbers = new int[3, 2] {{9, 99}, {3, 33}, {5, 55}};
foreach(int i in numbers)
{
Console.Write("{0} ", i);
}

The output of this example is:

9 99 3 33 5 55

However, with multidimensional arrays, using a nested for loop gives you more control over the array elements.

0 comments  

Command Line Parameters

The following examples show two different approaches to using the command line arguments passed to an application.

Example 1

This example demonstrates how to print out the command line arguments.

// cmdline1.cs
// arguments: A B C
using System;

public class CommandLine
{
public static void Main(string[] args)
{
// The Length property is used to obtain the length of the array.
// Notice that Length is a read-only property:
Console.WriteLine("Number of command line parameters = {0}",
args.Length);
for(int i = 0; i <>

Output

Run the program using some arguments like this: cmdline1 A B C.

The output will be:

Number of command line parameters = 3
Arg[0] = [A]
Arg[1] = [B]
Arg[2] = [C]

Example 2

Another approach to iterating over the array is to use the foreach statement as shown in this example. The foreach statement can be used to iterate over an array or over a .NET Framework collection class. It provides a simple way to iterate over collections.

// cmdline2.cs
// arguments: John Paul Mary
using System;

public class CommandLine2
{
public static void Main(string[] args)
{
Console.WriteLine("Number of command line parameters = {0}",
args.Length);
foreach(string s in args)
{
Console.WriteLine(s);
}
}
}

Output

Run the program using some arguments like this: cmdline2 John Paul Mary.

The output will be:

Number of command line parameters = 3
John
Paul
Mary

0 comments  

Hello World C#

The following examples show different ways of writing the C# Hello World program.

Example 1

// Hello1.cs
public class Hello1
{
public static void Main()
{
System.Console.WriteLine("Hello, World!");
}
}

Output

Hello, World!

Code Discussion

  • Every Main method must be contained inside a class (Hello1 in this case).
  • The System.Console class contains a WriteLine method that can be used to display a string to the console.

Example 2

To avoid fully qualifying classes throughout a program, you can use the using directive as shown below:

// Hello2.cs
using System;

public class Hello2
{
public static void Main()
{
Console.WriteLine("Hello, World!");
}
}

Output

Hello, World!

Example 3

If you need access to the command line parameters passed in to your application, simply change the signature of the Main method to include them as shown below. This example counts and displays the command line arguments.

// Hello3.cs
// arguments: A B C D
using System;

public class Hello3
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Console.WriteLine("You entered the following {0} command line arguments:",
args.Length );
for (int i=0; i <>

Output

Hello, World!
You entered the following 4 command line arguments:
A
B
C
D

Example 4

To return a return code, change the signature of the Main method as shown below:

// Hello4.cs
using System;

public class Hello4
{
public static int Main(string[] args)
{
Console.WriteLine("Hello, World!");
return 0;
}
}

Output

Hello, World!

0 comments