Saturday, 8 September 2012

C#.Net Interview Question


C#.Net Interview Question

1.What’s the implicit name of the parameter that gets passed into the class’ set method? 
Value, and its datatype depends on whatever variable we’re changing.

2.How do you inherit from a class in C#?
Place a colon and then the name of the base class. Notice that it’s double colon in C++.

3.Does C# support multiple inheritance? No, use interfaces instead.

4.When you inherit a protected class-level variable, who is it available to?
Classes in the same namespace.

5.Are private class-level variables inherited? Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.

6.Describe the accessibility modifier protected internal?
It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s declared in).

7.C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write? 
Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.

8.What’s the top .NET class that everything is derived from?
System.Object.

9.How’s method overriding different from overloading? When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.

10.What does the keyword virtual mean in the method definition? The method can be over-ridden.

11.Can you declare the override method static while the original method is non-static?
No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

12.Can you override private virtual methods? No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.

13.Can you prevent your class from being inherited and becoming a base class for some other classes?
Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It’s the same concept as final class in Java.

14.Can you allow class to be inherited, but prevent the method from being over-ridden? 
Yes, just leave the class public and make the method sealed.

15.What’s an abstract class?
A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, it’s a blueprint for a class without any implementation.

16.When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?
When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.

17.What’s an interface class?
It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.

18.Why can’t you specify the accessibility modifier for methods inside the interface?
They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it’s public by default.

19.Can you inherit multiple interfaces?
Yes, why not.

20.And if they have conflicting method names? It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.

21.What’s the difference between an interface and abstract class?
In the interface all methods must be abstract; in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes.

22.How can you overload a method?
Different parameter data types, different number of parameters, different order of parameters.

23.If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

24.What’s the difference between System.String and System.StringBuilder classes?System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

25.What’s the advantage of using System.Text.StringBuilder over System.String?StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.

26.Can you store multiple data types in System.Array?
No.

27.What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The first one performs a deep copy of the array, the second one is shallow.

28.How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.

29.What’s the .NET datatype that allows the retrieval of data by a unique key?HashTable.

30.What’s class SortedList underneath?
A sorted HashTable.


31.Will finally block get executed if the exception had not occurred?

Yes.

32.What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

33.Can multiple catch blocks be executed?
No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.

34.Why is it a bad idea to throw your own exceptions?
Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.

35.What’s a delegate?
A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.

36.What’s a multicast delegate?
It’s a delegate that points to and eventually fires off several methods.

37.How’s the DLL Hell problem solved in .NET? 
Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

38.What are the ways to deploy an assembly? 
An MSI installer, a CAB archive, and XCOPY command.

39.What’s a satellite assembly?
When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.

40.What namespaces are necessary to create a localized application?System.Globalization, System.Resources.

41.What’s the difference between // comments, /* */ comments and /// comments?
Single-line, multi-line and XML documentation comments.

42.How do you generate documentation from the C# file commented properly with a command-line compiler? 
Compile it with a /doc switch.

43.What’s the difference between c and code XML documentation tag?
Single line code example and multiple-line code example.

44.Is XML case-sensitive? 
Yes, so Student and student are different elements.

45.What debugging tools come with the .NET SDK?
CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.
46.What does the This window show in the debugger?
It points to the object that’s pointed to by this reference. Object’s instance data is shown.

47.What does assert() do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

48.What’s the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

49.Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.

50.Where is the output of TextWriterTraceListener redirected? 
To the Console or a text file depending on the parameter passed to the constructor.

51.How do you debug an ASP.NET Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.

52.What are three test cases you should go through in unit testing?
Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).

53.Can you change the value of a variable while debugging a C# application?
Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.

54.Explain the three services model (three-tier application)?
Presentation (UI), business (logic and underlying code) and data (from storage or other sources).

55.What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.

56.What’s the role of the DataReader class in ADO.NET connections?
It returns a read-only dataset from the data source when the command is executed.

57.What is the wildcard character in SQL?
Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.

58.Explain ACID rule of thumb for transactions?
Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).

59.What connections does Microsoft SQL Server support? 
Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).

60.Which one is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.

61.Why would you use untrusted verificaion?
Web Services might use it, as well as non-Windows applications.

62.What does the parameter Initial Catalog define inside Connection String?
The database name to connect to.

63.What’s the data provider name to connect to Access database?
Microsoft.Access.

64.What does Dispose method do with the connection object?
Deletes it from the memory.

65.What is a pre-requisite for connection pooling? 
Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.

MASM syntax highlighting in Visual Studio


MASM syntax highlighting in Visual Studio
When a text editor uses syntax highlighting, language keywords, strings, and other elements appear in different colors. Visual Studio and Visual C++ Express can highlight MASM reserved words and strings, as shown in the following example:

This won't happen automatically, but you can create a syntax definition file named Usertype.dat that contains MASM keywords. Then when Visual Studio (or Visual C++ Express) starts, it reads the syntax file and highlights MASM keywords.
Here are the required steps to set up MASM syntax highlighting in Visual Studio or Visual C++ Express:
1) Download the Usertype.dat file given here to a folder in which you have read/write permissions. If you are using Windows Vista, download to My Documents, or C:\temp, or any folder that doesn't have security restrictions.
2) Copy Usertype.dat to the C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE folder. If you are using Windows Vista, it will display a verification window before copying the file.
3) Open Visual Studio or Visual C++ Express, select Options from the Tools menu, selectText Editor, and select File Extension. On the right side of the dialog (shown below), enter asm as the extension, select Microsoft Visual C++ from the Editor list, and click theAdd button. Click the OK button to save your changes.

Close Visual Studio and restart it. Open your project and display an ASM file. You should see syntax highlighting in the editor.

How To Use Visual Studio For Running Assembly Code

You might be interested to know more about how Visual C++ projects are set up for assembly language programs. Follow the following steps to use .Net Framework to assemble your assembly code. First of all install VS 2005 or VS 2008 complete and extract the content of irvine.exe
Download Irvine.exe for VS 2005
Download Irvine.exe for VS 2008
Now open Visual Studio and choose File -> New -> Project .
Select Visual C++ in left column and Empty Project in Right Column. Give a name to your project i.e. "Project 1" and click OK.


Right Click on the project in Solution Explorer and Choose "Custom Build Rules". or open it from Project menu i.e . Project -> Custom Build Rules


Int that Dialog Box mark "Microsoft Macro Assembler" as checked. and click OK


Now open Add New Item dialog box by right clicking in the solution explorer and choosingAdd -> New Item.. Or you can also open Add New Item dialog box from toolbar button.

In Add New Item dialog box choose Code from left column and C++ File(.cpp) from right column. and give it any name with .asm extension. Like i have given it a name main.asm. Remember .asm extension is necessary.

Now select Project Properties from the Project menu. Expand the entry underConfiguration Properties. Then expand the entry named Microsoft Macro Assembler. This is what you should see:

Click the entry named General under Microsoft Macro Assembler . Notice that theInclude Paths option has been set to the c:\Irvine directory. This tells the assembler where to find files having a filename extension of ".inc". Here is a sample:

Find the Linker entry under Configuration Properties. Select the Input entry, and notice that two filenames have been added to the Additional Dependencies entry. Theuser32.lib file is a standard MS-Windows file. The irvine32.lib file is the link library file supplied with this book. There must be at least one space separating the file names:
Next, select Linker under Configuration Properties, and then select General. TheAdditional Library Directories option equals c:\Irvine, so the linker can find the Irvine32.lib library file:

Select Linker under the Configuration Properties and select Debugging. Notice that theGenerate Debug Info option is set to Yes:

Select System under the Linker entry. Notice that the SubSystem option has been set toConsole:

We use the Console setting because it is easy for assembly language programs to write output to a text console (Command) window. This is the window you see when running cmd.exe from the Start > Run menu in Windows.
Click the OK button to close the Project Property Pages window.

Now you have set up correctly so do start coding but remember to write the first line of code as
INCLUDE irvine32.inc

Saturday, 7 April 2012

C Sharp Tutorials/Lesson 10 Lesson 10: Properties


Lesson 10: Properties

This lesson teaches C# Properties. Our objectives are as follows:
  • Understand What Properties Are For.
  • Implement a Property.
  • Create a Read-Only Property.
  • Create a Write-Only Property.
  • Create an auto-implemented property.

Overview of Properties

Properties provide the opportunity to protect a field in a class by reading and writing to it through the property. In other languages, this is often accomplished by programs implementing specialized getter and setter methods. C# properties enable this type of protection while also letting you access the property just like it was a field.
Another benefit of properties over fields is that you can change their internal implementation over time. With a public field, the underlying data type must always be the same because calling code depends on the field being the same. However, with a property, you can change the implementation. For example, if a customer has an ID that is originally stored as an int, you might have a requirements change that made you perform a validation to ensure that calling code could never set the ID to a negative value. If it was a field, you would never be able to do this, but a property allows you to make such a change without breaking code. Now, lets see how to use properties.

Traditional Encapsultation Without Properties

Languages that don't have properties will use methods (functions or procedures) for encapsultation. The idea is to manage the values inside of the object, state, avoiding corruption and misuse by calling code. Listing 10-1 demonstrates how this traditional method works, encapsulating Customer information via accessor methods.
Listing 10-1. An Example of Traditional Class Field Access
using System;

public class Customer
{
   private int m_id = -1;

   public int GetID()
   {
       return m_id;
   }

   public void SetID(int id)
   {
       m_id = id;
   }

   private string m_name = string.Empty;

   public string GetName()
   {
       return m_name;
   }

   public void SetName(string name)
   {
       m_name = name;
   }
}

public class CustomerManagerWithAccessorMethods
{
   public static void Main()
   {
       Customer cust = new Customer();

       cust.SetID(1);
       cust.SetName("Amelio Rosales");

       Console.WriteLine(
           "ID: {0}, Name: {1}",
           cust.GetID(),
           cust.GetName());

       Console.ReadKey();
   }
}
Listing 10-1 shows the traditional method of accessing class fields. The Customer class has four properties, two for each private field that the class encapsulates: m_id and m_name. As you can see, SetID and SetName assign a new values and GetID and GetName return values.
Observe how Main calls the SetXxx methods, which sets m_id to 1 and m_name to "Amelio Rosales" in the Customer instance, cust. The call to Console.WriteLine demonstrates how to read m_id and m_name from cust, via GetID and GetName method calls, respectively.
This is such a common pattern, that C# has embraced it in the form of a language feature called properties, which you'll see in the next section.

Encapsulating Type State with Properties

The practice of accessing field data via methods was good because it supported the object-oriented concept of encapsulation. For example, if the type of m_id or m_namechanged from an int type to byte, calling code would still work. Now the same thing can be accomplished in a much smoother fashion with properties, as shown in Listing 10-2.
Listing 10-2. Accessing Class Fields With Properties
using System;

public class Customer
{
   private int m_id = -1;

   public int ID
   {
       get
       {
           return m_id;
       }
       set
       {
           m_id = value;
       }
   }

   private string m_name = string.Empty;

   public string Name
   {
       get
       {
           return m_name;
       }
       set
       {
           m_name = value;
       }
   }
}

public class CustomerManagerWithProperties
{
   public static void Main()
   {
       Customer cust = new Customer();

       cust.ID = 1;
       cust.Name = "Amelio Rosales";

 Console.WriteLine(
           "ID: {0}, Name: {1}",
           cust.ID,
           cust.Name);

       Console.ReadKey();
   }
}
Listing 10-2 shows how to create and use a property. The Customer class has the ID andName property implementations. There are also private fields named m_id and m_name;which ID and Name, respectively, encapsulate. Each property has two accessors, get andset. The accessor returns the value of a field. The set accessor sets the value of a field with the contents of value, which is the value being assigned by calling code. The valueshown in the accessor is a C# reserved word.
When setting a property, just assign a value to the property as if it were a field. TheCustomerManagerWithProperties class uses the ID and Name properties in the Customerclass. The first line of Main instantiates a Customer object named cust. Next the value of the m_id and m_name fields of cust are set by using the ID and Name properties.
To read from a property, use the property as if it were a field. Console.WriteLine prints the value of the m_id and m_name fields of cust. It does this by calling the ID and Nameproperties of cust.
This was a read/write property, but you can also create read-only properties, which you'll learn about next.

Creating Read-Only Properties

Properties can be made read-only. This is accomplished by having only a get accessor in the property implementation. Listing 10-3 demonstrates how you can create a read-only property.
Listing 10-3. Read-Only Properties
using System;

public class Customer
{
   private int m_id = -1;
   private string m_name = string.Empty;

   public Customer(int id, string name)
   {
       m_id = id;
       m_name = name;
   }

   public int ID
   {
       get
       {
           return m_id;
       }
   }

   public string Name
   {
       get
       {
           return m_name;
       }
   }
}

public class ReadOnlyCustomerManager
{
   public static void Main()
   {
       Customer cust = new Customer(1, "Amelio Rosales");

       Console.WriteLine(
           "ID: {0}, Name: {1}",
           cust.ID,
           cust.Name);

       Console.ReadKey();
   }
}
The Customer class in Listing 10-3 has two read-only properties, ID and Name. You can tell that each property is read-only because they only have get accessors. At some time, values for the m_id and m_name must be assigned, which is the role of the constructor in this example.
The Main method of the ReadOnlyCustomerManager class instantiates a new Customerobject named cust. The instantiation of cust uses the constructor of Customer class, which takes int and string type parameters. In this case, the values are 1 and "Amelio Rosales". This initializes the m_id and m_name fields of cust.
Since the ID and Name properties of the Customer class are read-only, there is no other way to set the value of the m_id and m_name fields. If you inserted cust.ID = 7 into the listing, the program would not compile, because ID is read-only; the same goes for Name. When the ID and Name properties are used in Console.WriteLine, they work fine. This is because these are read operations which only invoke the get accessor of the ID and Nameproperties.
One question you might have now is "If a property can be read-only, can it also be write-only?" The answer is yes, and explained in the next section.

Creating a Write-Only Property

You can assign values to, but not read from, a write-only property. A write-only property only has a set accessor. Listing 10-4 shows you how to create and use write-only properties.
Listing 10-4. Write-Only Properties
using System;

public class Customer
{
   private int m_id = -1;

   public int ID
   {
       set
       {
           m_id = value;
       }
   }

   private string m_name = string.Empty;

   public string Name
   {
       set
       {
           m_name = value;
       }
   }

   public void DisplayCustomerData()
   {
       Console.WriteLine("ID: {0}, Name: {1}", m_id, m_name);
   }
}

public class WriteOnlyCustomerManager
{
   public static void Main()
   {
       Customer cust = new Customer();

       cust.ID = 1;
       cust.Name = "Amelio Rosales";

       cust.DisplayCustomerData();

       Console.ReadKey();
   }
}
This time, the get accessor is removed from the ID and Name properties of the Customerclass, shown in Listing 10-1. The set accessors have been added, assigning value to the backing store fields, m_id and m_name.
The Main method of the WriteOnlyCustomerManager class instantiates the Customer class with a default constructor. Then it uses the ID and Name properties of cust to set the m_idand m_name fields of cust to 1 and "Amelio Rosales", respectively. This invokes the setaccessor of ID and Name properties from the cust instance.
When you have a lot of properties in a class or struct, there can also be a lot of code associated with those properties. In the next section, you'll see how to write properties with less code.

Creating Auto-Implemented Properties

The patterns you see here, where a property encapsulates a property with get and setaccessors, without any other logic is common. It is more code than we should have to write for such a common scenario. That's why C# 3.0 introduced a new syntax for a property, called an auto-implemented property, which allows you to create properties without getand set accessor implementations. Listing 10-5 shows how to add auto-implemented properties to a class.
Listing 10-5. Auto-Impemented Properties
using System;

public class Customer
{
   public int ID { get; set; }
   public string Name { get; set; }
}

public class AutoImplementedCustomerManager
{
   static void Main()
   {
       Customer cust = new Customer();

       cust.ID = 1;
       cust.Name = "Amelio Rosales";

       Console.WriteLine(
           "ID: {0}, Name: {1}",
           cust.ID,
           cust.Name);

       Console.ReadKey();
   }
}
Notice how the get and set accessors in Listing 10-5 do not have implementations. In an auto-implemented property, the C# compiler creates the backing store field behind the scenes, giving the same logic that exists with traditional properties, but saving you from having to use all of the syntax of the traditional property. As you can see in the Mainmethod, the usage of an auto-implemented property is exactly the same as traditional properties, which you learned about in previous sections.

C Sharp Tutorials/Lesson 11 Lesson 11: Indexers


This lesson teaches C# Indexers. Our objectives are as follows:
  • Understand What Indexers Are For.
  • Implement an Indexer.
  • Overload Indexers.
  • Understand How to Implement Multi-Parameter Indexers.
Indexers are real easy. They allow your class to be used just like an array. On the inside of a class, you manage a collection of values any way you want. These objects could be a finite set of class members, another array, or some complex data structure. Regardless of the internal implementation of the class, its data can be obtained consistently through the use of indexers. Here's an example.
Listing 11-1. An Example of An Indexer: IntIndexer.cs
using System;
/// 

/// A simple indexer example./// 

class IntIndexer
{
private string[] myData;
public IntIndexer(int size)
{
myData = 
new string[size];
for (int i=0; i < size; i++)
{
myData[i] = "empty";
}
}

public
 string this[int pos]
{
get
{return myData[pos];
}
set
{
myData[pos] = 
value;
}
}

static
 void Main(string[] args)
{
int size = 10;

IntIndexer myInd = 
new IntIndexer(size);

myInd[9] = "Some Value";
myInd[3] = "Another Value";
myInd[5] = "Any Value";

Console.WriteLine("\nIndexer Output\n");

for
 (int i=0; i < size; i++)
{
Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);
}
}
}
Listing 11-1 shows how to implement an Indexer. The IntIndexer class has a string array named myData. This is a private array that external users can't see. This array is initialized in the constructor, which accepts an int size parameter, instantiates the myData array, and then fills each element with the word "empty".
The next class member is the Indexer, which is identified by the this keyword and square brackets, this[int pos]. It accepts a single position parameter, pos. As you may have already guessed, the implementation of an Indexer is the same as a Property. It has get andset accessors that are used exactly like those in a Property. This indexer returns a string, as indicated by the string return value in the Indexer declaration.
The Main() method simply instantiates a new IntIndexer object, adds some values, and prints the results. Here's the output:
Indexer Output

myInd[0]: empty
myInd[1]: empty
myInd[2]: empty
myInd[3]: Another Value
myInd[4]: empty
myInd[5]: Any Value
myInd[6]: empty
myInd[7]: empty
myInd[8]: empty
myInd[9]: Some Value
Using an integer is a common means of accessing arrays in many languages, but the C# Indexer goes beyond this. Indexers can be declared with multiple parameters and each parameter may be a different type. Additional parameters are separated by commas, the same as a method parameter list. Valid parameter types for Indexers include integers,enums, and strings. Additionally, Indexers can be overloaded. In listing 11-2, we modify the previous program to accept overloaded Indexers that accept different types.
Listing 11-2. Overloaded Indexers: OvrIndexer.cs
using System;
/// 

/// Implements overloaded indexers./// 

class OvrIndexer
{
private string[] myData;private int arrSize;
public OvrIndexer(int size)
{
arrSize = size;
myData = 
new string[size];
for (int i=0; i < size; i++)
{
myData[i] = "empty";
}
}

public
 string this[int pos]
{
get
{return myData[pos];
}
set
{
myData[pos] = 
value;
}
}

public
 string this[string data]
{
get
{int count = 0;
for
 (int i=0; i < arrSize; i++)
{
if (myData[i] == data)
{
count++;
}
}
return count.ToString();
}
set
{for (int i=0; i < arrSize; i++)
{
if (myData[i] == data)
{
myData[i] = 
value;
}
}
}
}

static
 void Main(string[] args)
{
int size = 10;
OvrIndexer myInd = 
new OvrIndexer(size);

myInd[9] = "Some Value";
myInd[3] = "Another Value";
myInd[5] = "Any Value";

myInd["empty"] = "no value";

Console.WriteLine("\nIndexer Output\n");

for
 (int i=0; i < size; i++)
{
Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);
}

Console.WriteLine("\nNumber of \"no value\" entries: {0}", myInd["no value"]);
}
}
Listing 11-2 shows how to overload Indexers. The first Indexer, with the int parameter, pos, is the same as in Listing 11-1, but there is a new Indexer that takes a string parameter. The get accessor of the new indexer returns a string representation of the number of items that match the parameter value, data. The set accessor changes each entry in the array that matches the data parameter to the value that is assigned to the Indexer.
The behavior of the overloaded Indexer that takes a string parameter is demonstrated in the Main() method of Listing 11-2. It invokes the set accessor, which assigns the value of "no value" to every member of the myInd class that has the value of "empty". It uses the following command: myInd["empty"] = "no value";. After each entry of the myInd class is printed, a final entry is printed to the console, indicating the number of entries with the "no value" string. This happens by invoking the get accessor with the following code: myInd["no value"]. Here's the output:
Indexer Output

myInd[0]: no value
myInd[1]: no value
myInd[2]: no value
myInd[3]: Another Value
myInd[4]: no value
myInd[5]: Any Value
myInd[6]: no value
myInd[7]: no value
myInd[8]: no value
myInd[9]: Some Value

Number of "no value" entries: 7
The reason both Indexers in Listing 11-2 can coexist in the same class is because they have different signatures. An Indexer signature is specified by the number and type of parameters in an Indexers parameter list. The class will be smart enough to figure out which Indexer to invoke, based on the number and type of arguments in the Indexer call. An indexer with multiple parameters would be implemented something like this:
public object this[int param1, ..., int paramN]
{
get
{// process and return some class data
}
set
{
// process and assign some class data
}
}

C Sharp Tutorials/Lesson 12 Lesson 12: Structs


This lesson teaches C# Structs. Our objectives are as follows:
  • Understand the Purpose of structs.
  • Implement a struct.
  • Use a struct.
struct allows you to create new value-type objects that are similar to the built-in types (intfloatbool, etc.). When would you use a struct instead of a class? Think about how the built-in types are used. They have values and distinct operations to manipulate those values. If you have a need to create an object that behaves in this manner, consider implementing it as a struct. Later in this article, I'll explain a couple rules for using structs, which will give you a better idea of when to use them. In the meantime, here's an example.
Listing 12-1. Example of a struct: StructExample.cs
using System;
struct Point
{
public int x;public int y;
public
 Point(int x, int y)
{
this.x = x;this.y = y;
}

public
 Point Add(Point pt)
{
Point newPt;

newPt.x = x + pt.x;
newPt.y = y + pt.y;

return
 newPt;
}
}
/// 

/// Example of declaring and using a struct/// 

class StructExample
{
static void Main(string[] args)
{
Point pt1 = 
new Point(1, 1);
Point pt2 = 
new Point(2, 2);
Point pt3;

pt3 = pt1.Add(pt2);

Console.WriteLine("pt3: {0}:{1}", pt3.x, pt3.y);
}
}
Listing 12-1 shows how to declare and use a struct. It is easy to tell that a type is a structbecause of the keyword struct used in its definition. The basic layout of a struct is much like a class, but with differences, which will be explained in following paragraphs. The Pointstruct has a constructor which initializes its fields to the and y values passed in. It also has a method named Add(), which will accept another Point struct, add it to this struct, and return a new struct.
Notice that there is a Point struct declared in the Add() method. It does not need to be instantiated with a new operator, like a class. When this occurs, the struct is implicitly instantiated with its default (or parameterless) constructor. The parameterless constructor initializes all struct fields to default values. i.e. integrals are 0, floating points are 0.0, and booleans are false. It's illegal to define a parameterless constructor for a struct.
Although not required, a struct may be instantiated with a new operator. In Listing 12-1 thept1 and pt2 Point structs are initialized with values by using the constructor defined in thePoint struct. A third Point structpt3 is declared and defaults to using the parameterless (default) constructor, because it doesn't matter what it's value is at this point. The Add()method of the pt1 struct is then invoked, passing the pt2 struct as a parameter. The result is assigned to pt3, showing that a struct may be used just like any other value type. Here's the output from Listing 12-1:
 pt3: 3:3
Another difference between structs and classes is that structs can not have destructors. Also, structs cannot inherit another class or struct or be inherited from. However, a structmay implement multiple interfaces. An interface is a C# reference type with members that do not have implementations. Any class or struct implementing an interface must implement every one of that interface's methods. Interfaces are a subject for a later lesson.