Owner: C# Rocks URL:http://csharprocks.blogspot.com/ Join Date: Mon, 18 Jun 2007 22:19:03 -0500 Rating:0 Site Description: This blog is dedicated to the latest C# 2005 programming language...If u like C, C++...C# or C Sharp is the next big thing for you... Site statistics:Click here
Enumerations 2007-06-21 01:54:00 What are enumerations?Enumerations are a set of named integer constants. C# offers an intuitive way of representing numbers in your code. This can be well understood if you want to use the days in a week, one way is to assign each day an integer number ranging from 1-7, but C# allows you to use enumerations. By enumerations you can represent each number by its corresponding day as in real life. For Monday the value 1, for Tuesday value 2 and so on.Declaring an enumeration:enum name { enumeration list}The enumeration list is a comma-separated list of identifiers.enum days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }Here, Monday, Tuesday… is assigned a value starting from the default value 0.Initialize an enumeration:In above example Monday is assigned a value 0, but using 0 is not friendly in this examp
Learning Arrays in C# 2005 2007-05-23 08:42:00 Learning Arrays in C# 2005What is an array?An array is an unordered sequence of elements. All the elements in an array have the same type. The elements of an array are in a contagious block of memory and are accessed by using an integer value.Declaring Array VariablesWe declare an array variable by specifying the name of the element, followed by a pair of square brackets, followed by the variable name. The square brackets signify that the variable is an array. e.g, to declare an array of int variables called regNumbers, the syntax is:int[] regNumbers //Registration numbers.you are not restricted to primitive types as array elements. You can nowcreate arrays of structs, enums, classes.Creating Array InstancesArrays are refrence types, regradless of the type of their elements. This means that an array variable refers to an array instance on the heap and does not hold its array elements directly on the stack, ill write more about this in the future posts.To create an array instance, we us Read more:Learning
Difference between a class and an interface 2007-06-25 06:01:00 The difference between an interface and a class
is one that might not be immediately obvious if you're new to object-oriented programming. A class is an encapsulation of attributes and operations that may or may not inherit from another base class (the CLR does not support multiple inheritance). An interface is a contract that defines the attributes and operations that a class must implement in order to satisfy the conditions of the interface.For example, you can have a class that exposes a property called Color that might indicate the color of the object. You can also create an interface called IColorable. Any class that then implements that interface must define a property called Color. So, the essential difference between classes and interfaces is that classes are the definitions of abstractions of real-world entities, and interfaces are requirements and constraints to which all classes bound to the interfaces must conform. You will see more of how this works in the next section, w
Common Operations 2007-06-24 22:11:00 C# Language BasicsVisual C# 2005 Express Edition Working With Numbersint i = 0;// convert from a stringint i = int.Parse("1");// convert froma string and don't throw exceptionsif (int.TryParse("1", out i)) {}i++; // increment by onei--; // decrement by onei += 10; // add 10i -= 10; // subtract 10i *= 10; // multiply by 10i /= 10; // divide by 10i = checked(i*2) // check for overfl owi = unchecked(i*2) // ignore overfl ow Dates and TimesDateTime now = DateTime.Now; // date and timeDateTime today = DateTime.Today; // just the dateDateTime tomorrow = today.AddDays(1);DateTime yesterday = today.AddDays(-1);TimeSpan time = tomorrow - today;int days = time.Days;int hours = time.Hours;int minutes = time.Minutes;int seconds = time.Seconds;int milliseconds = time.Milliseconds;time += new TimeSpan(days, hours, minutes, seconds,milliseconds); Conditional Logicif (i == 0) {}if (i <= 10) {} else {}switch (i) {case 0:case 1:break;case 2:break;default:break;} Compare Operatorsif (i == 0) // e Read more:Common
Declaring and using delegates 2007-06-23 23:11:00 A delegate is declared using the keyword delegate. The general form of a delegate declaration is:Delegate ret-type name ( parameter list)Where ret-type is the type of the value returned by the methods that the delegate will be referring to. Name is the name of the delegate. A delegate can refer to only those methods whose signature exactly match as that specified in the delegate declaration. class Program { //Delegate shutdown declared. public delegate void Shutdown(); class CurrentProcess { public static void endCurrentProcess() { Console.WriteLine("Current process closed"); } } class BackGroundProcess { public static void endBackGroundProcess() { Console.WriteLine("Bac Read more:Declaring
, delegates
Reversing a Two-Dimensional Array 2007-06-22 23:57:00 ProblemYou need to reverse each row in a two-dimensional array. The Array
.Reverse method does not support this operation.SolutionUse the following Reverse2DimArray<T> method: public static void Reverse2DimArray<T>(T[,] theArray) { for (int rowIndex = 0; rowIndex <= (theArray.GetUpperBound(0)); rowIndex++) { for (int colIndex = 0; colIndex <= (theArray.GetUpperBound(1) / 2); colIndex++) { T tempHolder = theArray[rowIndex, colIndex]; theArray[rowIndex, colIndex] = theArray[rowIndex, theArray.GetUpperBound(1) - colIndex]; theArray[rowIndex, theArray.GetUpperBound(1) -colIndex] = tempHolder; } } }DiscussionThe following TestReverse2DimArray method shows how the Reverse2DimArray<T> method is used:public static void TestReverse2DimArray() { Read more:Reversing
Commonly Used String Instance Methods 2007-06-29 08:47:00 MethodDescriptionCompareToCompares this string instance with another string instance.ContainsReturns a Boolean indicating whether the current string instance contains the given substring.CopyToCopies a substring from within the string instance to a specified location within an array of characters.EndsWithReturns a Boolean value indicating whether the string ends with a given substring.EqualsIndicates whether the string is equal to another string. You can use the '==' operator as well.IndexOfReturns the index of a substring within the string instance.IndexOfAnyReturns the first index occurrence of any character in the substring within the string instance.PadLeftPads the string with the specified number of spaces or another Unicode character, effectively right-justifying the string.PadRightAppends a specified number of spaces or other Unicode character to the end of the string, creating a left-justification.RemoveDeletes a given number of characters from the string.ReplaceReplaces al Read more:String
, Methods
Some queue class methods: 2007-06-28 08:29:00 Queue MethodsMethodDescriptionClearRemoves all items from the QueueEnqueueAdds an item to the end of the QueueDequeueReturns and takes an item off the beginning of the QueuePeekReturns the item at the beginning of the Queue without removing itToArrayConverts the contents of the Queue to a fixed-length array of a given type
Read more:class
Iterating over Each Character in a String / Foreach vs For loop to iterate elements in a string. 2007-06-28 00:19:00 ProblemYou need to iterate over each character in a string efficiently in order to examine or process each character.SolutionC# provides two methods for iterating strings. The first is the foreach loop, which can be used as follows: string testStr = "abc123"; foreach (char c in testStr) { Console.WriteLine(c.ToString( )); }This method is quick and easy. Unfortunately, it is somewhat less flexible than the second method, which uses the for loop instead of a foreach loop to iterate over the string. For example: string testStr = "abc123"; for (int counter = 0; counter < testStr.Length; counter++) { Console.WriteLine(testStr[counter]); } Discussion The foreach loop is simpler and thus less error-prone, but it lacks flexibility. In contrast, the for loop is slightly more complex, but it makes up for that in flexibility.The for loop method uses the indexer of the string variable testStr to get the character Read more:Character
, elements
Ways to assign a method to a delegate/Delegate Method Group conversion 2007-06-27 06:02:00 One way to assign a method to a delegate is by using the new operator.class Program { //Declare a delegate delegate int calculator(int a,int b); //Static method sum declared having //same signature as of delegate calculator. static int sum(int a, int b) { return a+b; } static int multi(int a , int b) { return a*b; } static void Main(string[] args) { //Method assigned using new. calculator cal = new calculator(sum); int result; //method invoked using the delegate name. result=cal(20,30); Console.WriteLine("Sum of 20+30 is "+ result); cal=new calculator(multi); result=cal(20,30); Console.WriteLine("Prod Read more:Group
Member Visibility Levels 2007-06-26 04:26:00 Visibility KeywordDescriptionpublicThis member is accessible from both inside the assembly and outside the assembly, as well as by members inside and outside the class.privateThis member is accessible only from code within the class definition itself.protectedThis member is accessible only to derived types, both inside and outside the assembly.internalThis member is accessible by any code within the assembly.public protectedThis member is accessible by all code within the assembly, but only by derived types outside the assembly.private protectedThis member is protected within the assembly (accessible only to derived types), but is inaccessible outside the assembly.
Read more:Member
Appending a Line 2007-06-26 03:23:00 ProblemYou need to append a line, including a line terminator, to the current string.SolutionUse the AppendLine method of the StringBuilder class: StringBuilder sb = new StringBuilder("First line of string"); // Terminate the first line. sb.AppendLine(); // Add a second line. sb.AppendLine("Second line of string");This code will display the following: First line of string Second line of stringDiscussionThe AppendLine method accepts a string and returns a reference to the same instance of the StringBuilder object on which this method was called. The string that is passed in to this method has a newline character or characters automatically appended on to the end of this string. The newline character(s) is dependent on the type of platform you are running. For example, Windows uses the
carriage return and line-feed characters to represent a newline; on a Unix system the newline consists of only the line-feed character
. You do not need to worry about this, as the AppendLine method
Simple types in c# / Data types in c# 2.0 2007-07-06 00:30:00 TypeSize in bitsValue rangeStandardbool8true or false byte80 to 255, inclusive sbyte8128 to 127, inclusive char16'u0000' to 'uFFFF' (0 to 65535), inclusiveUnicodeshort1632768 to 32767, inclusive ushort160 to 65535, inclusive int322,147,483,648 to 2,147,483,647, inclusive uint320 to 4,294,967,295, inclusive float32Approximate negative range:IEEE 754 3.4028234663852886E+38 toIEC 60559 1.40129846432481707E45 Approximate positive range: 1.40129846432481707E45 to 3.4028234663852886E+38 Other supported values: positive and negative zero positive and negative infinity not-a-number (NaN) long649,223,372,036,854,775,808 to 9,223,372,036,854,775,807, inclusive ulong640 to 18,446,744,073,709,551,615, inclusive double64Approximate negative range:IEEE 754 1.7976931348623157E+308 toIEC 60559 4.94065645841246544E324 Approximate positive ran Read more:Simple
, types
Data Binding without Code / DataGridView Control 2007-07-05 08:08:00 Bind to Data Without Writing CodeThis is basically a guided tutorial on how to bind the dataGridView control to the database.Drag and drop the dataGridView control on the Form.To set up the database connection. You can do this in a number of ways, but it's easiest to click the smart tag and drop down the Choose Data Source list. Click Add Project Data Source as shown.At this screen select Database and click NextAssuming this is the first time you are connecting your database click New ConnectionAs you can see the default Data source is OLEDB, I want my SQL Express to be shown here, so that i could select any SQl Database. Click Change to choose SQL Express or if you want you can use MS Access as your Database. For now im using SQL Express.After selecting Sql Server click next.Type your Sql server name and then select the database, in my case XPSSQLEXPRESS is my sql server name and im using Employees. Choose next.Choose next to save your connection details.Choose tables as the datase Read more:Binding
, Control
Events in c# / Delegates and Events 2007-07-05 02:11:00 What are events?Events are simply signals sent by an action. Clicking of a mouse button, pressing of a key are all events. In GUI's events are occurred and we have some action which follows an event, such an action is called an event handler or a method that handles an event is called an event handler. Publishing and Subscribing:In C#, an object can publish events to which other classes can subscribe. The publishing class triggers an event to which the subscribed class respond by handling those events. So when a button is clicked the subscribers are notified about the click. The advantage of publish/subscribe is that any number of classes can be notified when an event is raised. The subscribing classes do not need to know how the event occurs, and the event itself does not need to know what the event handler is going to do.Events and Delegates:Events in C# are implemented using delegates. The publishing class defines a delegate that the subscribing classes must implement. When an e
Covariance and Contravariance 2007-07-05 01:16:00 C# 2.0 has added two more features to delegates "Covariance and contravariance". From my earlier discussions you already know that a method passed to a delegate must have the same return type and signature, however, Covariance and contravariance allows some flexibility. Covariance allows a method to be assigned to a delegate when the method's return type is a class derived from the class specified by the return type of the delegate. Contravariance allows a method to be assigned to a delegate when a method's parameter type is a base class of the class specified by the delegate's declaration. The below example explains Covariance and contravariance in more detail. class teacher {public int hoursWorked=0; } class parent : teacher { public int age=21; } delegate teacher convert(parent p); class Program { //At school parent is a teacher! //Takes parent as an argument //and r
Anonymous Methods / Pass Arguments to an Anonymous Method / Return a value from an Anonymous Method. 2007-07-04 23:07:00 C# 2.0 provides greater flexibility in terms of simplicity. You can pass a block of code to a delegate just like a method, but here no method name exists. Imagine sending methods signature and code body to the delegate, but not the name. This signature and block of code without a name is called an anonymous method. It may sound a bit confusing why to send a method to a delegate without its name? Well, anonymous methods basically reduce the amount of code that is required first to declare a method and then to assign it to a delegate. But you cannot use anonymous method again n again in your code, anonymous methods are best suitable in conditions where you need to execute a block of code just once. Take a look at the following example.delegate int calculator(int a,int b); //Declare a delegate. class Program { static void Main(string[] args) { //Instance of delegate assigned an annoym Read more:Methods
, Return
Create Auto-Complete Text Boxes 2 2007-07-04 02:14:00 What are auto-complete text boxes?Due to high viewership i have decided to dicuss in more detail on how to create auto-complete text boxes. this post is a sequel of my previos post found here. As you already know, auto complete is a user friendly feature which finds it extensive use in Browsers, for helping users to ease out the burden of writing complete already visited URL's. The text box offers alternate url's to choose from. In the below screen shot from mozilla, auto complete feature reducestyping time. The newly updated TextBox and ComboBox controls provided with Visual Studio 2005 allow you to add that functionality to your Windows Forms as well.How can i create my own Auto-complete text box?Create a new Windows application, call it AutoComplete and drag a TextBox onto the form.Click the TextBox control, and in the properties window drop down the AutoCompleteMode property, as shown:SuggestDisplays the drop-down list populated with one or more suggested completion strings.Appen Read more:Boxes
Multicasting Delegates 2007-07-03 23:19:00 One of the most important feature in delegates is multicasting. In multicasting you can create an invocation list, or a series of methods assigned to a delegate by the + or += operator. Methods can removed from the list using the – or -= operator. In case of methods returning a value, the last method in the chain that returns the value will become the return value of the entire chain. So, to be on the safer side void methods must be used when multicasting. delegate int calculator(int a,int b); //Declare a delegate. class Program { class Cal { //Two public non static methods. public int sum(int a, int b) { return a + b; } public int multi(int a, int b) { return a * b; } } static void Main(s
Using Instance Methods as Delegates 2007-07-03 09:12:00 In my last post about Delegates, I used a static class method as a delegate, but today I'm going to assign a non static class method to a delegate.delegate int calculator(int a,int b); //Declare a delegate. class Program { class Cal { //Two public non static methods. public int sum(int a, int b) { return a + b; } public int multi(int a, int b) { return a * b; } } static void Main(string[] args) { //Instance of Class Cal Cal c1 = new Cal(); //Declare a reference to a delegate calci calculator calci = c1.sum; //Inovoke sum via delegate calci int temp = calci(10, 20); Console.WriteLine("10 + 20 Read more:Methods
ASCII Character Set 2007-07-09 04:45:00 ASCII Character
Set. 01234567890nulsohstxetxeotenqackbelbsht1nlvtffcrsosidledc1dc2dc32dc4naksynetbcanemsubescfsgs3rsussp!"#$%&'4()*+,-./01523456789:;6<=>?@ABCDE7FGHIJKLMNO8PQRSTUVWXY9Z[]^_'abc10defghijklm11nopqrstuvw12xyz{|}~del The digits at the left of the table are the left digits of the decimal equivalent (0127) of the character code, and the digits at the top of the table are the right digits of the character code. For example, the character code for "F" is 70, and the character code for "&" is 38.
Read more:ASCII
Partial Classes 2007-07-08 02:13:00 Another language feature added in C# 2.0 is partial classes. Partial
classes are portions of a class that the compiler can combine to form a complete class. Although you could define two or more partial classes within the same file, the general purpose of a partial class is to allow the splitting of a class definition across multiple files. Primarily this is useful for tools that are generating or modifying code. With partial classes, the tools can work on a file separate from the one the developer is manually coding. C# 2.0 declares a partial class by appending the contextual keyword, partial, to the definition,. Defining a Partial Class// File: Program1.cspartial class Program{}// File: Program2.cspartial class Program{}In this case, each portion of Program is placed into a separate file, as identified by the comment. Besides their use with code generators, another common use of partial classes is to place any nested classes into their own files. This is in accordance with the codin Read more:Classes
The Common Documentation Comment Instructions / Comment Instructions in c# 2.0 2007-07-06 22:00:00 The CommonDocumentationCommentInstructions
InstructionWhat It Means<summary></summary> Describes the function itself. Displays when you enter the name of the function during editing.<param></param>Describes an argument to the function. Displays after you type in the function name and the open parenthesis,prompting you about what you should enter next. Use one set of <param> tags per argument.<returns></returns>Describes the value returned by the functionDocumentation comments follow XML/HTML rules: A command starts with a <command> tag and ends with a </command> tag. In fact, they are normally known as XML tags due to their relationship to XML. Numerous other XML tags are available for documentation comments. For more information, choose Help➪Index and then look under "XML documentation features [C#]."The following example is a commented version of a simple program:class Program { /// &
Some Important Keywords in c# 2007-07-12 07:03:00 Keywords in c#abstract A class modifier that specifies that the class must be derived from to be instantiated. as A binary-operator type that casts the left operand to the type specified by the right operand, and that returns nullrather than throwing an exception if the cast fails. base A variable with the same meaning as this, except it accesses a base class implementation of a member. bool A logical datatype that can be true or false. break A jump statement that exits a loop or switch statement block. byte A one-byte unsigned integral datatype.case A selection statement that defines a particular choice in a switch statement. catch The part of a try statement that catches exceptions of a specific type defined in the catch clause. char A two-byte Unicode character datatype. checked A statement or operator that enforces arithmetic bounds checking on an expression or statement block. class An extendable reference type that combines data and functionality into one unit. Read more:Keywords