PROWAREtech

articles » current » dot-net » tutorial » c-sharp » page-7

.NET C# Tutorial - A Beginner's Guide - Page 7

Arrays, Interfaces, Structures, Enumerations, Namespaces, internal Classes, Exception Handling.

Arrays

Working with arrays is simple.

using System;
using System.Collections.Generic;

// creating arrays
string[] string_array = {"0","1","2","3"};
string[] string_array_2 = new string[4];
string[] string_array_3 = new string[4] {"0","1","2","3"};

// creating array from a List<>
List<string> list = new List<string>();
string[] array_from_list = list.ToArray();

// creating array from a comma separated values string
string values = "1,2,3,4,5,6,7,8,9";
string[] array_from_string = values.Split(',');
values = string.Join(',', array_from_string); // join the array to a CSV string

//find a value in an array
int index = Array.IndexOf(array_from_string, "7"); // index == -1 then value not found, otherwise index 0 to array_from_string.Length - 1 is returned

Interfaces

An interface does not implement any methods. It is a logical construct describing a set of methods. Interfaces are similar to abstract classes. An interface should be declared public so that it can be implemented by any class in any program. It can not define constructors, destructors, or operator methods (operator overloading is not covered by this guide). It can not have static members, either. All of its method signatures are public by default and interfaces can inherit interfaces.

Example Program Code

using System;

namespace ConsoleApplication1
{
	public interface I
	{
		string Name();
	}

	class C : I
	{
		public string Name()
		{
			return "My name is C";
		}
	}

	class Program
	{
		static void Main(string[] args)
		{
			C c = new C();

			I i = c;

			Console.WriteLine(i.Name());
		}
	}
}

Structures

In C#, structures are a lot like classes and infact in C++ structures and classes are almost identical. Structures can not be inherited and cannot inherit other structures or classes. Use the struct keyword. Structures do not need to be created with the new operator.

struct Rectangle
{
	private int width, height;

	public int Area()
	{
		return width * height;
	}

	public Rectangle(int w, int h)
	{
		width = w;
		height = h;
	}
}

Enumerations

An enumeration is a set of named integer constants specifying the legal values a variable of that type may have. The keyword enum declares an enumerated type.

enum colors
{
	red, blue, green, navy, maroon
}

Initialize one or all of the symbols.

enum colors
{
	red = 10,
	blue = 12,
	green = 19,
	navy = 25,
	maroon = 50
}

By default, enumerations are based on int but this can be specified.

enum colors : ushort
{
	red, blue, green, navy, maroon
}

Example Program Code

using System;

namespace ConsoleApplication1
{
	enum colors
	{
		red, blue, green, navy, maroon
	}

	class Program
	{
		static void Main(string[] args)
		{
			colors c = colors.blue;
			Console.WriteLine(c);
		}
	}
}

Or a slightly more complex example using LINQ and string.Format.

using System;
using System.Linq;

namespace ConsoleApplication1
{
	public enum colors
	{
		red = 0xFF0000,
		blue = 0x0000FF,
		green = 0x009900,
		navy = 0x000040,
		white = 0xFFFFFF,
		black = 0x000000
	}

	class Program
	{
		static void Main(string[] args)
		{
			string[] a = Enum.GetValues(typeof(colors)).Cast<int>().Select(i =>
			{
				return string.Format("{0}={1:X6}", (colors)i, i);
			}).ToArray();
			foreach(string s in a)
			{
				Console.WriteLine(s);
			}
		}
	}
}

Namespaces

A namespace declares a region that keeps one set of names seperate from another. Use the using directive to use the members of a namespace in code without having to specify the namespace each time.

This code probably looks familiar by now:

using System;

namespace ConsoleApplication1
{
	class Program
	{
		static void Main(string[] args)
		{
			Console.WriteLine("HELLO!");
		}
	}
}

This is the same code without using the using directive.

namespace ConsoleApplication1
{
	class Program
	{
		static void Main(string[] args)
		{
			// must specify the System namespace!
			System.Console.WriteLine("HELLO!");
		}
	}
}

internal Classes

The internal access specifier is used to prevent classes outside the assembly from using the class.

// InternalExample.cs
namespace InternalExample
{
	internal class InternalClass
	{
		// class members go here
	}
}

Exception Handling

If an exception (or error) occurs inside a try block then the exception is thrown out of the try block and caught by the catch statement. Control passes to the catch block and the try block terminates.

Example Program Code

using System;
using System.IO;

namespace ConsoleApplication1
{
	class Program
	{
		static void Main(string[] args)
		{
			try
			{
				string choice;

				Console.Write("Do you want a file open exception? (Y/N): ");
				choice = Console.ReadLine().ToUpper();
				if (choice == "Y")
				{
					FileStream fs = new FileStream("ThisIsADud.tmp", FileMode.Open);
				}

				Console.Write("Do you want an out-of-bounds exception? (Y/N): ");
				choice = Console.ReadLine().ToUpper();
				if (choice == "Y")
				{
					int[] i = new int[2];
					i[2] = 0;
				}

				Console.Write("Do you want a division-by-zero exception? (Y/N): ");
				choice = Console.ReadLine().ToUpper();
				if (choice == "Y")
				{
					int i = 0;
					i = 1 / i;
				}

				Console.Write("Do you want a custom exception? (Y/N): ");
				choice = Console.ReadLine().ToUpper();
				if (choice == "Y")
				{
					throw new Exception("THIS IS THE EXCEPTION MESSAGE");
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
		}
	}
}
<<<[Page 7 of 7]>>>

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE