C# – Environment ”; Previous Next In this chapter, we will discuss the tools required for creating C# programming. We have already mentioned that C# is part of .Net framework and is used for writing .Net applications. Therefore, before discussing the available tools for running a C# program, let us understand how C# relates to the .Net framework. The .Net Framework The .Net framework is a revolutionary platform that helps you to write the following types of applications − Windows applications Web applications Web services The .Net framework applications are multi-platform applications. The framework has been designed in such a way that it can be used from any of the following languages: C#, C++, Visual Basic, Jscript, COBOL, etc. All these languages can access the framework as well as communicate with each other. The .Net framework consists of an enormous library of codes used by the client languages such as C#. Following are some of the components of the .Net framework − Common Language Runtime (CLR) The .Net Framework Class Library Common Language Specification Common Type System Metadata and Assemblies Windows Forms ASP.Net and ASP.Net AJAX ADO.Net Windows Workflow Foundation (WF) Windows Presentation Foundation Windows Communication Foundation (WCF) LINQ For the jobs each of these components perform, please see ASP.Net – Introduction, and for details of each component, please consult Microsoft”s documentation. Integrated Development Environment (IDE) for C# Microsoft provides the following development tools for C# programming − Visual Studio 2010 (VS) Visual C# 2010 Express (VCE) Visual Web Developer The last two are freely available from Microsoft official website. Using these tools, you can write all kinds of C# programs from simple command-line applications to more complex applications. You can also write C# source code files using a basic text editor, like Notepad, and compile the code into assemblies using the command-line compiler, which is again a part of the .NET Framework. Visual C# Express and Visual Web Developer Express edition are trimmed down versions of Visual Studio and has the same appearance. They retain most features of Visual Studio. In this tutorial, we have used Visual C# 2010 Express. You can download it from Microsoft Visual Studio. It gets installed automatically on your machine. Note: You need an active internet connection for installing the express edition. Writing C# Programs on Linux or Mac OS Although the.NET Framework runs on the Windows operating system, there are some alternative versions that work on other operating systems. Mono is an open-source version of the .NET Framework which includes a C# compiler and runs on several operating systems, including various flavors of Linux and Mac OS. Kindly check Go Mono. The stated purpose of Mono is not only to be able to run Microsoft .NET applications cross-platform, but also to bring better development tools for Linux developers. Mono can be run on many operating systems including Android, BSD, iOS, Linux, OS X, Windows, Solaris, and UNIX. Print Page Previous Next Advertisements ”;
Category: csharp
C# – Constants
C# – Constants and Literals ”; Previous Next The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well. The constants are treated just like regular variables except that their values cannot be modified after their definition. Integer Literals An integer literal can be a decimal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, and there is no prefix id for decimal. An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order. Here are some examples of integer literals − 212 /* Legal */ 215u /* Legal */ 0xFeeL /* Legal */ Following are other examples of various types of Integer literals − 85 /* decimal */ 0x4b /* hexadecimal */ 30 /* int */ 30u /* unsigned int */ 30l /* long */ 30ul /* unsigned long */ Floating-point Literals A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. Here are some examples of floating-point literals − 3.14159 /* Legal */ 314159E-5F /* Legal */ 510E /* Illegal: incomplete exponent */ 210f /* Illegal: no decimal or exponent */ .e55 /* Illegal: missing integer or fraction */ While representing in decimal form, you must include the decimal point, the exponent, or both; and while representing using exponential form you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E. Character Constants Character literals are enclosed in single quotes. For example, ”x” and can be stored in a simple variable of char type. A character literal can be a plain character (such as ”x”), an escape sequence (such as ”t”), or a universal character (such as ”u02C0”). There are certain characters in C# when they are preceded by a backslash. They have special meaning and they are used to represent like newline (n) or tab (t). Here, is a list of some of such escape sequence codes − Escape sequence Meaning \ character ” ” character “ ” character ? ? character a Alert or bell b Backspace f Form feed n Newline r Carriage return t Horizontal tab v Vertical tab xhh . . . Hexadecimal number of one or more digits Following is the example to show few escape sequence characters − Live Demo using System; namespace EscapeChar { class Program { static void Main(string[] args) { Console.WriteLine(“HellotWorldnn”); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − Hello World String Literals String literals or constants are enclosed in double quotes “” or with @””. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. You can break a long line into multiple lines using string literals and separating the parts using whitespaces. Here are some examples of string literals. All the three forms are identical strings. “hello, dear” “hello, dear” “hello, ” “d” “ear” @”hello dear” Defining Constants Constants are defined using the const keyword. Syntax for defining a constant is − const <data_type> <constant_name> = value; The following program demonstrates defining and using a constant in your program − Live Demo using System; namespace DeclaringConstants { class Program { static void Main(string[] args) { const double pi = 3.14159; // constant declaration double r; Console.WriteLine(“Enter Radius: “); r = Convert.ToDouble(Console.ReadLine()); double areaCircle = pi * r * r; Console.WriteLine(“Radius: {0}, Area: {1}”, r, areaCircle); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − Enter Radius: 3 Radius: 3, Area: 28.27431 Print Page Previous Next Advertisements ”;
C# – Regular Expressions
C# – Regular Expressions ”; Previous Next A regular expression is a pattern that could be matched against an input text. The .Net framework provides a regular expression engine that allows such matching. A pattern consists of one or more character literals, operators, or constructs. Constructs for Defining Regular Expressions There are various categories of characters, operators, and constructs that lets you to define regular expressions. Click the following links to find these constructs. Character escapes Character classes Anchors Grouping constructs Quantifiers Backreference constructs Alternation constructs Substitutions Miscellaneous constructs The Regex Class The Regex class is used for representing a regular expression. It has the following commonly used methods − Sr.No. Methods & Description 1 public bool IsMatch(string input) Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string. 2 public bool IsMatch(string input, int startat) Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string. 3 public static bool IsMatch(string input, string pattern) Indicates whether the specified regular expression finds a match in the specified input string. 4 public MatchCollection Matches(string input) Searches the specified input string for all occurrences of a regular expression. 5 public string Replace(string input, string replacement) In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string. 6 public string[] Split(string input) Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor. For the complete list of methods and properties, please read the Microsoft documentation on C#. Example 1 The following example matches words that start with ”S” − Live Demo using System; using System.Text.RegularExpressions; namespace RegExApplication { class Program { private static void showMatch(string text, string expr) { Console.WriteLine(“The Expression: ” + expr); MatchCollection mc = Regex.Matches(text, expr); foreach (Match m in mc) { Console.WriteLine(m); } } static void Main(string[] args) { string str = “A Thousand Splendid Suns”; Console.WriteLine(“Matching words that start with ”S”: “); showMatch(str, @”bSS*”); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Matching words that start with ”S”: The Expression: bSS* Splendid Suns Example 2 The following example matches words that start with ”m” and ends with ”e” − Live Demo using System; using System.Text.RegularExpressions; namespace RegExApplication { class Program { private static void showMatch(string text, string expr) { Console.WriteLine(“The Expression: ” + expr); MatchCollection mc = Regex.Matches(text, expr); foreach (Match m in mc) { Console.WriteLine(m); } } static void Main(string[] args) { string str = “make maze and manage to measure it”; Console.WriteLine(“Matching words start with ”m” and ends with ”e”:”); showMatch(str, @”bmS*eb”); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Matching words start with ”m” and ends with ”e”: The Expression: bmS*eb make maze manage measure Example 3 This example replaces extra white space − Live Demo using System; using System.Text.RegularExpressions; namespace RegExApplication { class Program { static void Main(string[] args) { string input = “Hello World “; string pattern = “\s+”; string replacement = ” “; Regex rgx = new Regex(pattern); string result = rgx.Replace(input, replacement); Console.WriteLine(“Original String: {0}”, input); Console.WriteLine(“Replacement String: {0}”, result); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Original String: Hello World Replacement String: Hello World Print Page Previous Next Advertisements ”;
C# – Collections
C# – Collections ”; Previous Next Collection classes are specialized classes for data storage and retrieval. These classes provide support for stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces. Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index etc. These classes create collections of objects of the Object class, which is the base class for all data types in C#. Various Collection Classes and Their Usage The following are the various commonly used classes of the System.Collection namespace. Click the following links to check their detail. Sr.No. Class & Description and Useage 1 ArrayList It represents ordered collection of an object that can be indexed individually. It is basically an alternative to an array. However, unlike array you can add and remove items from a list at a specified position using an index and the array resizes itself automatically. It also allows dynamic memory allocation, adding, searching and sorting items in the list. 2 Hashtable It uses a key to access the elements in the collection. A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection. 3 SortedList It uses a key as well as an index to access the items in a list. A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key , it is a Hashtable. The collection of items is always sorted by the key value. 4 Stack It represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. 5 Queue It represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue and when you remove an item, it is called deque. 6 BitArray It represents an array of the binary representation using the values 1 and 0. It is used when you need to store the bits but do not know the number of bits in advance. You can access items from the BitArray collection by using an integer index, which starts from zero. Print Page Previous Next Advertisements ”;
C# – Classes
C# – Classes ”; Previous Next When you define a class, you define a blueprint for a data type. This does not actually define any data, but it does define what the class name means. That is, what an object of the class consists of and what operations can be performed on that object. Objects are instances of a class. The methods and variables that constitute a class are called members of the class. Defining a Class A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces. Following is the general form of a class definition − <access specifier> class class_name { // member variables <access specifier> <data type> variable1; <access specifier> <data type> variable2; … <access specifier> <data type> variableN; // member methods <access specifier> <return type> method1(parameter_list) { // method body } <access specifier> <return type> method2(parameter_list) { // method body } … <access specifier> <return type> methodN(parameter_list) { // method body } } Note − Access specifiers specify the access rules for the members as well as the class itself. If not mentioned, then the default access specifier for a class type is internal. Default access for the members is private. Data type specifies the type of variable, and return type specifies the data type of the data the method returns, if any. To access the class members, you use the dot (.) operator. The dot operator links the name of an object with the name of a member. The following example illustrates the concepts discussed so far − Live Demo using System; namespace BoxApplication { class Box { public double length; // Length of a box public double breadth; // Breadth of a box public double height; // Height of a box } class Boxtester { static void Main(string[] args) { Box Box1 = new Box(); // Declare Box1 of type Box Box Box2 = new Box(); // Declare Box2 of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.height = 5.0; Box1.length = 6.0; Box1.breadth = 7.0; // box 2 specification Box2.height = 10.0; Box2.length = 12.0; Box2.breadth = 13.0; // volume of box 1 volume = Box1.height * Box1.length * Box1.breadth; Console.WriteLine(“Volume of Box1 : {0}”, volume); // volume of box 2 volume = Box2.height * Box2.length * Box2.breadth; Console.WriteLine(“Volume of Box2 : {0}”, volume); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Volume of Box1 : 210 Volume of Box2 : 1560 Member Functions and Encapsulation A member function of a class is a function that has its definition or its prototype within the class definition similar to any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object. Member variables are the attributes of an object (from design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions. Let us put above concepts to set and get the value of different class members in a class − Live Demo using System; namespace BoxApplication { class Box { private double length; // Length of a box private double breadth; // Breadth of a box private double height; // Height of a box public void setLength( double len ) { length = len; } public void setBreadth( double bre ) { breadth = bre; } public void setHeight( double hei ) { height = hei; } public double getVolume() { return length * breadth * height; } } class Boxtester { static void Main(string[] args) { Box Box1 = new Box(); // Declare Box1 of type Box Box Box2 = new Box(); double volume; // Declare Box2 of type Box // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // volume of box 1 volume = Box1.getVolume(); Console.WriteLine(“Volume of Box1 : {0}” ,volume); // volume of box 2 volume = Box2.getVolume(); Console.WriteLine(“Volume of Box2 : {0}”, volume); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Volume of Box1 : 210 Volume of Box2 : 1560 C# Constructors A class constructor is a special member function of a class that is executed whenever we create new objects of that class. A constructor has exactly the same name as that of class and it does not have any return type. Following example explains the concept of constructor − Live Demo using System; namespace LineApplication { class Line { private double length; // Length of a line public Line() { Console.WriteLine(“Object is being created”); } public void setLength( double len ) { length = len; } public double getLength() { return length; } static void Main(string[] args) { Line line = new Line(); // set line length line.setLength(6.0); Console.WriteLine(“Length of line : {0}”, line.getLength()); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Object is being created Length of line : 6 A default constructor does not have any parameter but if you need, a constructor can have parameters. Such constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the time of its creation as shown in the following example − Live Demo using System; namespace LineApplication { class Line { private double length; // Length of a line public Line(double len) { //Parameterized constructor Console.WriteLine(“Object is being created, length = {0}”, len); length = len; } public void setLength( double len ) { length = len; } public double getLength() { return length; } static void Main(string[] args) { Line line = new Line(10.0); Console.WriteLine(“Length of line : {0}”, line.getLength()); // set line length line.setLength(6.0); Console.WriteLine(“Length of line : {0}”, line.getLength()); Console.ReadKey(); } } } When the
C# – Namespaces
C# – Namespaces ”; Previous Next A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another. Defining a Namespace A namespace definition begins with the keyword namespace followed by the namespace name as follows − namespace namespace_name { // code declarations } To call the namespace-enabled version of either function or variable, prepend the namespace name as follows − namespace_name.item_name; The following program demonstrates use of namespaces − Live Demo using System; namespace first_space { class namespace_cl { public void func() { Console.WriteLine(“Inside first_space”); } } } namespace second_space { class namespace_cl { public void func() { Console.WriteLine(“Inside second_space”); } } } class TestClass { static void Main(string[] args) { first_space.namespace_cl fc = new first_space.namespace_cl(); second_space.namespace_cl sc = new second_space.namespace_cl(); fc.func(); sc.func(); Console.ReadKey(); } } When the above code is compiled and executed, it produces the following result − Inside first_space Inside second_space The using Keyword The using keyword states that the program is using the names in the given namespace. For example, we are using the System namespace in our programs. The class Console is defined there. We just write − Console.WriteLine (“Hello there”); We could have written the fully qualified name as − System.Console.WriteLine(“Hello there”); You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. The namespace is thus implied for the following code − Let us rewrite our preceding example, with using directive − Live Demo using System; using first_space; using second_space; namespace first_space { class abc { public void func() { Console.WriteLine(“Inside first_space”); } } } namespace second_space { class efg { public void func() { Console.WriteLine(“Inside second_space”); } } } class TestClass { static void Main(string[] args) { abc fc = new abc(); efg sc = new efg(); fc.func(); sc.func(); Console.ReadKey(); } } When the above code is compiled and executed, it produces the following result − Inside first_space Inside second_space Nested Namespaces You can define one namespace inside another namespace as follows − namespace namespace_name1 { // code declarations namespace namespace_name2 { // code declarations } } You can access members of nested namespace by using the dot (.) operator as follows − Live Demo using System; using first_space; using first_space.second_space; namespace first_space { class abc { public void func() { Console.WriteLine(“Inside first_space”); } } namespace second_space { class efg { public void func() { Console.WriteLine(“Inside second_space”); } } } } class TestClass { static void Main(string[] args) { abc fc = new abc(); efg sc = new efg(); fc.func(); sc.func(); Console.ReadKey(); } } When the above code is compiled and executed, it produces the following result − Inside first_space Inside second_space Print Page Previous Next Advertisements ”;
C# – Loops
C# – Loops ”; Previous Next There may be a situation, when you need to execute a block of code several number of times. In general, the statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or a group of statements multiple times and following is the general from of a loop statement in most of the programming languages − C# provides following types of loop to handle looping requirements. Click the following links to check their detail. Sr.No. Loop Type & Description 1 while loop It repeats a statement or a group of statements while a given condition is true. It tests the condition before executing the loop body. 2 for loop It executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. 3 do…while loop It is similar to a while statement, except that it tests the condition at the end of the loop body 4 nested loops You can use one or more loop inside any another while, for or do..while loop. Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. C# provides the following control statements. Click the following links to check their details. Sr.No. Control Statement & Description 1 break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. 2 continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. Infinite Loop A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty. Example using System; namespace Loops { class Program { static void Main(string[] args) { for (; ; ) { Console.WriteLine(“Hey! I am Trapped”); } } } } When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but programmers more commonly use the for(;;) construct to signify an infinite loop. Print Page Previous Next Advertisements ”;
C# – Reflection
C# – Reflection ”; Previous Next Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System.Reflection namespace. The System.Reflection namespace contains classes that allow you to obtain information about the application and to dynamically add types, values, and objects to the application. Applications of Reflection Reflection has the following applications − It allows view attribute information at runtime. It allows examining various types in an assembly and instantiate these types. It allows late binding to methods and properties It allows creating new types at runtime and then performs some tasks using those types. Viewing Metadata We have mentioned in the preceding chapter that using reflection you can view the attribute information. The MemberInfo object of the System.Reflection class needs to be initialized for discovering the attributes associated with a class. To do this, you define an object of the target class, as − System.Reflection.MemberInfo info = typeof(MyClass); The following program demonstrates this − using System; [AttributeUsage(AttributeTargets.All)] public class HelpAttribute : System.Attribute { public readonly string Url; public string Topic // Topic is a named parameter { get { return topic; } set { topic = value; } } public HelpAttribute(string url) // url is a positional parameter { this.Url = url; } private string topic; } [HelpAttribute(“Information on the class MyClass”)] class MyClass { } namespace AttributeAppl { class Program { static void Main(string[] args) { System.Reflection.MemberInfo info = typeof(MyClass); object[] attributes = info.GetCustomAttributes(true); for (int i = 0; i < attributes.Length; i++) { System.Console.WriteLine(attributes[i]); } Console.ReadKey(); } } } When it is compiled and run, it displays the name of the custom attributes attached to the class MyClass − HelpAttribute Example In this example, we use the DeBugInfo attribute created in the previous chapter and use reflection to read metadata in the Rectangle class. Live Demo using System; using System.Reflection; namespace BugFixApplication { //a custom attribute BugFix to be assigned to a class and its members [AttributeUsage( AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] public class DeBugInfo : System.Attribute { private int bugNo; private string developer; private string lastReview; public string message; public DeBugInfo(int bg, string dev, string d) { this.bugNo = bg; this.developer = dev; this.lastReview = d; } public int BugNo { get { return bugNo; } } public string Developer { get { return developer; } } public string LastReview { get { return lastReview; } } public string Message { get { return message; } set { message = value; } } } [DeBugInfo(45, “Zara Ali”, “12/8/2012”, Message = “Return type mismatch”)] [DeBugInfo(49, “Nuha Ali”, “10/10/2012”, Message = “Unused variable”)] class Rectangle { //member variables protected double length; protected double width; public Rectangle(double l, double w) { length = l; width = w; } [DeBugInfo(55, “Zara Ali”, “19/10/2012”, Message = “Return type mismatch”)] public double GetArea() { return length * width; } [DeBugInfo(56, “Zara Ali”, “19/10/2012”)] public void Display() { Console.WriteLine(“Length: {0}”, length); Console.WriteLine(“Width: {0}”, width); Console.WriteLine(“Area: {0}”, GetArea()); } }//end class Rectangle class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(4.5, 7.5); r.Display(); Type type = typeof(Rectangle); //iterating through the attribtues of the Rectangle class foreach (Object attributes in type.GetCustomAttributes(false)) { DeBugInfo dbi = (DeBugInfo)attributes; if (null != dbi) { Console.WriteLine(“Bug no: {0}”, dbi.BugNo); Console.WriteLine(“Developer: {0}”, dbi.Developer); Console.WriteLine(“Last Reviewed: {0}”, dbi.LastReview); Console.WriteLine(“Remarks: {0}”, dbi.Message); } } //iterating through the method attribtues foreach (MethodInfo m in type.GetMethods()) { foreach (Attribute a in m.GetCustomAttributes(true)) { DeBugInfo dbi = (DeBugInfo)a; if (null != dbi) { Console.WriteLine(“Bug no: {0}, for Method: {1}”, dbi.BugNo, m.Name); Console.WriteLine(“Developer: {0}”, dbi.Developer); Console.WriteLine(“Last Reviewed: {0}”, dbi.LastReview); Console.WriteLine(“Remarks: {0}”, dbi.Message); } } } Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − Length: 4.5 Width: 7.5 Area: 33.75 Bug No: 49 Developer: Nuha Ali Last Reviewed: 10/10/2012 Remarks: Unused variable Bug No: 45 Developer: Zara Ali Last Reviewed: 12/8/2012 Remarks: Return type mismatch Bug No: 55, for Method: GetArea Developer: Zara Ali Last Reviewed: 19/10/2012 Remarks: Return type mismatch Bug No: 56, for Method: Display Developer: Zara Ali Last Reviewed: 19/10/2012 Remarks: Print Page Previous Next Advertisements ”;
C# – Arrays
C# – Arrays ”; Previous Next An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type stored at contiguous memory locations. Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Declaring Arrays To declare an array in C#, you can use the following syntax − datatype[] arrayName; where, datatype is used to specify the type of elements in the array. [ ] specifies the rank of the array. The rank specifies the size of the array. arrayName specifies the name of the array. For example, double[] balance; Initializing an Array Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array. Array is a reference type, so you need to use the new keyword to create an instance of the array. For example, double[] balance = new double[10]; Assigning Values to an Array You can assign values to individual array elements, by using the index number, like − double[] balance = new double[10]; balance[0] = 4500.0; You can assign values to the array at the time of declaration, as shown − double[] balance = { 2340.0, 4523.69, 3421.0}; You can also create and initialize an array, as shown − int [] marks = new int[5] { 99, 98, 92, 97, 95}; You may also omit the size of the array, as shown − int [] marks = new int[] { 99, 98, 92, 97, 95}; You can copy an array variable into another target array variable. In such case, both the target and source point to the same memory location − int [] marks = new int[] { 99, 98, 92, 97, 95}; int[] score = marks; When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. For example, for an int array all elements are initialized to 0. Accessing Array Elements An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example, double salary = balance[9]; The following example, demonstrates the above-mentioned concepts declaration, assignment, and accessing arrays − Live Demo using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n is an array of 10 integers */ int i,j; /* initialize elements of array n */ for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; } /* output each array element”s value */ for (j = 0; j < 10; j++ ) { Console.WriteLine(“Element[{0}] = {1}”, j, n[j]); } Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109 Using the foreach Loop In the previous example, we used a for loop for accessing each array element. You can also use a foreach statement to iterate through an array. Live Demo using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n is an array of 10 integers */ /* initialize elements of array n */ for ( int i = 0; i < 10; i++ ) { n[i] = i + 100; } /* output each array element”s value */ foreach (int j in n ) { int i = j-100; Console.WriteLine(“Element[{0}] = {1}”, i, j); } Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109 C# Arrays There are following few important concepts related to array which should be clear to a C# programmer − Sr.No. Concept & Description 1 Multi-dimensional arrays C# supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. 2 Jagged arrays C# supports multidimensional arrays, which are arrays of arrays. 3 Passing arrays to functions You can pass to the function a pointer to an array by specifying the array”s name without an index. 4 Param arrays This is used for passing unknown number of parameters to a function. 5 The Array Class Defined in System namespace, it is the base class to all arrays, and provides various properties and methods for working with arrays. Print Page Previous Next Advertisements ”;
C# – Useful Resources
C# – Useful Resources ”; Previous Next The following resources contain additional information on C#. Please use them to get more in-depth knowledge on this topic. Useful Video Courses C Language Online Training Best Seller 69 Lectures 6 hours Tutorialspoint More Detail C++ Development Complete Course 78 Lectures 5.5 hours Frahaan Hussain More Detail C # in Telugu 38 Lectures 6.5 hours Vijay Kumar Parvatha Reddy More Detail C# in Depth: A Comprehensive Course (Beginner-To-Advanced) 108 Lectures 8 hours TELCOMA Global More Detail C# Coding Basics Course – For Beginners 86 Lectures 6.5 hours Metla Sudha Sekhar More Detail Learn C++ Programming From Scratch in Tamil 56 Lectures 13 hours Programming Line More Detail Print Page Previous Next Advertisements ”;