String Formats

DATE TIME
How to format DateTime using String.Format method. All formatting can be done also using DateTime.ToString method.

Custom DateTime Formatting

There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).

Following examples demonstrate how are the format specifiers rewritten to the output.


// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year
String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month
String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24
String.Format("{0:m mm}", dt); // "5 05" minute
String.Format("{0:s ss}", dt); // "7 07" second
String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction
String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes
String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M.
String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone

You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeForma­tInfo.DateSepa­rator and DateTimeForma­tInfo.TimeSepa­rator.


// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)

Here are some examples of custom date and time formatting:


// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt); // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt); // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt); // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt); // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"

Standard DateTime Formatting

In DateTimeForma­tInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture.

Following table shows patterns defined in DateTimeForma­tInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.

Specifier DateTimeFormatInfo property Pattern value (for en-US culture)
t ShortTimePattern h:mm tt
d ShortDatePattern M/d/yyyy
T LongTimePattern h:mm:ss tt
D LongDatePattern dddd, MMMM dd, yyyy
f (combination of D and t) dddd, MMMM dd, yyyy h:mm tt
F FullDateTimePattern dddd, MMMM dd, yyyy h:mm:ss tt
g (combination of d and t) M/d/yyyy h:mm tt
G (combination of d and T) M/d/yyyy h:mm:ss tt
m, M MonthDayPattern MMMM dd
y, Y YearMonthPattern MMMM, yyyy
r, R RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s SortableDateTi­mePattern yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
u UniversalSorta­bleDateTimePat­tern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
(*) = culture independent

Following examples show usage of standard format specifiers in String.Format method and the resulting output.


String.Format("{0:t}", dt);  // "4:05 PM"                         ShortTime
String.Format("{0:d}", dt); // "3/9/2008" ShortDate
String.Format("{0:T}", dt); // "4:05:07 PM" LongTime
String.Format("{0:D}", dt); // "Sunday, March 09, 2008" LongDate
String.Format("{0:f}", dt); // "Sunday, March 09, 2008 4:05 PM" LongDate+ShortTime
String.Format("{0:F}", dt); // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt); // "3/9/2008 4:05 PM" ShortDate+ShortTime
String.Format("{0:G}", dt); // "3/9/2008 4:05:07 PM" ShortDate+LongTime
String.Format("{0:m}", dt); // "March 09" MonthDay
String.Format("{0:y}", dt); // "March, 2008" YearMonth
String.Format("{0:r}", dt); // "Sun, 09 Mar 2008 16:05:07 GMT" RFC1123
String.Format("{0:s}", dt); // "2008-03-09T16:05:07" SortableDateTime
String.Format("{0:u}", dt); // "2008-03-09 16:05:07Z" UniversalSortableDateTime

INTEGER
Integer numbers can be formatted in .NET in many ways. You can use static
method String.Format or instance method int.ToString. Following examples shows how to align numbers (with
spaces or zeroes), how to format negative numbers or how to do custom formatting
like phone numbers.

Add zeroes before number

To add zeroes before a number, use colon separator „:“ and write as many zeroes as you want.


String.Format("{0:00000}", 15); // "00015" String.Format("{0:00000}", -15); // "-00015"

Align number to the right or left

To align number to the right, use comma „,“ followed by a number of characters. This alignment option must be before the colon separator.


String.Format("{0,5}", 15); // " 15" String.Format("{0,-5}", 15); // "15 " String.Format("{0,5:000}", 15); // " 015" String.Format("{0,-5:000}", 15); // "015 "

Different formatting for negative numbers and zero

You can have special format for negative numbers and zero. Use semicolon separator „;“ to separate formatting to two or three sections. The second section is format for negative numbers, the third section is for zero.


String.Format("{0:#;minus #}", 15); // "15" String.Format("{0:#;minus #}", -15); // "minus 15" String.Format("{0:#;minus #;zero}", 0); // "zero"

Custom number formatting (e.g. phone number)

Numbers can be formatted also to any custom format, e.g. like phone numbers or serial numbers.


String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456" String.Format("{0:##-####-####}", 8958712551); // "89-5871-2551"

DOUBLE

The following examples show how to format float numbers to string in C#. You can use static method String.Format or instance methods double.ToString and float.ToString.

Digits after decimal point

This example formats double to string with fixed number of decimal places. For two decimal places use pattern „0.00“. If a float number has less decimal places, the rest digits on the right will be zeroes. If it has more decimal places, the number will be rounded.


// just two decimal places String.Format("{0:0.00}", 123.4567); // "123.46" String.Format("{0:0.00}", 123.4); // "123.40" String.Format("{0:0.00}", 123.0); // "123.00"

Next example formats double to string with floating number of decimal places. E.g. for maximal two decimal places use pattern „0.##“.


// max. two decimal places String.Format("{0:0.##}", 123.4567); // "123.46" String.Format("{0:0.##}", 123.4); // "123.4" String.Format("{0:0.##}", 123.0); // "123"

Digits before decimal point

If you want a float number to have any minimal number of digits before decimal point use N-times zero before decimal point. E.g. pattern „00.0“ formats a float number to string with at least two digits before decimal point and one digit after that.


// at least two digits before decimal point String.Format("{0:00.0}", 123.4567); // "123.5" String.Format("{0:00.0}", 23.4567); // "23.5" String.Format("{0:00.0}", 3.4567); // "03.5" String.Format("{0:00.0}", -3.4567); // "-03.5"

Thousands separator

To format double to string with use of thousands separator use zero and comma separator before an usual float formatting pattern, e.g. pattern „0,0.0“ formats the number to use thousands separators and to have one decimal place.


String.Format("{0:0,0.0}", 12345.67); // "12,345.7" String.Format("{0:0,0}", 12345.67); // "12,346"

Zero

Float numbers between zero and one can be formatted in two ways, with or without leading zero before decimal point. To format number without a leading zero use # before point. For example „#.0“ formats number to have one decimal place and zero to N digits before decimal point (e.g. „.5“ or „123.5“).

Following code shows how can be formatted a zero (of double type).


String.Format("{0:0.0}", 0.0); // "0.0" String.Format("{0:0.#}", 0.0); // "0" String.Format("{0:#.0}", 0.0); // ".0" String.Format("{0:#.#}", 0.0); // ""

Align numbers with spaces

To align float number to the right use comma „,“ option before the colon. Type comma followed by a number of spaces, e.g. „0,10:0.0“ (this can be used only in String.Format method, not in double.ToString method). To align numbers to the left use negative number of spaces.


String.Format("{0,10:0.0}", 123.4567); // " 123.5" String.Format("{0,-10:0.0}", 123.4567); // "123.5 " String.Format("{0,10:0.0}", -123.4567); // " -123.5" String.Format("{0,-10:0.0}", -123.4567); // "-123.5 "

Custom formatting for negative numbers and zero

If you need to use custom format for negative float numbers or zero, use semicolon separator;“ to split pattern to three sections. The first section formats positive numbers, the second section formats negative numbers and the third section formats zero. If you omit the last section, zero will be formatted using the first section.


String.Format("{0:0.00;minus 0.00;zero}", 123.4567); // "123.46" String.Format("{0:0.00;minus 0.00;zero}", -123.4567); // "minus 123.46" String.Format("{0:0.00;minus 0.00;zero}", 0.0); // "zero"

Some funny examples

As you could notice in the previous example, you can put any text into formatting pattern, e.g. before an usual pattern „my text 0.0“. You can even put any text between the zeroes, e.g. „0aaa.bbb0“.


String.Format("{0:my number is 0.0}", 12.3); // "my number is 12.3" String.Format("{0:0aaa.bbb0}", 12.3); // "12aaa.bbb3"


Align String with Spaces [C#]

This example shows how to align strings with spaces. The example formats text to table and writes it to console output.

To align string to the right or to the left use static method String.Format. To align string to the left (spaces on the right) use formatting patern with comma (,) followed by a negative number of characters: String.Format(„{0,–10}“, text). To right alignment use a positive number: {0,10}.

Following example shows how to format text to the table. Values in the first and second column are aligned to the left and the third column is aligned to the right.

[C#]
Console.WriteLine("-------------------------------"); Console.WriteLine("First Name | Last Name | Age"); Console.WriteLine("-------------------------------"); Console.WriteLine(String.Format("{0,-10} | {1,-10} | {2,5}", "Bill", "Gates", 51)); Console.WriteLine(String.Format("{0,-10} | {1,-10} | {2,5}", "Edna", "Parker", 114)); Console.WriteLine(String.Format("{0,-10} | {1,-10} | {2,5}", "Johnny", "Depp", 44)); Console.WriteLine("-------------------------------"); Output string:
------------------------------- First Name | Last Name | Age ------------------------------- Bill | Gates | 51 Edna | Parker | 114 Johnny | Depp | 44 -------------------------------

Indent String with Spaces [C#]

This example shows how to indent strings using method for padding in C#. To repeat spaces use method String.PadLeft. If you call „hello“.PadLeft(10) you will get the string aligned to the right: „ hello“. If you use empty string instead of the „hello“ string the result will be 10× repeated space character. This can be used to create simple Indent method.

The Indent method:

[C#]
public static string Indent(int count) { return "".PadLeft(count); }

Test code:

[C#]
Console.WriteLine(Indent(0) + "List"); Console.WriteLine(Indent(3) + "Item 1"); Console.WriteLine(Indent(6) + "Item 1.1"); Console.WriteLine(Indent(6) + "Item 1.2"); Console.WriteLine(Indent(3) + "Item 2"); Console.WriteLine(Indent(6) + "Item 2.1");

Output string:

List Item 1 Item 1.1 Item 1.2 Item 2 Item 2.1

How to prevent our .NET DLL from decompilation

Scenario: By design, .NET embeds rich Meta data inside the executable code using MSIL. Any one can
easily decompile your DLL back using tools like ILDASM (owned by Microsoft) or Reflector for
.NET which is a third party.
                Secondly, there are many third party tools, which make this
decompiling process int a single click. So any one can easily look in to your assemblies and reverse
engineer them back in to actual source code and understand some real good logic, which can
make it easy to crack your application.

Here the solution: You can stop this reverse engineering by using "obfuscation". It is a
technique, which will foil the decompilers. Many third parties (XenoCode, Demeanor for .NET)
provide .NET obfuscation solution. Microsoft includes one that is Dotfuscator Community
Edition with Visual Studio.NET.

Automatically adding namespace

Scenario: Consider that u want to use a class but u don't know under which namespace the class belong.
Here the solution: keep the cursor on the class that u r using and press 'Alt+Shift+F10' a new popup menu will occur which will show the namespace just click on the popup menu the name space will automatically added in the starting of ur code.

Example:
using System;
Regex clsReg = new Regex(); here Regex is a class which comes under System.Text.RegularExpressions namespace but u didnt include it in ur code

now keep the cursor on Regex and press alt+shit+F10 a popup menu will occur like the below image.









then click the using System.Text.RegularExpressions;
now u go and see the starting page of ur code.


Note: This technique will workout for all the built in classes also for the classes which are added in the reference.

IS IT POSSIBLE TO USE INNER JOIN QUERY IN A DATASET

Scenario: U have 2 tables in ur dataset with both the table contains a column name 'Samecolumn'
Table1: Samecolumn has the following 3 value
col1
col2
col3
Table2: Samecolumn has the following 2 value
col2
col3
Is it possible to query in the dataset to get the ouput of 2 rows i.e) col2, col3

Solution: No, There is no direct way to get the child rows
DataRelation and get joined rows, you will need to use the GetChildRows method of DataRow and pass the DataRelation object.
The following code example creates a DataRelation between the Customers
table and the Orders table of a DataSet and returns all the orders for each
customer.

Dim custOrderRel As DataRelation = custDataset.Relations.Add("CustOrders", _
custDS.Tables("Table1").Columns("Samecolumn"), _
custDS.Tables("Table2").Columns("Samecolumn"))

Dim custRow As DataRow
Dim orderRow As DataRow

For Each custRow in custDataset.Tables("Table1").Rows
Console.WriteLine(custRow("Samecolumn"))
For Each orderRow in custRow.GetChildRows(custOrderRel)
Console.WriteLine(orderRow("Samecolumn"))
Next
Next

Rare images

Find rowindex in dataset based on datarow, Set primary key to dataset

//To SETS THE DATASET PRIMARY KEY
DataCoulumn[] keys = new DataColumn[1];
keys[0] = DataSet.Tables["mytable"].Column["i_ID"];
DataSet.Tables["mytable"].PrimaryKey = keys;

// To Bind in THE DATAGRID VIEW
BindingManagerBase bm;
DataGridView1.DataSource = DataSet.Tables["mytable"].DefaultView;
bm = this.DataGridView1.BindingContext[this.DataGridView1.DataSource, this. DataGridView1.DataMember];

//You have a datarow and u need to find the rowindex of the row in dataset
DataRow findRow = DataSet.Tables["mytable"].Rows.Find(((DataRowView)bm.Current).Row[0]); // Row[0] is the collumn to seach in in this case ID column
int indexNumber = DataSet.Tables["mytable"].Rows.IndexOF(findRow);

 

Ping a machine using c#.net

Name space: using System.Net.NetworkInformation;
try
{
Ping oping = new Ping();
PingReply oReply = oping.Send(machineipaddress);
if (oReply.Status.ToString().ToLower() != "success")
{
MessageBox.Show("Unable to ping the machine " + machineipaddress + "\n\n\t" + oReply.Status);
Environment.Exit(0);
}
}
catch (PingException ex)
{
MessageBox.Show("Error while pinging the machine " + machineipaddress + "\n\n" + ex.Message);
Environment.Exit(0);
}

.net windows forms interview question

  1. Can you write a class without specifying namespace? Which namespace does it belong to by default??
    Yes, you can, then the class belongs to global namespace which has no name. For commercial products, naturally, you wouldn't want global namespace.
  2. You are designing a GUI application with a window and several widgets on it. The user then resizes the app window and sees a lot of grey space, while the widgets stay in place. What's the problem? One should use anchoring for correct resizing. Otherwise the default property of a widget on a form is top-left, so it stays at the same location when resized.
  3. How can you save the desired properties of Windows Forms application? .config files in .NET are supported through the API to allow storing and retrieving information. They are nothing more than simple XML files, sort of like what .ini files were before for Win32 apps.
  4. So how do you retrieve the customized properties of a .NET application from XML .config file? Initialize an instance of AppSettingsReader class. Call the GetValue method of AppSettingsReader class, passing in the name of the property and the type expected. Assign the result to the appropriate variable.
  5. Can you automate this process? In Visual Studio yes, use Dynamic Properties for automatic .config creation, storage and retrieval.
  6. My progress bar freezes up and dialog window shows blank, when an intensive background process takes over. Yes, you should've multi-threaded your GUI, with taskbar and main form being one thread, and the background process being the other.
  7. What's the safest way to deploy a Windows Forms app? Web deployment: the user always downloads the latest version of the code; the program runs within security sandbox, properly written app will not require additional security privileges.
  8. Why is it not a good idea to insert code into InitializeComponent method when working with Visual Studio? The designer will likely throw it away; most of the code inside InitializeComponent is auto-generated.
  9. What's the difference between WindowsDefaultLocation and WindowsDefaultBounds? WindowsDefaultLocation tells the form to start up at a location selected by OS, but with internally specified size. WindowsDefaultBounds delegates both size and starting position choices to the OS.
  10. What's the difference between Move and LocationChanged? Resize and SizeChanged? Both methods do the same, Move and Resize are the names adopted from VB to ease migration to C#.
  11. How would you create a non-rectangular window, let's say an ellipse? Create a rectangular form, set the TransparencyKey property to the same value as BackColor, which will effectively make the background of the form transparent. Then set the FormBorderStyle to FormBorderStyle.None, which will remove the contour and contents of the form.
  12. How do you create a separator in the Menu Designer? A hyphen '-' would do it. Also, an ampersand '&\' would underline the next letter.
  13. How's anchoring different from docking? Anchoring treats the component as having the absolute size and adjusts its location relative to the parent form. Docking treats the component location as absolute and disregards the component size. So if a status bar must always be at the bottom no matter what, use docking. If a button should be on the top right, but change its position with the form being resized, use anchoring.

 

Asp.net interview Questions

1.      Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process. inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension),the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.

2.      What's the difference between Response.Write() andResponse.Output.Write()? The latter one allows you to write formattedoutput.

3.      What methods are fired during the page load? Init() - when the pageis instantiated, Load() - when the page is loaded into server memory,PreRender() - the brief moment before the page is displayed to the user asHTML, Unload() - when page finishes loading.

4.      Where does the Web page belong in the .NET Framework class hierarchy?System.Web.UI.Page

5.      Where do you store the information about the user's locale? System.Web.UI.Page.Culture

6.      What's the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"? CodeBehind is relevant to Visual Studio.NET only.

7.      What's a bubbled event? When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.

8.      Suppose you want a certain ASP.NET function executed on MouseOver overa certain button. Where do you add an event handler? It's the Attributesproperty, the Add function inside that property. So btnSubmit.Attributes.Add("onMouseOver","someClientCode();")

9.      What data type does the RangeValidator control support? Integer,String and Date.

10.  Explain the differences between Server-side and Client-side code?  Server-side code runs on the server. Client-side code runs in the clients' browser.

11.  What type of code (server or client) is found in a Code-Behind class? Server-side code.

12.  Should validation (did the user enter a real date) occur server-side or client-side? Why? Client-side. This reduces an additional request to the server to validate the users input.

13.  What does the "EnableViewState" property do? Why would I want it on or off?  It enables the viewstate on the page. It allows the page to save the users input on a form.

14.  What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other? Server.Transfer is used to post a form to another page. Response.Redirect is used to redirect the user to another page or site.

15.  Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?

·         A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.

·         A DataSet is designed to work without any continuing connection to the original data source.

·         Data in a DataSet is bulk-loaded, rather than being loaded on demand.

·         There's no concept of cursor types in a DataSet.

·         DataSets have no current record pointer You can use For Each loops to move through the data.

·         You can store many edits in a DataSet, and write them to the original data source in a single operation.

·         Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.

16.  Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?  This is where you can set the specific variables for the Application and Session objects.

17.  If I'm developing an application that must accommodate multiple security levels though secure login and my ASP.NET web application is spanned across three web-servers (using round-robin load balancing) what would be the best approach to maintain login-in state for the users? Maintain the login state security through a database.

18.  Can you explain what inheritance is and an example of when you might use it? When you want to inherit (use the functionality of) another class. Base Class Employee. A Manager class could be derived from the Employee base class.

19.  Whats an assembly?  Assemblies are the building blocks of the .NET framework. Overview of assemblies from MSDN

20.  Describe the difference between inline and code behind. Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.

21.  Explain what a diffgram is, and a good use for one? The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. For reading database data to an XML file to be sent to a Web Service.

22.  Whats MSIL, and why should my developers need an appreciation of it if at all? MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL.

23.  Which method do you invoke on the DataAdapter control to load your generated dataset with data? The .Fill() method

24.  Can you edit data in the Repeater control?  No, it just reads the information from its data source

25.  Which template must you provide, in order to display data in a Repeater control? ItemTemplate

26.  How can you provide an alternating color scheme in a Repeater control? Use the AlternatingItemTemplate

27.  What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control? You must set the DataSource property and call the DataBind method.

28.  What base class do all Web Forms inherit from?  The Page class.

29.  Name two properties common in every validation control? ControlToValidate property and Text property.

30.  What tags do you need to add within the asp:datagrid tags to bind columns manually? Set AutoGenerateColumns Property to false on the datagrid tag

31.  What tag do you use to add a hyperlink column to the DataGrid? <asp:HyperLinkColumn>

32.  What is the transport protocol you use to call a Web service? SOAP is the preferred protocol.

33.  True or False: A Web service can only be written in .NET? False

34.  What does WSDL stand for? (Web Services Description Language)

35.  Where on the Internet would you look for Web services? (http://www.uddi.org)

36.  Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box? DataTextField property

37.  Which control would you use if you needed to make sure the values in two different controls matched?  CompareValidator Control

38.  True or False: To test a Web service you must create a windows application or Web application to consume this service? False, the webservice comes with a test page and it provides HTTP-GET method to test.

39.  How many classes can a single .NET DLL contain?  It can contain many classes.

C# interview Questions

  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.

 

Useful C# for interview point II

within a class:
main must be a static method
In a static class we cant able to declare non static methods
In a non static class we can able to declare static methods
From a static method we cant able to call non static method. if need use an object for that class
From a non static method we can able to call static method
Two Non static classes:
From a non static method we cant call a non static method. need to create object for the class
From a non static method we cant call a static method. only able by using class name and dot(.)
From a static method we cant call a static method. only able by using class name and dot(.)
From a static method we cant call a non static method. need to create object for the class
Two static classes:
Cant able to create object for classs
From a static method we can call a static method. only able by using class name and dot(.)

Cant able to override non virtual or static methods
Cant able to create instance for interface or abstact class
you can use a cast to create an instance for an interface in C#
Cant able to inherit abstract method but able abstract class
Cant able to derive a sealed class
interface has only method declaration bcoz all method in interface are public and abstaract, Abstract method does not have any body
Abstract class have both abstract and nonabstract methodes.so those abstract methods only have declaration and non ablstract method have body also.
All abstract methods must implemented while using the abstract class or interface
Non abstract class doesnot contain abstract method
Boxing:
Value type to object type-implicit-compiler will do
unboxing
object type to value type-explicit-using type cast
We can override the base class method from deri class, only if the the base class method is virtual or abstract

Unlike base classes, interfaces don't implement any of their members by providing the actual code for properties, methods, and so on. Interfaces are just specifications for those members, and if your class implements an interface, it must provide code for all the members of that interface.
Delegates let you pass methods as parameters. They provide you with another form of polymorphism, because you can assign methods to delegates at runtime, leaving the rest of your code unchanged but calling the methods you specify at runtime.
No special impact for the delegate on static methods
BufferedStream object, which will use its own internal buffer to maximize performance

we've simply read data from a file and waited for the read operation to finish before doing anything. As we start working with network I/O, where things can be a lot slower, it won't be as easy to wait for reading and writing operations to complete. For that reason, the .NET Framework supports asynchronous I/O through the BeginRead and BeginWrite methods of the Stream class. You can call BeginRead to read a bufferfull of data, or BeginWrite to write a bufferfull of data, and then go on to do other work

C# enables you to save an entire object, including all its data (called an object-graph) through a process called serialization. Serialization lets you write entire objects out to disk and read them back in later. Objects that pass between assembly boundaries (through a process called marshalling) are also serialized.

The common language runtime does not support static variables in methods.

You don't have to serialize all the members of an object; for example, if you have a huge array filled with sequential numbers that's easy to re-create, there's no benefit to taking up a great deal of disk space by storing that array to memory. To mark members that you don't want serialized, you use the [NonSerialized] attribute.
if you didn't want to serialize the data array in ch05_13.cs, you could mark it with [NonSerialized]; note that when you use this attribute, you should implement the IDeserializationCallback interface,

Isolated storage saves data for your application that you might have stored in the Registry before.To store data in isolated storage, you use the IsolatedStorageFileStream class;(used to store configuration data)

You can also create arrays of arrays, called jagged arrays because they need not be rectangular.Here's the syntax you use to create an array of arrays.

Answer: Web services are programmable business logic components that provide access to functionality through the Internet. Standard protocols like HTTP can be used to access them. Web services are based on the Simple Object Access Protocol (SOAP), which is an application of XML. Web services are given the .asmx extension..

out and ref are reference type diff is ref must initialize.but out does not must be initialized

Eval is used for unidirectional (readonly) data binding, while Bind is for bi-directional (editable) databinding.

The Eval method is a static (read-only) method that takes the value of a data field and returns it as a string. The Bind method supports read/write functionality with the ability to retrieve the values of data-bound controls and submit any changes made back to the database.

DataSet is just a collection of DataTable objects

DataSet is an in-memory representation of data, containing one or more DataTables. A DataTable is an in-memory representation of data, typically retrieved from a database or XML source.
A DataView is a view onto an in-memory representation of data held in a DataTable.

Useful C# for interview point

Note that because static methods are not part of an object, you cannot use the this keyword
in such methods. It's important to know that static methods cannot directly access non-static
members (which means, for example, that you cannot call a non-static method from a static
method). Instead, they must instantiate an object and use the members of that object to
access non-static members .

Static constructors are called before any objects(constructor) are created from your class

what's the difference between new and override? You use new when you're replacing a
base class method with the same signature, and you use override when you're customizing it
in the current class.

Power of the DataView

The Power of the DataView


Introduction

Its hard to imagine what the creators of ADO.NET were thinking as they were designing it. It has been challenge enough just understanding and mastering all of the many objects and their capabilities. Just think, to physically access a column of data you have to now maneuver through at least five objects instead of two in ADO.

As part of my effort to learn ADO.NET, I decided to first determine how to reproduce the basic functionality that I had in ADO, especially with the Recordset. That is where I discovered the new and many uses of the DataView class (although I prefer the term object to class).

Think about the following code snippet:

objRS.Sort = "CompanyName"
objRS.Filter = "Country = " & strCountry
If Not objRS.EOF Then
Do Until objRS.EOF
...
ObjRS.MoveNext
Loop
End If
objRS.Filter = 0
objRS.Sort = ""

If the Recordset was the order detail for a customer, the sort order was specified on OrderNumber followed by ProductName. Then we used the marvelous Filter method of the Recordset to create a view of only those records we wished to work with. After we were through, we removed both the sort and the filter to perform any other tasks that were necessary.

When I first started working with ADO.NET, I just couldnt seem to figure out how to easily reproduce this functionality. Sure, you can bind a DataSet to a grid with just two lines of code. But where were examples of how to perform tasks where I needed more than just databinding to a DataTable? Thats when I stumbled across the DataView class.

I like to use the following analogy. DataSets are very much like simple, stand-alone databases. They contain tables called DataTables with rows and columns. These tables can have relationships. They also contain views called DataViews. The DataView class is very similar to a database view that you would create in Oracle or SQL Server. You can use a DataView just about anywhere you can use a DataTable. Yet they contain some additional properties and methods that a DataTable does not.

Sorting, Finding and Filtering

Three of the most useful things that you can do with a DataView are sorting, finding specific rows and filtering unwanted records. If I could do these things with a view, then I could reproduce the code snippet above using ADO.NET:

Dim dv As DataView
dv = New DataView(DataSet1.Tables("Customers"))
dv.Sort = "CompanyName"
dv.RowFilter = "Country = " & strCountry

At this point you can either Bind the view to one of the ASP.NET server side controls or you can process each row individually:

Dim i As Integer
For i = 0 To dv.count - 1
' perform your logic here
Next

In ADO.NET, there is no MoveFirst, MoveNext, MovePrior or MoveLast. Nor is there EOF or BOF. The data is all referenced as an array. To see if data is present, just check the Count property of the DataView (no more EOF runtime errors!). Remember that arrays begin at 0 and not 1.

If you want to filter rows with null values, you must first convert the null values to something such as a string:

dv.RowFilter = "Isnull(Col1,'Null') = 'Null'"

Only the Tip of the Iceberg

DataViews are also useful for other things than just the functions that we just discussed. Think about this: Every table has at least one DataView, which is a view of itself. This is called the DefaultView. That means that if you reference a table by its DefaultView, it can do anything a DataView can do as well:

DataSet1.Tables(0).DefaultView.Sort = "CompanyName"
DataSet1.Tables(0).DefaultView.RowFilter = "Country = " & strCountry
MyDataGrid.DataSource = DataSet1.Tables(0).DefaultView
MyDataGrid.DataBind()

Another great feature of DataViews is that you can create them with the RowFilter and Sort already specified:

Dim dv As New DataView(ds.Tables("Country"), _
"Country = 'UK'", _
"CompanyName", _
DataRowViewState.CurrentRows)

DataView Differences

Of course, the DataView is not a DataTable. The most obvious difference is that DataViews are comprised of DataRowViews where as a table contains DataRows. DataRowViews do not contain a Columns collection, but an Item property to reference the underlying column. And editing data in a DataRowView is also different. But there is one trick that you can play on the DataRowView. Just like every table has a DefaultDataView property, the DataRowView has a Row property that is an actual reference to the underlying DataRow:

Dim drv As DataRowView
For Each drv In dv
Response.Write(drv.Rows("CompanyName") & "<br>")
Next drv

Conclusion

As you can see, this is just one of the many areas where ADO.NET differs dramatically from ADO. Now that Ive discovered the DataView, Ive been able to reproduce the functionality that was in my old ASP application in my new ASP.NET applications. And with a little more practice, I hope to even overcome obstacles that were present with the Recordset.

Generics

What Are Generics?

Generics allow you to realize type safety at compile time. They allow you to create a data structure without committing to a specific data type. When the data structure is used, however, the compiler makes sure that the types used with it are consistent for type safety. Generics provide type safety, but without any loss of performance or code bloat. While they are similar to templates in C++ in this regard, they are very different in their implementation.

Using Generics Collections

The System.Collections.Generics namespace contains the generics collections

Y Generics

ex:

List<int> aList = new List<int>();
aList.Add(3);
aList.Add(4);
aList.Add(5.0);
int total = 0;
foreach(int val in aList)
{
total = total + val;
}
This will cause an compiler error bcoz not able to cast the double5.0 to integer
But the same was handled as error at runtime while using arraylist.

CLR Support for Generics



Generics is not a mere language-level feature. The .NET CLR recognizes generics. In
that regard, the use of generics is a first-class feature in .NET. For each type of parameter used for
a generic, a class is not rolled out in the Microsoft Intermediate Language (MSIL). In
other words, your assembly contains only one definition of your parameterized data
structure or class, irrespective of how many different types are used for that parameterized
type. For instance, if you define a generic type MyList, only one definition of that
type is present in MSIL. When the program executes, different classes are dynamically created,
one for each type for the parameterized type. If you use MyList and
MyList, then two classes are created on the fly when your program executes.



Writing a generic class




//MyList.cs
#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace CLRSupportExample
{
public class MyList
{
private static int objCount = 0;

public MyList()
{
objCount++;
}

public int Count
{
get
{
return objCount;
}
}
}
}

//Program.cs
#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace CLRSupportExample
{
class SampleClass {}

class Program
{
static void Main(string[] args)
{
MyList myIntList = new MyList();
MyList myIntList2 = new MyList();

MyList myDoubleList
= new MyList();

MyList mySampleList
= new MyList();

Console.WriteLine(myIntList.Count);
Console.WriteLine(myIntList2.Count);
Console.WriteLine(myDoubleList.Count);
Console.WriteLine(mySampleList.Count);
Console.WriteLine(
new MyList().Count);

Console.ReadLine();
}
}
}


I have created a generic class named MyList. To parameterize it, I simply inserted an angle
bracket. The T within <> represents the actual type that will be specified when the
class is used. Within the MyList class, I have a static field, objCount. I am incrementing this
within the constructor so I can find out how many objects of that type are created by the
user of my class. The Count property returns the number of instances of the same type as
the instance on which it is called.



In the Main() method, I am creating two instances of MyList, one instance of
MyList, and two instances of MyList, where
SampleClass is a
class I have defined. The question is: what will be the value of Count? That is, what is the
output from the above program? Go ahead and think on this and try to answer this
question before you read further.



Have you worked the above question? Did you get the following answer?




2
2
1
1
2

Generics Methods



In addition to having generic classes, you may also have generic methods. Generic methods
may be part of any class. Let's look at Example 4:



Example 4. A generic method




public class Program
{
public static void Copy(List source, List destination)
{
foreach (T obj in source)
{
destination.Add(obj);
}
}

static void Main(string[] args)
{
List lst1 = new List();
lst1.Add(2);
lst1.Add(4);

List lst2 = new List();
Copy(lst1, lst2);
Console.WriteLine(lst2.Count);
}
}


The Copy() method is a generic method that works with the parameterized type T.
When Copy() is invoked in Main(), the compiler figures out the specific
type to use, based on the arguments presented to the Copy() method.



Unbounded Type Parameters



If you create generics data structures or classes, like MyList in Example 3, there are no
restrictions on what type the parametric type you may use for the parameteric type. This
leads to some limitations, however. For example, you are not allowed to use
==, !=, or < on instances of the parametric type:




if (obj1 == obj2) …


The implementation of operators such as == and != are different for value types and
reference types. The behavior of the code may not be easier to understand if these were
allowed arbitrarily. Another restriction is the use of default constructor. For instance, if
you write new T(), you will get a compilation error, because not all classes have a
no-parameter constructor. What if you do want to create an object using new T(), or you
want to use operators such as == and !=? You can, but first you have to constraint the type
that can be used for the parameterized type. Let's look at how to do that.



Constraints and Their Benefits



A generic class allows you to write your class without committing to any type, yet allows
the user of your class, later on, to indicate the specific type to be used. While this
gives greater flexibility by placing some constraints on the types that may be used for
the parameterized type, you gain some control in writing your class. Let's look at an example:



Example 5. The need for constraints: code that will not compile




public static T Max(T op1, T op2)
{
if (op1.CompareTo(op2) <>


The code in Example 5 will produce a compilation error:




Error 1 'T' does not contain a definition for 'CompareTo'


Assume I need the type to support the CompareTo() method. I can specify
this by using the constraint that the type specified for the parameterized type must implement the
IComparable interface. Example 6 has the code:



Example 6. Specifying a constraint




public static T Max(T op1, T op2) where T : IComparable
{
if (op1.CompareTo(op2) <>


In Example 6, I have specified the constraint that the type used for
parameterized type must inherit from (implement) IComparable.
The following constraints may be used:




where T : struct type must be a value type (a struct)
where T : class type must be reference type (a class)
where T : new() type must have a no-parameter constructor
where T : class_name type may be either class_name or one of its
sub-classes (or is below class_name
in the inheritance hierarchy)
where T : interface_name type must implement the specified interface


You may specify a combination of constraints, as in: where T : IComparable, new().
This says that the type for the parameterized type must implement the
IComparable interface and must have a no-parameter constructor.



Inheritance and Generics



A generic class that uses parameterized types, like MyClass1, is called
an open-constructed generic. A generic class that uses no parameterized types,
like MyClass1, is called a closed-constructed generic.



You may derive from a closed-constructed generic; that is, you may inherit a class
named MyClass2 from another class named MyClass1, as in:




public class MyClass2 : MyClass1


You may derive from an open-constructed generic, provided the type is parameterized.
For example:




public class MyClass2 : MyClass2


is valid, but




public class MyClass2 : MyClass2


is not valid, where Y is a parameterized type. Non-generic classes may derive from closed-constructed
generic classes, but not from open-constructed generic classes. That is,




public class MyClass : MyClass1


is valid, but




public class MyClass : MyClass1


is not.


Generics' Limitations

We have seen the power of generics so far in this article. Are there any limitations? There is one significant limitation, which I hope Microsoft addresses. In expressing constraints, we can specify that the parameter type must inherit from a class. How about specifying that the parameter must be a base class of some class? Why do we need that?

In Example 4, I showed you a Copy() method that copied contents of a source List to a destination list. I can use it as follows:

List appleList1 = new List(); List appleList2 = new List(); … Copy(appleList1, appleList2);

However, what if I want to copy apples from one list into a list of Fruits (where Apple inherits from Fruit). Most certainly, a list of Fruits can hold Apples. So I want to write:

List appleList1 = new List(); List fruitsList2 = new List(); … Copy(appleList1, fruitsList2);

This will not compile. You will get an error:

Error 1 The type arguments for method 'TestApp.Program.Copy(System.Collections.Generic.List, System.Collections.Generic.List)' cannot be inferred from the usage.

The compiler, based on the call arguments, is not able to decide what T should be. What I really want to say is that the Copy should accept a List of some type as the first parameter, and a ListList of its base type as the second parameter. of the same type or a

Even though there is no way to say that a type must be a base type of another, you can get around this limitation by still using the constraints. Here is how:

public static void Copy(List source, List destination) where T : E

Here I have specified that the type T must be the same type as, or a sub-type of, E. We got lucky with this. Why? Both T and E are being defined here. We were able to specify the constraint (though the C# specification discourages using E to define the constraint of T when E is being defined as well).

Consider the following example, however:

public class MyList { public void CopyTo(MyList destination) { //… } }

I should be able to call CopyTo:

MyList appleList = new MyList(); MyList appleList2 = new MyList(); //… appleList.CopyTo(appleList2);

I must also be able to do this:

MyList appleList = new MyList(); MyList fruitList2 = new MyList(); //… appleList.CopyTo(fruitList2);

This, of course, will not work. How can we fix this? We need to say that the argument to CopyTo()MyList of some type or MyList of the base type of that type. However, the constraints do not allow us to specify the base type. How about the following? can be either

public void CopyTo(MyList destination) where T : E

Sorry, this does not work. It gives a compilation error that:

Error 1 'TestApp.MyList.CopyTo()' does not define type parameter 'T'

Of course, you may write the code to accept MyList of any arbitrary type and then within your code, you may verify that the type is one of acceptable type. However, this pushes the checking to runtime, losing the benefit of compile-time type safety.

Conclusion

Generics in .NET 2.0 are very powerful. They allow you to write code without committing to a particular type, yet your code can enjoy type safety. Generics are implemented in such a way as to provide good performance and avoid code bloat. While there is the drawback of constraints' inability to specify that a type must be a base type of another type, the constraints mechanism gives you the flexibility to write code with a greater degree of freedom than sticking with the least-common-denominator capability of all types.

Listen to nirmaln - sakara - playlist audio songs at MusicMazaa.com