Share via


A Component in Visual C#

Here is how our simple string component looks in Visual C#:

Listing 1. Component in Visual C# (CompCS.cs)

using System;

namespace CompCS {
   public class StringComponent {
      private string[] StringsSet;

      public StringComponent() {
         StringsSet = new string[] {
            "C# String 0",
            "C# String 1",
            "C# String 2",
            "C# String 3"
         };
      }

     public string GetString(int index) {
        if ((index < 0) || (index >= 
           StringsSet.Length)) {
           throw new IndexOutOfRangeException();
         }
         return StringsSet[index];
      }

      public int Count {
         get { return StringsSet.Length; }
      }
   }
}

As mentioned previously, you use the namespace statement to create a new namespace to encapsulate the classes that you will be creating:

namespace CompCS {

This namespace can be nested and split among multiple files. A single source-code file can also contain multiple namespaces that are not nested. A containing namespace is required, since all Visual C# code must be contained in a class.

public class StringComponent {

Instances of StringComponent will be created by the common language runtime and managed in the garbage collection heap. The class constructor — which executes each time a new instance of the class is created — has the same name as the class and does not have a return type.

public StringComponent() {

Since Visual C# uses only managed types, you do not have to do anything special when declaring variables, as you had to do in Managed Extensions for C++.

Here is the GetString method, which takes an integer and returns a string and is simple and equivalent for all three sample languages:

public string GetString(int index) {
   ...
   return StringsSet[index];
}

Note the throw statement in the GetString method:

throw new IndexOutOfRangeException();

This statement creates — and throws — a runtime-based exception-handling object of type IndexOutOfRangeException.

Finally, you create the read-only Length property:

public int Count {
   get { return StringsSet.Length; }
}

The compile process for a Visual C# component is only a little more complicated than that for a stand-alone program:

csc.exe /t:library /debug+ /out:..\bin\CompCS.dll CompCS.cs

As with the Managed Extensions for C++ component, you use the /out switch to put the compiled component in the ..\Bin subdirectory. Likewise, you need the /t(arget):library switch to create a DLL rather than an executable file with a .dll file name extension.

See Also

A Component in Visual Basic | Clients for the Simple Components | Summary of Development Tutorial | Appendix A: Tools for Exploring Namespaces