Learn C sharpLearn C sharpA blog which helps novice programmers learn c sharp 2005 Articles
Interface-Creating a private implementation/ Implicit and Explicit Implemen
2007-06-13 14:20:00 Review the following example: class Program { static void Main(string[] args) { person p1 = new person(); p1.display(); IDisplay d = p1; //Create an interface reference variable d.show(); //Calling the explicitly implemented method Console.ReadLine(); } interface IDisplay //Declasre IDisplay as an interface { // no access modifiers, methods are public // no implementation void display(); //Method signature only, no implementation. void show(); } class person : IDisplay //Inherit IDisplay { public string _name; //members public person() //defualt constructor { _name = "Waseem"; } ... More About: Creating , Private , Interface , Eating , Riva
Using Interface Reference or referencing a class through its interface
2007-06-13 08:05:00 It's quite surprising but yes you can create an interface reference variable. As you already know that you can reference an object by using a variable defined as class that his higher up the hierarchy. You can reference an object by using a variable defined as an interface that its class implements. person p1 = new person();IDispay d = p1; //Legal d.display();Â Â Â Â In this example, you can reference a person object by using an IDisplay variable.We can declare a method, that accepts only those arguments that implement the interface. class Program { static void Main(string[] args) { person p1 = new person(); person.checker(p1); //passes the p1 as an argument to the checker method. student s1 = new student(); person.checker(s1); //compliation error, since student does not implement IDisplay Cons... More About: Reference , Interface , Class , Ferenc , Refer
More on Interfaces
2007-06-13 06:24:00 Things to remember:The method names and return types should exactly match.Any parameters (including ref and out keyword modifiers) should match exactly.The method name is prefaced by the name of the interface.Implementing More Than One Interface:Classes can implement more than one interface.class Program { static void Main(string[] args) { person p1 = new person(); p1.display(); //uses its own implementation for the display method p1.read(); p1.display();  Console.Read(); }  interface IDispay //Declasre IDisplay as an interface { // no access modifiers, methods are public // no implementation void display(); //Method signature only, no implementation. } interface IRead //Declare IRead as an... More About: Interfaces
Virtual Methods
2007-06-11 07:30:00 Before I start my today's post on virtual methods, I would like to share some of my experiences with you. Well, I try to post on this blog some topics on the wonderful C# programming language. Some of you may think that I have C# on the brain, well that's not completely true. The only force that drives me posting on this blog is the idea of helping others. I don't earn much from this blog, as this blog is quite fresh, earning was not may aim when I started this blog; I just thought it to be an outcome of hard work. Anyways, without wasting much time and energy lets get started with one of the most important aspects in object oriented programming Virt ual methods. First thing's first. What are virtual methods?Those who are already familiar with Object Oriented Programming & some of the fundamentals there in, shouldn't have much problem understanding Virtual methods, well those who do not, I strongly recommend reading some basics of OOP (search in Google for more). What is a v... More About: Methods , Method
Inheritance and Name Hiding
2007-06-09 13:51:00 It is possible for a derived class to define a variable/method that has the same name as that of the base class's variable/method. When this happens, the member in the base class is hidden within the defined class. The compiler generates a warning message telling you that variable/method hides the inherited variable/method of the base class.public humans(string name, int age) { _name=name; _age=age; } public void display() { Console.WriteLine("Name =" + _name); Console.WriteLine("Age = " + _age); } } class students:humans //Derived from humans class { private int _sID; public students(string name, int age, int sID):base(name,age) //Calls humans { _sID = sID; ... More About: Inheritance
Using base to access a hidden name
2007-06-09 13:51:00 You can access base class methods/variables which are hidden by the member names of the derived class. Lets us consider a situation:class a { public int i=0; } class b : a { new public int i; void put(int a, int b) { base.i = a; //assigns a to base class variable i. i = b; //assigns b to derived class variable i. } } Here, the base class member is accessed using the base keyword. More About: Access , Inheritance , Hidden , Base
Calling Base class Constructors
2007-06-09 07:50:00 Calling Base Class Cons t ructorsHow to call the base class constructor from the derived class?Every class has its own constructor whether you create it or not (if you don't provide a default constructor, the compiler generates a default constructor itself). When you inherit a class, it contains members and methods. The members of the base class require initialization, since the constructor of the derived class can initialize only the derived class members. The solution is quite simple; you use the base keyword to call a base class constructor, when the constructor is defined. E.g. class humans { //Members of the base class private string _name; private int _age; //base class constructor public humans(string name, int age) { _name=name; _age=age; } } class students:humans //Derive... More About: Calling , Inheritance
Using Inheritance in c#
2007-06-07 14:13:00 Using Inheritance Its time to get under the hood, so here it goes?In c#, the syntax for declaring a class is derived from other class is as follows:class student:human { //Actual Implementation. } Here, student is derived from the base class human. Unlike c++, c# classes can be derived from just one class but can derive many interfaces. More on interfaces in my future posts. Here in c# inheritance is always implicitly public. One more important thing, when you define classes, these classes are automatically inherits all the features of System.Object class. E.g. the .ToString method.Member Access and inheritance:Members of class are either declared public or private depending upon their levels of protection. Members declared private prevent any unauthorized use. When a class inherits from a base class which has private members, the derived class cannot access the private members of the base class. A private class member will remain private to its class...
Types of Inheritance
2007-06-06 13:38:00 Types of Inheritance Before you lay your hands on writing the code, you should understand the types of inheritance.Implementation inheritance:Implementation inheritance means that a type takes all the members & methods/functions of the base type. The derived type uses the implementation of the base type functions. The derived class has the option of either using the base functions/methods implementation or override it to be more specific. This type of inheritance is useful when you want to add functionality to an existing class or where the numbers of related classes have functionality.e.g. System.Windows.Forms.TextBox and System.Windows.Forms.ListBox are derived from Controls. But each control has its own method overridden to provide their unique functionality.Interface Inheritance:In this inheritance, the derived class only implements the method signatures rather than implementing the entire method. This inheritance is most used when you want distinct functionality. In c#, unli... More About: Types
Introduction to Inheritance
2007-06-06 13:38:00 InheritanceHi! There, this is my new post on one of the fundamental topics of Object Oriented Programming. Understanding inheritance is quite challenging, but hey we all love challenges, don't we? Before I explain inheritance, I assume you have a good understanding of Objects and classes. If you don't I would suggest you to lay your hands on some fundamental programming book or search the internet. Ill add some more posts on object oriented fundamental topics in the course of time. When I first learnt about inheritance a couple of questions really haunted me. "Why inheritance, what is inheritance" and so on. After working with c# a lot, I can now understand the use of it. Inheritance is often used when we say a child inherits genes from parents. He a child inherits some genes from mom and some from daddy. A child has properties like face cut, colour of eyes and hair, etc mostly inherited from parents or grandparents. In programming, inheritance is classification. To fully understa... More About: Introduction , Inheritance , Intro
Difference between array and arrayList
2007-06-06 05:48:00 If you go through my previous posts "Diff erence between array and collections", you will probably understand the difference. However, as a revision all I can say here is that array stores value types which do not require any unboxing, whereas Array List stores elements as objects which require unboxing. Array and ArrayList also have some distinct features, array cannot grow or shrink in size, i.e. we cant change the size of the array or we cannot redim it what it used to be in VB. In case of ArrayList can be dynamically resized or reduced. The ArrayList.count property returns the total number of elements in the arraylist to keep track of the size of the arraylist. ArrayList uses complex boxing and unboxing, arrays as such are much easier in their implementation. More About: Ferenc , Ween
ArrayList Properties & Methods
2007-06-06 05:38:00 ArrayList methods and properties Method or propertyPurposeAdapter( ) Public static method that creates an ArrayList wrapper for an IList object. FixedSize( ) Overloaded public static method that returns a list object as a wrapper. The list is of fixed size; elements can be modified but not added or removed. ReadOnly( ) Overloaded public static method that returns a list class as a wrapper, allowing read-only access. Repeat( ) Public static method that returns an ArrayList whose elements are copies of the specified value. Synchronized( ) Overloaded public static method that returns a list wrapper that is thread-safe. Capacity Property to get or set the number of elements the ArrayList can contain. Count Property to get the number of elements currently in the array.IsFixedSize Property to get to find out if the ArrayList is of fixed size. IsReadOnly Property to get to find out if the ArrayList is read-only. IsSynchronized Property to get to find out if the ArrayList is thread-safe. It... More About: Collections , Methods , Array , Properties
Arrays Vs Collections
2007-06-05 15:51:00 Arrays Vs Coll ections An array list declares the type of elements it holds.A collection stores elements as objects.An array instance cannot be grow or shrink. It size remains constant.Collections can grow dynamically.We cannot create a read only array.Collections can be used in Read-Only modes. The collection class provides a ReadOnly method for this. More About: Arrays , Rays , Array
SortedList Class
2007-06-05 14:41:00 The Sort edList classWhat is a sortedList?SortedList is much like a hashtable, the only difference between them is that they key array of the sortedlist is always sorted.When you insert a new item into the sortedlist the list automatically sorts and fits the element. The same happens when you remove an element. SortedList like the hashtable cannot have duplicate keys. An example of a sortedList. static void Main(string[] args) { SortedList sl = new SortedList(); sl.Add("name", "Waseem"); sl.Add("EmpCode", "xps"); sl.Add("Address", "India"); //We can add by using the indexer. sl["Pin Code"] = 190010; //Get a collection of the keys. ICollection ic = sl.Keys; //Use the keys to obtain the valuue foreach (string c in ic) { Console.WriteLine(sl[c]); } ... More About: Collections , Class , T class
The Hashtable class
What is a hashtable?
Hashtable...
2007-06-04 08:31:00 The Hashtable classWhat is a hashtable?Hashtable creates a collection that uses a hash table for storage. Unlike an array or a arraylist, hastable uses string, double, time as in index. Hashtable contains two values as arguments?the fist is the key and the second the value itself. The key is then converted into hash code automatically (it is an internal process and we never see the hash code).Hashtable implements the IDictionary, ICollection, IEnumerable, ISerializable, IDeseriliazationCallback and ICloeable interfaces. (I'll explain interfaces in getter detail later in the posts).An example of a hashtable.static void Main(string[] args) { Hashtable ht = new Hashtable(); ht.Add("name", "Waseem"); ht.Add("empID", "12"); ht.Add("Address", "India"); foreach (DictionaryEntry d in ht) { Console.Write(d.Key + " " + d.Value); Console.WriteLin... More About: Class
Collections Part2
2007-06-01 14:47:00 The Queue classWhat is a queue list?The queue list, as the name suggest is a simple queue which implements a LIFO (Last in first out) mechanism. Like a queue an element is inserted into the queue at the back (the enqueue operation) and is removed from the queue at the beginning (the dequeue operation).An example of a queue and its operations. static void Main(string[] args) { Queue names = new Queue(2); names.Enqueue("Hello!"); names.Enqueue("World!"); //Foreach loop should be used to iterate the elements in a queue list. foreach (string t in names) { Console.WriteLine(t); } //This loop will not return Hello!World! it will return only Hello! //Since, the queue gets reduced by 1, when dequeued. for (int i = 0; i != names.Count; i++) { ... More About: Collections , Coll
Collections
2007-05-31 07:37:00 CollectionsWhat are collections?Collections provide advanced functionality for managing groups of objects. A collection is a specialized class that organizes and exposes a group of objects.Features of a collection:Collections accept, hold, and return their elements as objects.Collections can be resized dynamically, and members can be added and removed at run time.Boxing and unboxing is required to hold data in collections. The array list classWhat is an array list?The System.Collections.ArrayList class provides general collection functionality that is suitable for most purposes. This class allows you to dynamically add and remove items from a simple list. Items in the list are retrieved by accessing the index of the item. You can create a new instance of the ArrayList class as shown in the following example: System.Collections.ArrayList myList = new System.Collections.ArrayList(); There are certain occasions when an ordinary array can be too restrictive:If you want to resize an arra... More About: Collections , Coll
Other Arrays
2007-05-30 08:30:00 Char Array s What is a char Array?A character array contains characters as array elements. Each character in the character array can be accessed using the array index. This is much like the any other array like int. Here, when assigning each character should be inside a single quote. 'a' like this.Declaring a char array:Char Arrays can be declared and initialized in the following pattern // One way of declaring the char array without providing the sizechar[] name = new char[4] { 'p', 'o', 'g', 'o' }; //Here name is implicitly assigned 5 as its size.char[] name = new char[] { 'h', 'e', 'l', 'l', 'o' }; Example showing how to read and write the values of a char array.static void Main(string[] args) { //Here name is implicitly assigned 5 as its size.char[] name = new char[] { 'h', 'e', 'l', 'l', 'o' }; int x=0; //Loop to write hello in a pattern... More About: Rays
Summary Arrays
2007-05-30 08:09:00 Topics Covered:Introduction to arrays.System.arrays Methods and Properties.The array class.Using params.Passing arrays and array elements to methods.Passing arrays as value and as refrence.Common Errors in arrays.MultiDimensional arrays.Jagged Array s .Other ArraysImportant Notes. More About: Rays , Summary
Jagged Arrays
2007-05-30 06:30:00 What is a jagged Array ?A jagged array is really an array of arrays. To create a jagged array, you declare the array of arrays with multiple sets of parentheses or brackets and indicate the size of the jagged array in the first set of brackets (parentheses). The following example demonstrates how to create a simple jagged array:Declaring a jagged array:Jagged Arrays can be declared and initialized in the following pattern // Declares an array of 3 arraysstring[][] Families = new string[3][]; // Initializes the first array to 4 members and sets valuesFamilies[0] = new string[] {"Smith", "Mom", "Dad", "Uncle Phil"}; // Initializes the second array to 5 members and sets valuesFamilies[1] = new string[] {"Jones", "Mom", "Dad", "Suzie", "Little Bobby"}; // Initializes the third array to 3 members and sets valuesFamilies[2] = new string[] {"Williams", "Earl", "Bob"}; Example to read write the values of a two dimensional ar... More About: Rays
MultiDimensional Arrays
2007-05-28 15:47:00 Two-Dimension al Array s Declaring a two-dimensional array:int[ , ] arr;We know that from our previous topics how to declare an array. To remind us again the square brackets that are part of the declaration identify the rank, or the number of dimensions, for the array; in this case the rank is 2.Instantiating and assigning arrays:Once an array is declared we can immediately fills its contents using a comma delimited list of items enclosed within a pair of curly brackets e.g.int[ , ] arr = int [ 2, 2 ] ;//Here a two dimensional array arr is declared having two rows and two columns OR having 4 cells. The rank of this array is two. The length property of this array will return us 4.Arrays can be initialized in the following patternint [ , ] arr = { {1, 2}, {3, 4} };Here the cells 0, 0 are assigned the value 1; cells 0, 1 value 2 and so on?Example to read write the values of a two dimensional array.static void Main(string[] args){Console.WriteLine(" Understanding MultiDimension Arr... More About: Sion , Rays
The Array Class
2007-05-26 08:09:00 Properties Defined by Array public bool IsFixedSize { get; }A read-only property that is true if the array is of fixed size and false if the array is dynamic.public bool IsReadOnly { get; }A read-only property that is true if the Array object is read-only and false if it is not.public bool IsSynchronized { get; }A read-only property that is true if the array is safe for use in a multithreaded environment and false if it is not.public int Length { get; }An int read-only property that contains the number of elements in the array.public long LongLength { get; }A long read-only property that contains the number of elements in the array.public int Rank { get; }A read-only property that contains the number of dimensions in the array.public object SyncRoot { get; }A read-only property that contains the object that synchronizes access to the array. More About: Class , The A
Passing array as value and as refrence
2007-05-25 13:23:00 In C#, a variable that "stores" an object, such as an array, does not actually store the object itself. Instead, such a variable stores a reference to the object (i.e., the location in the computer's memory where the object itself is stored). This distinction raises ambiguity in the stablility of programs.When the variable passed to a method is of value type, the called method recieves the copy of that arguments value, but if the variable is of refrence type, the method recieves the copy of the refrence , i.e. now both the the objects now refer to the same value, changing the value of the argument in method will change the value of orginal object.Pass ing arrays and other objects by reference makes sense for performance reasons. If arrays were passed by value, a copy of each element would be passed. For large, frequently passed arrays, this would waste time and would consume considerable storage for the copies of the arraysboth of these problems cause poor performance.Passi ng an arr... More About: Value , Array , Passing
Passing Arrays and Array Elements to Methods
2007-05-25 04:56:00 To pass an array to a method we need to pass the array name without the brackets, e.g if we have an array cars declared as:int[] cars = new cars[4];to pass this array to a method we need to call the method and send the array name as its parameter.e.g fun(cars)passes the reference of array cars to method fun. Every array object "knows" its own length (and makes it available via its Length property). Thus, when we pass an array object's reference to a method, we need not pass the array length as an additional argument.we assume the code in method fun is :public void fun( int[] c)The parameter list must contain an array parameter to hold the passed refrence.The method call passes array cars's reference, so when the called method uses the array variable c, it refers to the same array object as cars in the calling method.When an argument to a method is an entire array or an individual array element of a reference type, the called method receives a copy of the reference. However, when a... More About: Elements , Pass , Methods , Arrays , Rays
Arrays Imp note
2007-05-24 11:07:00 When a method receives a reference-type parameter by value, a copy of the object's reference is passed. This prevents a method from overwriting references passed to that method. In the vast majority of cases, protecting the caller's reference from modification is the desired behavior. If you encounter a situation where you truly want the called procedure to modify the caller's reference, pass the reference-type parameter using keyword refbut, again, such situations are rare. More About: Note , Arrays , Rays , Array
The params Keyword
2007-05-24 10:15:00 The params Keyword You can create a method that displays any number of integers to the console by passing in an array of integers and then iterating over the array with a foreach loop. The params keyword allows you to pass in a variable number of parameters without necessarily explicitly creating the array.In the next example, you create a method, DisplayVals( ), that takes a variable number of integer arguments:public void DisplayVals(params int[] intVals)The method itself can treat the array as if an integer array were explicitly created and passed in as a parameter. You are free to iterate over the array as you would over any other array of integers:foreach (int i in intVals){ Console.WriteLine("DisplayVals {0}",i);}The calling method, however, need not explicitly create an array: it can simply pass in integers, and the compiler will assemble the parameters into an array for the DisplayVals( ) method:t.DisplayVals(5,6,7,8);You are free to pass in an array if you prefer:int [] exp...
About Me...
2007-05-24 09:59:00 Hi,I am Waseem Bashir, recently graduated as a BCA (Bachelor of Computer Applications). I am a C# developer and i intend to dedicate this blog to this wonderful programming language.This blog will contain all the tips n tricks in Visual C# 2005.Feel free to be a part of this blog...Happy Blogging!Cya soon
Reading a XML into a dataset?
2007-05-24 09:58:00 If u dont happen to use a database or if u dont have a database installed you can use XML as a data store.Just create a simple .xsd (xmlSchemaDocument) and then create a XML file using the namespace of the .xsd file you created earlier, alternatively you can direclty use ur xml document without any schema's ( this can happen when your data is too small to be stored in a database).private void button1_Click(object sender, EventArgs e){//Create a datasetDataSet ds = new DataSet();//Read the XML documentds.ReadXml("YourXmlFile.xml");//u se a datagrid to show the recordsdataGridView1.DataSource=ds.Tables (0);//This code works fine, but for updation hmm.. stay tuned!} More About: Reading
System.Array methods and properties
2007-05-24 09:56:00 Method or property PurposeBinarySearch( )Overloaded public static method that searches a one-dimensional sorted array.Clear( )Public static method that sets a range of elements in the array either to zero or to a null reference.Copy( )Overloaded public static method that copies a section of one array to another array.CreateInstance( )Overloaded public static method that instantiates a new instance of an array.IndexOf( )Overloaded public static method that returns the index (offset) of the first instance of a value in a one-dimensional array.LastIndexOf( )Overloaded public static method that returns the index of the last instance of a value in a one-dimensional array.Reverse( )Overloaded public static method that reverses the order of the elements in a one-dimensional array.Sort( )Overloaded public static method that sorts the values in a one-dimensional array.IsFixedSizePublic property that returns a value indicating whether the array has a fixed size.IsReadOnlyPublic property that ... More About: System , Methods , Array , Properties , Method
Learning Series
More articles from this author:2007-05-24 09:55: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... More About: Series , Learning , Learn , Serie , Erie 1, 2, 3, 4 |



