C#faq

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View C#faq as PDF for free.

More details

  • Words: 15,112
  • Pages: 34
C# FAQ Contents •

1. Introduction o 1.1 What is C#? o 1.2 How do I develop C# apps? o 1.3 Where can I download the .NET SDK & Visual Studio.NET? o 1.4 Does C# replace Java? o 1.5 Does C# replace C++? o 1.6 What does a simple C# program look like? o 1.7 Is C# object-oriented? o 1.8 Does C# have its own class library?



2. Basic types o 2.1 What standard types does C# supply? o 2.2 Is it true that all C# types derive from a common base class? o 2.3 So this means I can pass an instance of a value type to a methodthat takes an object as a parameter? o 2.4 What are the fundamental differences between value types andreference types? o 2.5 Okay, so an int is a value type, and a class is areference type. How can int be derived from object? o 2.6 C# uses references instead of pointers. Are C# references the sameas C++ references?



3. Classes and structs o 3.1 Structs are largely redundant in C++. Why does C# have them? o 3.2 Does C# support multiple inheritance (MI)? o 3.3 Is a C# interface the same as a C++ abstract class? o 3.4 Are C# constructors the same as C++ constructors? o 3.5 Are C# destructors the same as C++ destructors? o 3.6 If C# destructors are so different to C++ destructors, why did MSuse the same syntax? o 3.7 What is a static constructor? o 3.8 Are all methods virtual in C#? o 3.9 How do I declare a pure virtual function in C#?



4. Exceptions o 4.1 Can I use exceptions in C#? o 4.2 What types of object can I throw as exceptions? o 4.3 Can I define my own exceptions? o 4.4 Are there any standard exceptions that I can re-use? o 4.5 Does the System.Exception class have any cool features? o 4.6 When should I throw an exception? o 4.7 Does C# have a 'throws' clause?



5. Run-time type information o 5.1 How can I check the type of an object at runtime? o 5.2 Can I get the name of a type at runtime?



6. Advanced language features o 6.1 What are delegates? o 6.2 Are delegates just like interfaces with a single method? o 6.3 What is the C# equivalent of QueryInterface?



7. It doesn't work like that in C++ ... o 7.1 I 'new'-ed an object, but how do I delete it? o 7.2 I tried to create an object on the stack, but the C# compilercomplained. What's going on? o 7.3 I defined a destructor, but it never gets called. Why? o 7.4 Most of the C# basic types have the same names as C++ basic types?Are they the same?



8. Miscellaneous

o o o o o o •

8.1 String comparisons using == seem to be case-sensitive? How do I doa case-insensitive string comparison? 8.2 I've seen some string literals which use the @ symbol, and somewhich don't. What's that all about? 8.3 Does C# support a variable number of arguments? 8.4 How can I process command-line arguments? 8.5 Does C# do array bounds checking? 8.6 How can I make sure my C# classes will interoperate with other .NETlanguages?

9. Resources o 9.1 Recommended books o 9.2 Internet Resources o 9.3 Sample code and utilities o

1. Introduction 1.1 What is C#? C# is a programming language designed by Microsoft. It is loosely based on C/C++, and bears a striking similarity to Java in many ways. Microsoft describe C# as follows: "C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C# (pronounced 'C sharp') is firmly planted in the C and C++ family tree of languages, and will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++." 1.2 How do I develop C# apps? The (free) .NET SDK contains the C# command-line compiler (csc.exe). Visual Studio.NET has fully integrated support for C# development. 1.3 Where can I download the .NET SDK & Visual Studio.NET? You can download the SDK from http://www.microsoft.com/net. If you are an MSDN Universal subscriber, you can also download Visual Studio.NET. 1.4 Does C# replace Java? C# is a very Java-like language - the core of both languages have similar advantages and limitations when compared to C++. For example, both languages have garbage collection, but neither language has templates. Microsoft have ceased production of Visual J++, so it's hard not to view C# as Microsoft's alternative to Java. 1.5 Does C# replace C++? The obvious answer is no. However it's difficult to see C++ as the best choice for new .NET code. For the .NET runtime to function fully, it requires the programming language to conform to certain rules - one of these rules is that language types must conform to the Common Type System (CTS). Unfortunately many C++ features are not supported by the CTS - for example multiple inheritance of classes and templates. Microsoft's answer to this problem is to offer Managed Extensions (ME) for C++, which allows you to write C++ that conforms to the CTS. New keywords are provided to mark your C++ classes with CTS attributes (e.g. __gc for garbage collection). However, it's difficult to see why ME C++ would be chosen over C# for new projects. In terms of features they are very similar, but unlike C++, C# has been designed from the ground-up to work seamlessly with the .NET environment. The raison d'etre for ME C++ would therefore appear to be porting existing C++ code to the .NET environment. So, in answer to the question, my suspicion is that C++ will remain an important language outside of the .NET environment, and will be used (via ME) to port existing code to .NET, but I think C# will become the language of choice for one-time C++ developers developing new .NET applications. But only time will tell ... 1.6 What does a simple C# program look like? Sorry, my imagination has deserted me. Yes, you guessed it, here comes 'Hello, world' ... class CApplication { public static void Main() { System.Console.Write( "Hello, new .NET world." ); } } (No, you can't put Main() as a global function - global functions don't exist in C#.)

1.7 Is C# object-oriented? Yes, C# is an OO language in the tradition of Java and C++. 1.8 Does C# have its own class library? Not exactly. In common with all .NET languages (e.g. VisualBasic.NET, JScript.NET) C# has access to the .NET class library. C# does not have its own class library.

2. Basic types 2.1 What standard types does C# supply? C# supports a very similar range of basic types to C++, including int, long, float, double, char, string, arrays, structs and classes. However, don't assume too much. The names may be familiar, but some of the details are different. For example, a long is 64 bits in C#, whereas in C++ the size of a long depends on the platform (typically 32 bits on a 32bit platform, 64 bits on a 64-bit platform). Also classes and structs are almost the same in C++ - this is not true for C#. 2.2 Is it true that all C# types derive from a common base class? Yes and no. All types can be treated as if they derive from object (System.Object), but in order to treat an instance of a value type (e.g. int, float) as object-derived, the instance must be converted to a reference type using a process called 'boxing'. In theory a developer can forget about this and let the run-time worry about when the conversion is necessary, but in reality this implicit conversion can have side-effects that may trip up the unwary. 2.3 So this means I can pass an instance of a value type to a methodthat takes an object as a parameter? Yes. For example: class CApplication { public static void Main() { int x = 25; string s = "fred"; DisplayMe( x ); DisplayMe( s ); } static void DisplayMe( object o ) { System.Console.WriteLine( "You are {0}", o ); } } This would display: You are 25 You are fred 2.4 What are the fundamental differences between value types andreference types? C# divides types into two categories - value types and reference types. Most of the basic intrinsic types (e.g. int, char) are value types. Structs are also value types. Reference types include classes, interfaces, arrays and strings. The basic idea is straightforward - an instance of a value type represents the actual data (stored on the stack), whereas an instance of a reference type represents a pointer or reference to the data (stored on the heap). The most confusing aspect of this for C++ developers is that C# has predetermined which types will be represented as values, and which will be represented as references. A C++ developer expects to take responsibility for this decision. For example, in C++ we can do this: int x1 = 3; // x1 is a value on the stack int *x2 = new int(3) // x2 is a reference to a value on the heap but in C# there is no control: int x1 = 3; // x1 is a value on the stack int x2 = new int(); x2 = 3; // x2 is also a value on the stack! 2.5 Okay, so an int is a value type, and a class is areference type. How can int be derived from object? It isn't, really. When an int is being used as an int, it is a value (on the stack). However, when it is being used as an object, it is a reference to an integer value on the heap. In other words, when you treat an int as an object, the

runtime automatically converts the int value to an object reference. This process is called boxing. The conversion involves copying the contents of the int from the stack to the heap, and creating an object instance which refers to it. Unboxing is the reverse process - the object is converted back to a stack-based value. int x = 3; // new int value 3 on the stack object objx = x; // new int on heap, set to value 3 - still have x=3 on stack int y = (int)objx; // new value 3 on stack, still got x=3 on stack and objx=3 on heap 2.6 C# uses references instead of pointers. Are C# references the sameas C++ references? Not quite. The basic idea is the same, but one significant difference is that C# references can be null . So you cannot rely on a C# reference pointing to a valid object. If you try to use a null reference, a NullReferenceException is thrown. For example, look at the following method: void displayStringLength( string s ) { Console.WriteLine( "String is length {0}", s.Length ); } The problem with this method is that it will throw a NullReferenceException if called like this: string s = null; displayStringLength( s ); Of course for some situations you may deem a NullReferenceException to be a perfectly acceptable outcome, but in this case it might be better to re-write the method like this: void displayStringLength( string s ) { if( s == null ) Console.WriteLine( "String is null" ); else Console.WriteLine( "String is length {0}", s.Length ); }

3. Classes and structs 3.1 Structs are largely redundant in C++. Why does C# have them? In C++, a struct and a class are pretty much the same thing. The only difference is the default visibility level (public for structs, private for classes). However, In C# structs and classes are very different. In C#, structs are value types (stored on the stack), whereas classes are reference types (stored on the heap). Also structs cannot inherit from structs or classes, though they can implement interfaces. Structs cannot have destructors. 3.2 Does C# support multiple inheritance (MI)? C# supports multiple inheritance of interfaces, but not of classes. 3.3 Is a C# interface the same as a C++ abstract class? No, not quite. An abstract class in C++ cannot be instantiated, but it can (and often does) contain implementation code and/or data members. A C# interface cannot contain any implementation code or data members - it is simply a group of method names & signatures. A C# interface is more like a COM interface than a C++ abstract class. The other major difference is that a C# class can inherit from only one class (abstract or not), but can implement multiple interfaces. 3.4 Are C# constructors the same as C++ constructors? Very similar. 3.5 Are C# destructors the same as C++ destructors? No! They look the same but they're very different. First of all, a C# destructor isn't guaranteed to be called at any particular time. In fact it's not guaranteed to be called at all. Truth be told, a C# destructor is really just a Finalize method in disguise. In particular, it is a Finalize method with a call to the base class Finalize method inserted. So this: class CTest { ~CTest() { System.Console.WriteLine( "Bye bye" ); } } is really this:

class CTest { protected override void Finalize() { System.Console.WriteLine( "Bye bye" ); base.Finalize(); } } With the arrival of Beta 2, explicitly overriding Finalize() like this is not allowed - the destructor syntax must be used. 3.6 If C# destructors are so different to C++ destructors, why did MSuse the same syntax? Because they're evil, and they want to mess with your mind. 3.7 What is a static constructor? A constructor for a class, rather than instances of a class. The static constructor is called when the class is loaded. 3.8 Are all methods virtual in C#? No. Like C++, methods are non-virtual by default, but can be marked as virtual. 3.9 How do I declare a pure virtual function in C#? Use the abstract modifier on the method. The class must also be marked as abstract (naturally). Note that abstract methods cannot have an implementation (unlike pure virtual C++ methods).

4. Exceptions 4.1 Can I use exceptions in C#? Yes, in fact exceptions are the recommended error-handling mechanism in C# (and in .NET in general). Most of the .NET framework classes use exceptions to signal errors. 4.2 What types of object can I throw as exceptions? Only instances of the System.Exception classes, or classes derived from System.Exception. This is in sharp contrast with C++ where instances of almost any type can be thrown. 4.3 Can I define my own exceptions? Yes, as long as you follow the rule that exceptions derive from System.Exception. More specifically, MS recommend that user-defined exceptions inherit from System.ApplicationException (which is derived from System.Exception). 4.4 Are there any standard exceptions that I can re-use? Yes, and some of them loosely correspond to standard COM HRESULTs. The table below shows a mapping from HRESULTs to .NET (and therefore C#) exceptions: HRESULT

.NET EXCEPTION

E_INVALIDARG

ArgumentOutOfRangeException, or the more general ArgumentException. Alternatively FormatException if a supplied parameter is not the correct format - e.g. a URL is specified as htp:// instead of http://

E_POINTER

ArgumentNullException

E_NOTIMPL

NotImplementedException

E_UNEXPECTED

Some may consider InvalidOperationException to be equivalent. InvalidOperationException is normally used to indicate that an object cannot perform the requested operation because it is not in a suitable state to do so.

E_OUTOFMEMORY

OutOfMemoryException

Other standard exceptions that you might want to re-use are IndexOutOfRangeException and ArithmeticException . 4.5 Does the System.Exception class have any cool features? Yes - the feature which stands out is the StackTrace property. This provides a call stack which records where the exception was thrown from. For example, the following code:

using System; class CApp { public static void Main() { try { f(); } catch( Exception e ) { Console.WriteLine( "System.Exception stack trace = \n{0}", e.StackTrace ); } } static void f() { throw new Exception( "f went pear-shaped" ); } } produces this output: System.Exception stack trace = at CApp.f() at CApp.Main() Note, however, that this stack trace was produced from a debug build. A release build may optimise away some of the method calls which could mean that the call stack isn't quite what you expect. 4.6 When should I throw an exception? This is the subject of some debate, and is partly a matter of taste. However, it is accepted by many that exceptions should be thrown only when an 'unexpected' error occurs. How do you decide if an error is expected or unexpected? This is a judgement call, but a straightforward example of an expected error is failing to read from a file because the seek pointer is at the end of the file, whereas an example of an unexpected error is failing to allocate memory from the heap. 4.7 Does C# have a 'throws' clause? No, unlike Java, C# does not require (or even allow) the developer to specify the exceptions that a method can throw.

5. Run-time type information 5.1 How can I check the type of an object at runtime? You can use the is keyword. For example: using System; class CApp { public static void Main() { string s = "fred"; long i = 10; Console.WriteLine( "{0} is {1}an integer", s, (IsInteger(s) ? "" : "not ") ); Console.WriteLine( "{0} is {1}an integer", i, (IsInteger(i) ? "" : "not ") ); } static bool IsInteger( object obj ) { if( obj is int || obj is long ) return true; else return false; } }

produces the output: fred is not an integer 10 is an integer 5.2 Can I get the name of a type at runtime? Yes, use the GetType method of the object class (which all types inherit from). For example: using System; class CTest { class CApp { public static void Main() { long i = 10; CTest ctest = new CTest(); DisplayTypeInfo( ctest ); DisplayTypeInfo( i ); } static void DisplayTypeInfo( object obj ) { Console.WriteLine( "Type name = {0}, full type name = {1}", obj.GetType(), obj.GetType().FullName ); } } } produces the following output: Type name = CTest, full type name = CTest Type name = Int64, full type name = System.Int64

6. Advanced language features 6.1 What are delegates? A delegate is a class derived from System.Delegate. However the language has a special syntax for declaring delegates which means that they don't look like classes. A delegate represents a method with a particular signature. An instance of a delegate represents a method with a particular signature on a particular object (or class in the case of a static method). For example: using System; delegate void Stereotype(); class CAmerican { public void BePatriotic() { Console.WriteLine( "... ... God bless America."); } } class CBrit { public void BeXenophobic() { Console.WriteLine( "Bloody foreigners ... " ); } } class CApplication { public static void RevealYourStereotype( Stereotype[] stereotypes ) {

foreach( Stereotype s in stereotypes ) s(); } public static void Main() { CAmerican chuck = new CAmerican(); CBrit edward = new CBrit(); // Create our list of sterotypes. Stereotype[] stereotypes = new Stereotype[2]; stereotypes[0] = new Stereotype( chuck.BePatriotic ); stereotypes[1] = new Stereotype( edward.BeXenophobic ); // Reveal yourselves! RevealYourStereotype(stereotypes ); } } This produces the following result: ... ... God bless America. Bloody foreigners ... 6.2 Are delegates just like interfaces with a single method? Conceptually delegates can be used in a similar way to an interface with a single method. The main practical difference is that with an interface the method name is fixed, whereas with a delegate only the signature is fixed - the method name can be different, as shown in the example above. 6.3 What is the C# equivalent of QueryInterface? The as keyword. For example: using System; interface IPerson { string GetName(); } interface IPerson2 : IPerson { int GetAge(); } class CPerson : IPerson { public CPerson( string name ) { m_name = name; } // IPerson public string GetName() { return m_name; } private string m_name; } class CPerson2 : IPerson2 { public CPerson2( string name, int age ) { m_name = name;

m_age = age; } // IPerson2 public string GetName() { return m_name; } public int GetAge() { return m_age; } private string m_name; private int m_age; } public class CApp { public static void Main() { CPerson bob = new CPerson( "Bob" ); CPerson2 sheila = new CPerson2( "Sheila", 24 ); DisplayAge( bob ); DisplayAge( sheila ); } static void DisplayAge( IPerson person ) { IPerson2 person2 = person as IPerson2; // QueryInterface lives on !!! if( person2 != null ) Console.WriteLine( "{0} is {1} years old.", person2.GetName(), person2.GetAge() ); else Console.WriteLine( "Sorry, don't know {0}'s age.", person.GetName() ); } } Running the program produces the following output: Sorry, don't know Bob's age. Sheila is 24 years old.

7. It doesn't work like that in C++ ... 7.1 I 'new'-ed an object, but how do I delete it? You can't. You are not allowed to call the destructor explicitly, and no delete operator is provided. Don't worry, the garbage collector will destroy your object .... eventually .... probably .... :-) 7.2 I tried to create an object on the stack, but the C# compilercomplained. What's going on? Unlike C++, you cannot create instances of classes on the stack. Class instances always live on the heap and are managed by the garbage collector. 7.3 I defined a destructor, but it never gets called. Why? A C# destructor is really just an implementation of Finalize, and the runtime doesn't guarantee to call Finalize methods. The semantics of a C# destructor are quite different from a C++ destructor. 7.4 Most of the C# basic types have the same names as C++ basic types?Are they the same? No. A char in C# is equivalent to a wchar_t in C++. All characters (and strings, obviously) are Unicode in C#. Integral values in C# are concrete sizes, unlike C++ (where size depends on processor). For example, a C# int is 32 bits, whereas a C++ int is normally 32 bits on a 32-bit processor and 64 bits on a 64-bit processor. A C# long is 64 bits.

8. Miscellaneous 8.1 String comparisons using == seem to be case-sensitive? How do I doa case-insensitive string comparison? Use the String.Compare function. Its third parameter is a boolean which specifies whether case should be ignored or not. "fred" == "Fred" // false System.String.Compare( "fred", "Fred", true ) // true 8.2 I've seen some string literals which use the @ symbol, and somewhich don't. What's that all about? The @ symbol before a string literal means that escape sequences are ignored. This is particularly useful for file names, e.g.

string fileName = "c:\\temp\\test.txt" versus: string fileName = @"c:\temp\test.txt" 8.3 Does C# support a variable number of arguments? Yes, using the params keyword. The arguments are specified as a list of arguments of a specific type, e.g. int. For ultimate flexibility, the type can be object. The standard example of a method which uses this approach is System.Console.WriteLine(). 8.4 How can I process command-line arguments? Like this: using System; class CApp { public static void Main( string[] args ) { Console.WriteLine( "You passed the following arguments:" ); foreach( string arg in args ) Console.WriteLine( arg ); } } 8.5 Does C# do array bounds checking? Yes. An IndexOutOfRange exception is used to signal an error. 8.6 How can I make sure my C# classes will interoperate with other .NETlanguages? Make sure your C# code conforms to the Common Language Subset (CLS). To help with this, add the [assembly:CLSCompliant(true)] global attribute to your C# source files. The compiler will emit an error if you use a C# feature which is not CLS-compliant.

Delegates Q: What do delegates buy you? A: Delegates enable scenarios that some other languages have addressed with function pointers. However, unlike function pointers, delegates are object-oriented and type-safe. Q: Are delegates really type-safe? Not really. A delegate instance does not know or care about the classes of the methods it encapsulates; all that matters is that those methods be compatible with the delegate's type. Q: What does that mean? The problem is best illustrated with an example:

using System; class Department { public delegate void Fireable(); public static void FireEmployee(Fireable fireable) { fireable(); } } class Military { public delegate void Fireable(); public static void FireMissile(Fireable fireable) { fireable(); } } class Missile { public void Fire() { Console.WriteLine("missile fired"); } } class Employee { public void Fire() { Console.WriteLine("employee fired"); } } class Test { static Employee e1 = new Employee(); static Missile e2 = new Missile(); static void Main(string[] args) { Department.Fireable e = new Department.Fireable(e2.Fire); Department.FireEmployee(e); } }

In this program, the programmer has made an

error. The line Department.Fireable e = new Department.Fireable(e2.Fire); Department.Fireable e = new Department.Fireable(e1.Fire);

really should be

However the compiler does not detect this coding error. The program compiles fine and you get this output when you run it: missile fired Uh oh! The programmer intended to fire an employee, but he has launched a missile instead! Q: Is there a better way to do this? A: Yes. You can get type safety by using interfaces instead of delegates.

using System; class Department { public interface Fireable { void Fire(); } public static void FireEmployee(Fireable fireable) { fireable.Fire(); } } class Military { public interface Fireable { void Fire(); } public static void FireMissile(Fireable fireable) { fireable.Fire(); } } class Missile : Military.Fireable { public void Fire() { Console.WriteLine("missile fired"); } } class Employee : Department.Fireable { public void Fire() { Console.WriteLine("employee fired"); } } class Test { static Employee e1 = new Employee(); static Missile e2 = new Missile(); static void Main(string[] args) { Department.Fireable e = e1; Department.FireEmployee(e); } }

Try changing the line Department.Fireable e = e1; Department.Fireable e = e2;

to this:

When you try to compile the program the compiler tells you: test.cs(38,33): error CS0029: Cannot implicitly convert type 'Missile' to 'Department.Fireable' The compiler has detected your coding error! Q: What is type safety all about? A: Type safety is about increasing the opportunities for the compiler to detect your coding errors. If you use interfaces instead of delegates the compiler will have more opportunities to detect your coding errors. Q: What other differences exist between delegates and interfaces? A: Interfaces carry semantics, and when a programmer implements an interface, he is typically well aware of that semantics. When you try to invoke a particular method via an interface, you can be fairly certain that if you succeed, the semantics of that method is what you expect. For that reason, using interfaces is essentially doing a check for semantic correctness on some level. Delegates, on the other hand, by only verifying the method signature, make the programmer responsible for ensuring that the semantics of the method is compatible. The semantics may cover not only the meaning of the arguments and return value (some times even the order of the arguments if they are of the same type), the ranges of the arguments, but also an invocation order when multiple methods are concerned. Hence, in a sufficiently large program there is plenty of margin to make an error when different programmers are not forced to comply with a uniform semantics (as they would be if

interfaces were used). [credit: Mind Bridge] Q: What can we conclude from all this? A: Use of delegates results in shorter but less reliable code.

Boxing and unboxing Q: What does boxing and unboxing buy you? A: Boxing and unboxing enable type system unification. Q: What is type system unification? The goal of type system unification is to bridge the gap between value types and reference types that exists in most languages. For example, a Stack class can provide Push and Pop methods that take and return object values. public class Stack { public object Pop() {...} public void Push(object o) {...} } Because C# has a unified type system, the Stack class can be used with elements of any type, including value types like int. Q: Does boxing and unboxing really bridge the gap between value types and reference types? No, not really. Reference types have the concept of identity and equality, while value types only have equality. Boxing and unboxing does not change this fundamental difference. Autoboxing in C# allows value types to go back and forth between being objects, but each time a value type becomes an object it acquires a new identity. Here's a sample program to illustrate this problem: using System; struct A { } class B { } public class Test { static Object Process(Object o) { if (o is A) { A a = (A)o; // do something with a return a; } else if (o is B) { B b = (B)o; // do something with b return b; } return null; } static void Check(Object o) { Console.WriteLine(o == Process(o)); } public static void Main(string[] args) { Check(new A()); Check(new B()); } } This program prints False True

which may be unexpected if you don't understand that value types and reference types cannot be treated the same way. This illustrates the fact that C# does not bridge the gap between value types and reference types. The solution to this problem is to use wrapper classes. Pretending there is no difference between reference types and value types is dangerous as it will invariably result in hard-to-detect bugs, as demonstrated by this example. Q: What other pitfalls should I be aware of? A: A boxing conversion always makes a copy of the value being boxed. This is different from a conversion of a reference-type to type object, in which the value continues to reference the same instance. For example, given the declaration struct Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } the following statements Point p = new Point(10, 10); object box = p; p.x = 20; Console.Write(((Point)box).x); will output the value 10 because the implicit boxing operation that occurs in the assignment of p to box causes the value of p to be copied. Had Point been declared a class instead, the value 20 would be output because p and box would reference the same instance. Q: Isn't it cool to have collections which can take both ints as well as strings? A: Yes, but note that if you store a value type in a collection, then in order to update the value you have to unbox, update the value, rebox the updated value and then replace the object in the collection. This has two problems: • Performance. As this article shows, you can almost double performance by using wrapper classes (see IntHolderClass) instead of autoboxing. • Loss of identity. The updated object is not the same as the old object. This can break code that depends on the identity of the object. Again, this problem can also be solved by using a wrapper class. Q: What can we conclude from all this? A: The 'Type System Unification' in C# is half-baked and full of pitfalls. Properties Q: What do properties buy you? A: The most oft quoted benefit is as follows: You can start with public member variables, and at a later stage in your development process if you decide that you need to do some processing whenever the variable is read or written you can do so by changing the public member variable into a property. Q: Why doesn't that work in practice? A: In reality, if you change a public member variable to a property you have no guarantee that you will not break client code. For example, this code will not compile if you change Sum to a property: public void Test() { Foo(ref bar.Sum); } Q: Do properties have any other benefits? A: Properties have a cleaner syntax because you don't have to supply the parenthesis. Q: Does omitting the parenthesis make the syntax cleaner? A: Yes, if "cleaner" to you is fewer characters on the screen. No, if "cleaner" to you is something that appeals to the sense of logic and reason. It should be noted that Pascal did not require you to supply the parenthesis when you call a function, if that function takes no parameters. C requires you to supply the parenthesis even if the function takes no parameters. Many people think C is cleaner in this regard because it makes logical sense to require the parenthesis. Q: What case convention should I follow when naming properties? A: Private member names should begin with a lowercase letter while other member names should begin with an uppercase letter. It should be noted that while this is a good convention to follow while writing code, it is only a convention, and is not enforced by the compiler. Hence it is not a good idea to rely on this convention while reading code.

Sample code included with the .NET SDK does not always adhere to this convention (see portal example). Also, some tools (such as xsd) generate code which has wrong case properties. Q: How can using properties cause me to miss inefficiencies? A: Quick, can you spot the inefficiency in this code? public void Calc(int[] foo) { Sum = 0; for (int i = 0; i < foo.Length; i++) Sum += foo[i]; } What you may have missed is that every += involves two function calls. The only indication of this fact is the uppercase 'S' in Sum (which by the way is a convention that is frequently not followed), so the inefficiency is not easy to spot. Now consider this variation of the same code: public void Calc(int[] foo) { Sum = 0; for (int i = 0; i < foo.Length; i++) SetSum(GetSum() + foo[i]); } Now the inefficiency is glaringly obvious, so you may rewrite it like this: public void Calc(int[] foo) { int temp = 0; for (int i = 0; i < foo.Length; i++) temp += foo[i]; SetSum(temp); } If getting or setting sum is not cheap (now or in the future), the resulting improvement in performance may be nothing to sneeze at. Code that uses properties gives you no immediate feedback on the compactness and efficiency of the code. Q: Are there any other pitfalls I should be aware of? A: Quick, can you spot the database access in this code? public int CalculateRaise(int percent) { return (salary + bonus + Commission) * percent / 100; } If you missed the uppercase 'C' in Commission you missed the database access. (Database access in a property getter is not uncommon.) Be sure to choose a good font when reading code — one in which uppercase C looks very different from lowercase c. Better still, rewrite your code like this, so you can clearly see the function call: public int CalculateRaise(int percent) { return (salary + bonus + GetCommission()) * percent / 100; } Q: What can we conclude from all this? A: Properties buy very little when weighed against the problems its use is likely to cause.

Structs Q: What do structs buy you? A: Structs can sometimes improve performance. Q: How are structs different from classes? A: Structs are stored on the stack as opposed to the heap. Structs are value types rather than reference types. Q: How do structs impair code readability and maintainability? A: What will this code snippet print? Point a = new Point(10, 10); Point b = a;

a.x = 100; Console.WriteLine(b.x); The answer depends on whether Point is a class or a struct. If Point is a class then the answer is 100. If Point is a struct then the answer is 10. Even though structs and classes work differently, they look the same. This makes the code hard to follow. C# violates a principle of programming language design, known as the principle of uniformity. Q: What is the principle of uniformity and why should I care? A: In The Psychology of Computer Programming, Weinberg explains that uniformity is a psychological principle which says that users/programmers expect that things that look similar should do similar things, and conversely that things that look different should do different things. If a programming language violates this principle then it increases complexity, and code written in that language becomes harder to understand and maintain. Because of C#'s violation of the principle of uniformity, the programmer has the extra burden of tracking whether something is a struct or a class. Q: Isn't that a problem in C++ too? A: No. In C++, structs and classes work the same. The only difference is the default visibility for fields and methods. Also, in C++ the syntax for using a class/struct reference is very different from the syntax for using a class/struct value. Q: Why should I track whether something is a struct or a class? A: It's a huge semantic difference. A class variable holds a reference to to a heap-allocated object, while a struct variable directly holds the value of the object. In C++, this is usually visible in the declaration of the variable (Foo f for a value type, Foo *pF for a pointer) and in its use (f.x for a value type, f->x for a reference type). In C#, both use the same syntax for declaration and use, and there isn't even any suggested name standard to mark the difference. In just about every case, it's important to know if you are dealing with value types or reference types — reference types has the concept of identity and equality, while value types only has equality. Allocating an array of value types gives you a number of objects with default values while an array of reference types gives you a array of null references. Adding a struct type to a list means it's silently boxed and removing it unboxes it at a significantly higher cost than if a reference types were added removed. Etc, etc. [credit: Mats Olsson] Q: What can we conclude from all this? A: Structs buy very little when weighed against the maintenance headaches its use is likely to cause User-defined implicit conversions Q: What do user-defined implicit conversions buy you? A: User-defined implicit conversions allow your class to define conversions from other classes (or basic types), without requiring a cast, or requiring you to call a conversion function. For example, if you have a class called Complex and you have defined an implicit conversion from float then you can use it like this: Complex c1 = 12.345F; Without user-defined implicit conversions, you would have to use one of the following less-convenient statements: Complex c2 = (Complex)12.345F; Complex c3 = Complex.ValueOf(12.345F); Q: Isn't this what wreaked havoc in VB4? A: Yes. VB4 did not have the ability for users to define their own implicit conversions. Instead, it came with a large set of built-in, "convenient" conversions. This supposed "convenience" caused so many problems that VB programmers nicknamed this feature "Evil Type Coercion". You can read more about it here: http://www.devx.com/premier/mgznarch/vbpj/1995/11nov95/progtech.pdf Q: Don't many programming languages have built-in implicit conversions? A: Yes, many programming languages including C do some implicit type conversions, such as from int to long. But such built-in implicit conversions are usually limited, well understood and very strict. Q: How does implicit type conversion reduce software reliability? A: Implicit type conversions decrease type error detection ability of the compiler. Fewer of your programming errors will be caught by the compiler, which leads to less reliable software. For example, if you erroneously assigned an integer to a variable of type Foo, the compiler will catch the error. However if you have defined an implicit conversion from integer to Foo, then the compiler will assume you meant to

convert the integer to type Foo and then store the value, so your error will not be caught. If this is really what you meant, then it is better to make it explicit by calling a conversion function like this: Foo f = Foo.ValueOf(123); Q: Are implicit type conversions OK when there is no loss of precision? A: The issues with implicit type conversion have nothing to do with whether there is loss of precision or not. See above. Q: What can we conclude from all this? A: The evils of implicit type conversion outweigh the benefits.

Unchecked Exceptions Q: What is the problem with checked exceptions? A: With checked exceptions, you have to either catch exceptions thrown by the methods you call, or mention the exception in the throws clause of your method. Because of the tedium of mentioning each exception in the throws clause, some programmers may take the shortcut of swallowing exceptions. Q: What is meant by swallowing an exception? A: You should only catch exceptions that you are prepared to handle. Otherwise, if you catch an exception and ignore it (or log it), you are "swallowing" the exception. As a result, code higher up the call chain that may be prepared to handle the exception will never see the exception. Q: Does C# solve the problem of swallowed exceptions? A: No. In fact, C# requires it! Methods in C# cannot specify the exceptions it may throw. The documentation of the method you wish to call may mention the list of exceptions you can expect. But this list of exceptions is not enforced by the compiler, and is not guaranteed to be exhaustive. Also, since the list of exceptions is not part of the contract, the method can be revised at any time and a new exception that you didn't know about can be thrown. Since there is no previously agreed upon list of exceptions, you are left with no option but to catch all exceptions if you want to recover from an exception (such as by offering to connect to an alternate database if the primary database is down, etc.) Obviously, if you catch all exceptions, you will end up swallowing some of them. Q: What other problems exist with C# exceptions? A: Often in C#, if you have multiple implementations of an interface, each of those implementations may have their own disjoint exception hierarchies. (i.e., the exception hierarchies have no common classes other than System.Exception.) Example: ADO.NET. This makes it impossible for generic code (i.e., code that can use any of those implementations) to recover from exceptions generically without catching all exceptions (i.e., System.Exception.) Again, if you catch all exceptions you will end up swallowing some of them. Q: What can we conclude from all this? A: Unchecked exceptions results in shorter but less robust code. How do I write a method that accepts a variable number of parameters? Q: How do I write a method that accepts a variable number of parameters? A: Languages like C and C++ have always offered some means for using and creating functions capable to accept a variable number of parameters. The most widely known example of a function which takes a variable number of parameters is printf(): int printf(char *format, …); // the ellipsis means "variable number of params" Using this function is pretty easy: printf("Hello, world\n"); printf("The sum of %d and %d is %d\n", a, b, a+b); However, the creation of such functions in these languages relays on a set of predefined macros and is not particularly elegant or intuitive. C# offers an elegant solution to this problem through parameter arrays. A parameter array is a single-dimensional array included as the last parameter in the parameter list of a method: public string Concat(string separator, params string[] strings) { string result = ""; for (int i = 0; i < strings.Length; i++)

{ if (i > 0) result += separator; result += strings[i]; } return result; } Such a function can be called in two different ways: a)

Passing the function an array instance argument: string[] names = { "Anders", "Eric", "Scott", "Duncan" }; MessageBox.Show(Concat("+", names) + " = great team");

b)

Using zero or more type-compatible arguments for the parameter array: MessageBox.Show(Concat("+", "Anders", "Eric", "Scott", "Duncan") + " = great team"); In this case, the invocation will create an array from the supplied arguments and use it as the actual argument.

Thanks to the unified .NET type system, object[] can be used as “common denominator” for arguments of different types: public int SumTheIntegers(params object[] list) { // sum all the integers included in list int sum = 0; foreach (object o in list) if (o.GetType() == typeof(int)) sum += (int) o; return sum; } Why doesn't C# support static method variables? Q: In C++, it's possible to write a static method variable, and have a variable that can only be accessed from inside the method. C# doesn't provide this feature. Why? A: There are two reasons C# doesn't have this feature. First, it is possible to get nearly the same effect by having a class-level static, and adding method statics would require increased complexity. Second, method level statics are somewhat notorious for causing problems when code is called repeatedly or from multiple threads, and since the definitions are in the methods, it's harder to find the definitions. Why must attribute properties be read/write in C#? Q: Why must attribute properties be read/write in C#? In the C# language, when you define an attribute class, you can define both constructor arguments and properties. For example: class MyAttribute: Attribute { string name; int number; public MyAttribute(string name) { this.name = name;} public int Number { get {return number;} set {number = value; } } public string Name { get {return name;} } }

[My("Fred", Number=5)] class Fred { } When you do this, C# requires that properties (such as Number in this example) be read/write properties, though languages such as VB.NET only require them to be readable. Why? A: Using an attribute in C# is logically equivalent to calling the constructor of the attribute class, and then executing the “property = value” part for each named property. Requiring a writeable property is consistent with this view. Why do I get the error "Object reference not set to an instance of an object"? The code is trying to access a member of a reference type variable that is set to null. Given the following class, let's examine some code that could be in the Main method: using System; class Foo { static void Main() { // foo has not been instantiated Foo foo = null; // implementation to be discussed... } public int BarProperty { get { return 0; } } public string BarMethod() { return null; } } Looking at Main, notice that foo is set to null. Your situation will not be this explicit because the variable you are trying to use could be a class field, parameter, or local variable that was once instantiated but was subseqently set to null. Given that foo is null, the following code will throw a NullReferenceException: try { // foo is null, and you can't call // BarProperty on null. int resultBad = foo.BarProperty; } catch (NullReferenceException nre) { Console.WriteLine( "\nCan't read BarProperty, foo is null.\n" + nre.Message); } Since foo is null, you can not use its members. This was a property, but the following code demonstrates calling a method: try { // foo is null, and you can't call // BarMethod on null. foo.BarMethod(); } catch (NullReferenceException nre) { Console.WriteLine( "\nCan't call BarMethod(), foo is null.\n" +

nre.Message); } The code above throws a NullReferenceException because foo is still null. It doesn't matter that the first call was a property and the second is a method - they are both members of the type. Now, to fix this problem, you must ensure that foo is instantiated before it is used. The following code instantiates foo and the previous problems are solved: // now we have an instance foo = new Foo(); // works fine int resultGood = foo.BarProperty; Since foo now refers to a valid instance, the code can call any of its members. This was easier than many null reference problems. Sometimes you have multiple levels of indirection, leaving you with a scenario you didn't expect. Assuming that foo now references an object, there is still a problem with the following code: try { // still breaks because BarMethod() returned // null and you can't call Trim() on null. foo.BarMethod().Trim(); } catch (NullReferenceException nre) { Console.WriteLine( "\nCan't call Trim(), BarMethod() returns null.\n" + nre.Message); } The problem occurs in the code above because BarMethod returned null, which means that the code is trying to call the Trim method on a string reference that is set to null. The proper way to fix this problem is to debug BarMethod to find out why it returned null. That assumes BarMethod is not supposed to return null. If, in your application, it made sense for BarMethod to sometimes return null, then you would have to check the return value of BarMethod before you called any members of the return value. Why did I receive the error: "The type or namespace '' does not exist in the class or namespace '<parent namespace>' (are you missing an assembly reference?)" You need to add a reference in your project to an assembly where that namespace is defined. If you are using VS.NET: 1. Right click on the References folder on your project. 2. Select Add Reference. 3. Select the .NET tab (or select the Browse button if it is not a .NET Framework assembly). 4. Double-click the assembly containing the namespace in the error message. 5. Press the OK button. If you are using the command line, use the /r: or /reference: option. For Example: csc.exe /reference:System.Drawing.dll MyFontDisplayApp.cs When you recompile, this error will no longer appear. You can find the assembly, where a namespace is defined, in the documentation. Identify one of the types in the namespace that you want to use. Every type in the .NET Framework has an "About" page that provides an overview, basic information about the type, and example code if you're lucky. At the bottom of the Overview, for all types, there is a "Requirements" section. This has a Namespace member that tells what namespace the type belongs to. It also tells what assembly type belongs to, which is the assembly you need to reference in your application. For example, if I had an application that was using Font types, I would look up Font in the .NET Framework documentation, using the Index tab, and observe that the Font type is in the System.Drawing namespace and its assembly is System.Drawing.dll. Another question related to this is "If I've already declared a using statement, why do I have to add the reference to the project?" The reason derives from the fact that the using statement and assembly references have two different purposes. Recall that the purpose of namespaces is to disambiguate type references and provide logical organization of types. When specifying a namespace in a using statement, you are telling C# that you want to use the types in that namespace in an unqualified manner. The key point is that namespaces are "logical" entities that could exist in one or more assemblies. On the other hand, assemblies are "physical" entities that contain multiple types. Assemblies are many things, but for the purposes of this discussion, an assembly is the unit of deployment in .NET. So, the reason you need a reference to the assembly that the type is located in is so that C# can find the physical location of that type, which is not possible with the logical namespace provided by a using statement.

How can I subscribe to events exposed by a remoted object? Delegates require information about the type that the method is associated with in order to make a call. In a single app-domain, this isn't a problem, because the server (the object firing the events) has access to the type information for the client (which has the event handlers) by way of the delegate. However, during remoting, the server most likely does not have any information about the client. If you want events from the server to fire in the client app domain, then the client must derive from MarshalByRefObject. This is required so that the server will call back into the client, as opposed to a copy of the client object that is passed to the server. A simple way to do this is to place a copy of the client assembly in the same directory where the server directory is. While this will work, it is not an elegant solution, as it exposes the client type unecessarily. A more elegant solution (albiet more complex), is to have a single assembly that is referenced by both the client and the server. This assembly will have a shim class which will expose methods that share the signature of the events that you want to shim. The assembly will also provide an interface with methods that share the signature of the events as well. The shim will then take a reference to the interface, and the methods will aggregate the call to the interface that was passed in (I recommend the constructor as the place to pass the interface implementation). Finally, the client object will implement the interface. When subscribing to the events that the server exposes, attach the delegates to the methods on the shim, which will be passed your client object's implementation. It is also important to note that in order for this to work, the TypeFilterLevel property on the sink provider for the server needs to be set to TypeFilterLevel.Full. Why does my Windows Form project not use visual styles in XP even when I call Application.EnableVisualStyles? If you set a property on a Windows Forms control which forces the creation of the control (e.g. the SelectedIndex property on the ComboBox class), the control (and perhaps the rest of the form) will not render with visual styles enabled. The resolution is to place the code that sets these properties in an event handler for the Load event on the form/control. Why aren't reference types polymorphic? Q: Why aren't reference types polymorphic? A: Consider the following code: using System; class Dog { public string Name; } class Test { public static void Swap(ref object a, ref object b) { object temp; temp = a; a = b; b = temp; } public static void Main() { Dog d1 = new Dog(); d1.Name = "fido"; Dog d2 = new Dog(); d2.Name = "rex"; Swap(ref d1, ref d2); } } The compiler will report an error on the call to the Swap() function. Why? Consider if the swap function was like this: public static void Swap(ref object a, ref object b) { a = 5; b = “Hello“; } If the compiler allowed this code, it would mean assigning a boxed int to a Dog object, which is clearly not type safe. When should I use == and when should I use Equals?

The Equals method is just a virtual one defined in System.Object, and overridden by whichever classes choose to do so. The == operator is an operator which can be overloaded by classes, but which usually has identity behaviour. For reference types where == has not been overloaded, it compares whether two references refer to the same object which is exactly what the implementation of Equals does in System.Object. Value types do not provide an overload for == by default. However, most of the value types provided by the framework provide their own overload. The default implementation of Equals for a value type is provided by ValueType, and uses reflection to make the comparison, which makes it significantly slower than a type-specific implementation normally would be. This implementation also calls Equals on pairs of references within the two values being compared. However, the main difference between the two types of comparison in normal use (where you're unlikely to be defining your own value types very often) is polymorphism. Operators are overloaded, not overridden, which means that unless the compiler knows to call the more specific version, it'll just call the identity version. To illustrate that, here's an example: using System; public class Test { static void Main() { // Create two equal but distinct strings string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'}); string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'}); Console.WriteLine (a==b); Console.WriteLine (a.Equals(b)); // Now let's see what happens with the same tests but // with variables of type object object c = a; object d = b; Console.WriteLine (c==d); Console.WriteLine (c.Equals(d)); } } The results are: True True False True The third line is False because the compiler can only call the non-overloaded version of == as it doesn't know that the contents of c and d are both string references. As they are references to different strings, the identity operator returns false. So, when should you use which operator? My rule of thumb is that for almost all reference types, use Equals when you want to test equality rather than reference identity. The exception is for strings - comparing strings with == does make things an awful lot simpler and more readable but you need to remember that both sides of the operator must be expressions of type string in order to get the comparison to work properly. For value types, I'd normally use == for easier-to-read code. Things would get tricky if a value type provided an overload for == which acted differently to Equals, but I'd consider such a type very badly designed to start with. Should I assign null to my local variables? Q: Should I assign null to my local variables after I use them? For example: string s = ...; Console.WriteLine(s); s = null; A: There is rarely a need to do this for local variables in C# The lifetime of variables is tracked by the JIT - it analyzes how variables are used in a routine, and it knows exactly when the variable is no longer needed, and after that point, the value is available to be collected. Interestingly, if you assign it to null, you are actually extending the lifetime of the variable slightly, so it could cause it to be garbage collected later (though realistically, there's unlikely to be any real difference here.

This is true for the vast majority of methods. If you have a method where your code lives for a while - a loop on a separate thread, for example - then it may be worthwhile to see if there are any unnecessary values living in variables while you wait. Why do I need a null test before I invoke a delegate? Q: Why do I need a null test before I invoke a delegate? A: If you have an event in a class, you need to add a null test before you call the delegate. Typically, you would write: if (Click != null) Click(arg1, arg2); There is actually a possible race condition here - the event can be cleared between the first and second line. You would actually want to write: ClickHandler handler = Click; if (handler != null) handler(arg1, arg2); usually. You might want to do some other sort of synchronization in other scenarios. So back to the main question. Why is the null test required? We can't change the existing behavior of calling through a delegate as some apps may depend on it, so it would have to be an addition to the language. We have talked about adding an Invoke() keyword to the language to make this easier, but after a fair bit of discussion, we decided that we couldn't do the right thing all the time, so we elected not to do anything. Why doesn't C# warn about unused methods? Q: Why doesn't C# warn on unused methods? A: This is something that the C# compiler could do, subject to a few caveats: • Virtual functions would have to be excluded • Interface implementations wouldn have to be excluded • You would get false positives if you used reflection • You might get false positives if you used delegates (the compiler might be able to be smart here) Other than that, it would be possible for us to do this, and we may do it in a future version. How can I update my user interface from a thread that did not create it? When performing any action on a control which requires the updating of a user interface element (e.g. setting the Text property on almost any class derived from Control, updating the data source behind a DataGrid), these operations MUST take place on the thread that created the UI element. In order to do this, the Control class provides the Invoke method, which will take a delegate and execute it on the thread that the UI element was created on. In order to use this, one must declare a function that performs the UI operation. For example, say a form has a TextBox on it named m_TextBox. To update the text from another thread, create a method that will update the Text property on the TextBox: // The declaration of the textbox. private TextBox m_TextBox; // Updates the textbox text. private void UpdateText(string text) { // Set the textbox text. m_TextBox.Text = text; } Now, create a delegate that has the same signature as the method that was previously defined: public delegate void UpdateTextCallback(string text); In your thread, you can call the Invoke method on m_TextBox, passing the delegate to call, as well as the parameters. m_TextBox.Invoke(new UpdateTextCallback(this.UpdateText), new object[]{”Text generated on non-UI thread.”}); Note: Do not create a method that matches the EventHandler delegate signature and pass that. The implementation of Invoke on the Control class will not take into account the parameters passed to Invoke if the type of the delegate is EventHandler. It will pass the control that Invoke was called on for the sender parameter as well as the value returned by EventArgs.Empty for the e parameter. Why can't I have static and instance methods with the same name? Q: Why can't I have static and instance methods with the same name? class Test {

static void Process(); void Process(); void AmbiguousCaller() { Process(); } } there's no ambiguity, since the first can only be called through the type name, and the second can only be called through an instance. A: It is true that there would be no ambiguity between the two functions as far as a compiler is concerned. There would, however, be a considerable potential for confusion on the part of the user. It would be tough to find the right method in documentation, and once you did, hard to be sure that you are calling the right version (ie you could accidentally call the static version when you wanted the instance version). We therefore prohibit this case. Where can I find sample C# code for simple threading? Refer to the System.Threading namespace on MSDN for full details. Meanwhile here is a quick taste. using System; using System.Threading; class ThreadTest { public void Runme() { Console.WriteLine("Runme Called"); Thread.Sleep(10000); } public static void Main(String[] args) { ThreadTest b = new ThreadTest(); Thread t = new Thread(new ThreadStart(b.Runme)); t.Start(); Console.WriteLine("Thread 't' started."); Console.WriteLine("There is no telling when " + "'Runme' will be invoked. "); t.Join(); Console.WriteLine("Thread 't' has ended."); } } How do C# generics compare to C++ templates? Q: How do C# generics compare to C++ templates? A: This is really a fairly complex topic. Anders has touched on it in an interview. I should state at the outset that the goals of generics are not the same as the goals of templates. There are some things that templates do better than generics, and vice versa. Model C++ templates use a compile-time model. When a template is used in a C++ program, the effect is as if a sophisticated macro processor had been used. C# generics are not just a feature of the compiler, but also a feature of the runtime. A generic type such as List maintains its generic-ness (genericity) after it has been compiled. Or, to look at it another way, the substitution that the C++ compiler does at compile time is done at JIT time in the C# generic world. Error Checking Error is best illustrated through an example. Consider a template that has a method like this; T Add(T t1, Tt2) { return t1 + t2; }

the C++ compiler will be able to parse this method successfully. When this template is actually used, the Ts will be replaced with an actual type. If a type such as int is used, the compiler will be able to create the Add method correctly, as it knows how to add two ints. If a type such as Employee was used, the compiler would issue an error, as the compiler would know that there was no way to add two Employees. The generics world is very different. Because the type that is used with the generic is not known at compile time, the compiler needs additional information about the type that will be used with a generic class. This is done through constraints, which allow the author to constrain the types that can be used with a generic type. For example: Class List where T:IComparable means that whenever I use a T in my implementation, I can call the CompareTo() function on it. Constraints could theoretically provide nearly the same level of flexibility that templates do, but that would require a very complex constraint syntax. For the Whidbey release, only certain operations can be specified through contraints, which limits the number of operations you can perform. For example, there is no way to say that a generic type must have an add operator, so you can't write “a + b“ in a generic class. It is possible to work around this at runtime using reflection, but the implementation isn't as clean and there may be a performance loss. We may address some of these issues in future releases Run-time operations Generics in C# have full run-time support. If you use reflection, you will find that you can reflect over generic types, and create them at runtime. There's no real analog of this in the C++ world. Space Use The use of space is different between C++ and C#. Because C++ templates are done at compile time, each use of a different type in a template results in a separate chunk of code being created by the compiler. In the C# world, it's somewhat different. The actual implementations using a specific type are created at runtime. When the runtime creates a type like List, the JIT will see if that has already been created. If it has, it merely users that code. If not, it will take the IL that the compiler generated and do appropriate replacements with the actual type. That's not quite correct. There is a separate native code path for every value type, but since reference types are all reference-sized, they can share their implementation. This means that the C# approach should have a smaller footprint on disk, and in memory, so that's an advantage for generics over C++ templates. In fact, the C++ linker implements a feature known as “template folding“, where the linker looks for native code sections that are identical, and if it finds them, folds them together. So it's not a clear-cut as it would seem to be. Template metaprogramming C++ templates are sometimes used for a technique known as template metaprogramming. There is no way to do this in C#. Where can I get a full comparison between C# and VB.NET? Microsoft provides a very full language equivalents page which compares not only C# and VB.NET, but also other languages targeted at the .NET framework. It looks at the equivalent concepts, keywords, types, operators etc. A very valuable resource when you're trying to read or write code in a language which isn't your preferred one. Is there an equivalent of MyClass? No, C# doesn't have an equivalent of VB.NET's MyClass keyword. If you want to guarantee not to call an overridden version of a method, you need to make it non-virtual in the first place. What do I use instead of addressof? To create delegate instances in C#, you just specify the delegate type, the method, and (if you want to create a delegate targetting a different instance or type from the current one) the target. For instance, each of these creates a ThreadStart delegate: ThreadStart x1 = new ThreadStart(SomeInstanceMethod); ThreadStart x2 = new ThreadStart(AnotherType.SomeStaticMethod); ThreadStart x3 = new ThreadStart(someVariable.SomeInstanceMethod); How do I get the rightmost part of a string, as with the VB Right function? Use String.Substring. Assuming that x is a string of length at least n, to get the last n characters, you would use x.Substring(x.Length-n). Note that the above assumes that the string is at least n characters long. For a more robust version, you might use something like: x.Length < n ? x.Substring(x.Length-n) : x. What are the equivalents of Me and MyBase?

Me in C# is this, and MyBase in C# is base. To access normal members, just use this.memberName or base.memberName. For information about chaining constructors together, see my article on constructors. What's the equivalent of Nothing? For reference types, the equivalent of VB's Nothing is C#'s null. For value types, it's the default value - 0, false, etc. How do I tell C# what kind of literal number I want? If you need to tell C# that you want it to treat a literal as a particular type of number, you may do so by adding a number type suffix at the end of the literal you provide. For example: 1u; // An unsigned int 1l; // A signed long 1ul; // An unsigned long 1f; // A System.Single floating-point number; 1d; // A System.Double floating-point number 1m; // a System.Decimal floating-point number This is somewhat important because sometimes you must match a literal to the signature of something or specify the value to 'defeat' an implicit cast behavior you don't like. For example, Hashtable names = new Hashtable(100, 0.1); won't compile because the constructor takes parameters (int, float) and the above is (int, double). The line should read Hashtable names = new Hashtable(100, 0.1f); A full listing of the suffixes is in the Grammar portion of the C# specification (appendix A in the ECMA specification, appendix C in the MS specification). The suffixes are also detailed in the Literals section of the specification (9.4.4 of the ECMA specification, 2.4.4 of the MS specification). How do I use an alias for a namespace or class? Use the using directive to create an alias for a long namespace or class name. You can then use it anywhere you normally would have used that class or namespace. The using alias has a scope within the namespace you declare it in. Sample code: // Namespace: using act = System.Runtime.Remoting.Activation; // Class: using list = System.Collections.ArrayList; ... list l = new list(); // Creates an ArrayList act.UrlAttribute foo; // Equivalent to System.Runtime.Remoting.Activation.UrlAttribute foo What's the difference between override and new? This is all to do with polymorphism. When a virtual method is called on a reference, the actual type of the object that the reference refers to is used to decide which method implementation to use. When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn't "know" that the object was an instance of the derived class. For instance: public class Base { public virtual void SomeMethod() { } } public class Derived : Base { public override void SomeMethod() { } } ... Base b = new Derived(); b.SomeMethod(); will end up calling Derived.SomeMethod if that overrides Base.SomeMethod. Now, if you use the new keyword instead of override, the method in the derived class doesn't override the method in the base class, it merely hides it. In that case, code like this: public class Base

{ public virtual void SomeOtherMethod() { } } public class Derived : Base { public new void SomeOtherMethod() { } } ... Base b = new Derived(); Derived d = new Derived(); b.SomeOtherMethod(); d.SomeOtherMethod(); Will first call Base.SomeOtherMethod (line 3), then Derived.SomeOtherMethod (line 4). They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method. If you don't specify either new or overrides, the resulting output is the same as if you specified new, but you'll also get a compiler warning (as you may not be aware that you're hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword). That provides the basics of overriding and the difference between new and override, but you should really see a book or tutorial for a more in-depth look at polymorphism. Q: What is the difference between const and static readonly? A: The difference is that static readonly can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on the static readonly case a bit, the containing class can only modify it: - in the variable declaration (through a variable initializer) - in the static constructor (instance constructors if it's not static) Q: How do I make a DLL in C#? A: You need to use the /target:library compiler option. Q: How do I use enum's in C#? A: Here's an example: namespace Foo { enum Colors { BLUE, GREEN } class Bar { Colors color; Bar() { color = Colors.GREEN;} public static void Main() {} }

}

Q: Why is the compiler referencing things that I'm not telling it to reference?

A: The C# compiler automatically references all the assemblies listed in the 'csc.rsp' file. You can disable the usage of the csc.rsp file by using the /noconfig compiler option on your command line. Note that the Visual Studio .NET IDE never uses the response file Q: Does C# support templates? A: No. However, there are plans for C# to support a type of template known as a generic. These generic types have similar syntax, but are instantiated at runtime as opposed to compile time. You can read more about them here. Q: Is it possible to have different access modifiers on the get/set methods of a property? A: No. The access modifier on a property applies to both it's get and set accessors. What you probably want to do if you need them to be different is make the property read-only (by only providing a get accessor) and creating a private/internal set method separate from the property. Q: How do I create a multi-language single-file assembly? A: This is currently not supported by Visual Studio .NET. Q: How do I get deterministic finalization in C#? A: In a garbage collected environment its impossible to get true determinism. However, a design pattern that we recommend is implementing IDisposable on any class that contains a critical resource. Whenever this class is consumed it may be placed in a using statement for example: using(FileStream myFile = File.Open(@"c:\temp\test.txt", FileMode.Open)) { int fileOffset = 0;

}

while(fileOffset < myFile.Length) { Console.Write((char)myFile.ReadByte()); fileOffset++; } When myFile leaves

the lexical scope of the using, its dispose method will be called. Q: What is the difference between a struct and a class in C#? A: From language spec: The list of similarities between classes and structs is longstructs can implement interfaces, and can have the same kinds of members as classes. Structs differ from classes in several important ways, however: structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiatedone for the array and one each for the 100 elements. Q: Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace? A: There is no way to restrict to a namespace. Namespaces are never units of protection. But if you're using assemblies, you can use the 'internal' access modifier to restrict access to only within the assembly. Q: Is there regular expression (regex) support available to C# developers? A: Yes. The .NET class libraries provide support for regular expressions. Look at the documentation for the System.Text.RegularExpressions namespace Q: Why do I get a security exception when I try to run my C# app? A: Some security exceptions are thrown if you are working on a network share. There are some parts of the frameworks that will not run if being run off a share (roaming profile, mapped drives, etc.). To see if this is what's happening, just move the executable over to your local drive and see if it runs without the exceptions.

One of the common exceptions thrown under these conditions is System.Security.SecurityException. To get around this, you can change your security policy for the intranet zone, code group 1.2, (the zone that running off shared folders falls into) using the caspol.exe tool. Q: What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development? A: Try using RegAsm.exe. The general syntax would be: RegAsm there's a pretty good description of it and it's associated switches in the .NET SDK docs. Just search on "Assembly Registration Tool". Q:Does C# support parameterized properties? A: No; however, C# supports the concept of an indexer from language spec: An indexer is a member that enables an object to be indexed in the same way as an array. Whereas properties enable field-like access, indexers enable array-like access. As an example, consider the Stack class presented earlier. The designer of this class might want to expose array-like access so that it is possible to inspect or alter the items on the stack without performing unnecessary Push and Pop operations. That is, Stack is implemented as a linked list, but it also provides the convenience of array access. Indexer declarations are similar to property declarations, with the main differences being that indexers are nameless (the name used in the declaration is this, since this is being indexed) and that indexers include indexing parameters. The indexing parameters are provided between square brackets. Other FAQ’s:

1)Pag level transaction how to maintain 2)How to group mutiple controls with a single validation control 3)what is http.pipeline 4)why do we need dataadapter what is the logical use of that 5)how do we implement caching in asp.net why it is called smart caching -- use cachedependency how the page knows that there is some change in the database and it updated the page design patterns process Quality multiple page transaction New RequiresNew SQL + OLEDB Providers sql nested transaction xml serialization Difference between Client Activated & Server Activated SingleCall Difference between Web Services & Remoting validator controls - what is the difference between Text property and ErrorMessage property validator controls - if javascript is disabled, will this validator controls work ? give reasons ! ADO.NET architecture difference between ASP & ASP.NET difference between ADO & ADO.NET AcceptChanges & RejectChanges... 1)how to maitain sessions across web garden(muliple cpu's 2)what is remote host 3)how to create dynamic assembly 4)how to use exception in web services (soapframe) 5)Indexers inside the loop will all the values be displayed of the array 6)how to get the element of the xmldocument 7)is there any default login page in .net

8)what is polymorphomisn is there any other method by which u can enforce polymorphism apart from using virtual and override 9)what is delegate(multicast delegate) 10)can u use polymorphism in delegates 11)can i call a group of methods using delegates 12)how xsp worker process is assocaited with session 13)what is isapi filters 14)what is lazy registration 15)how can i pass infinite parameters in the method 1 time i want to pass 2 parameters and next time i want to apss 3 methods 16)what are the different types of arrays what is the advantage of using jagged array over rectangular array 17)do u have to do any setup for using the validation in asp.net 18)i have virtual methods in the base and overriden methods in the child class.now if i make reference of the base class and object of the child class what happens 19)same question without using overriden methods in the child class 20)public class a() { public int i = 100; } will it create a probelm 21)Indexers program make a class which has an array and then make a class which has indexers and make the object of the indexer 1)mybase 2)typed dataset 3)dataset and recordset 4)union in c# 5)joins and unions 6)code for populating and manipulating dataset 7)code for datevalidation 8)Gac 9)user logging in from different location 10)forms and windows authenctication 11)remoting 12)what is strong name 13)transactions in dataset 14)create a tree view structure using datagrid -----------------------------------------------------------------------------------1)what is gac 2)what is snk file 3)how to create the snk file 4)where to use the snk file in visual studio 5)diff between datareaders and dataset 6)code to bind the datagrid with datareader and dataset 7)implementing relations and constraints in dataset 8)how to do paging in datagrid 9)what is the path of the gac 10)what is shadowing and overriding 11)diff between interfaces and abstract classes 12)vb.net file used in c# application 13)transaction in .net 14)code for using com component in .net 15)what is service component. 16)forms and windows authentication

what is operator overloading? Ans : Operator overloading enables developers to define new struct types that behave much like the predefined value types. For instance, a Digit struct can support the same mathematical operations as the predefined integral types, and can define conversions between Digit and predefined types. The predefined types employ operator overloading themselves. For example, the comparison operators == and != have different semantics for different predefined types: · Two expressions of type int are considered equal if they represent the same integer value. · Two expressions of type object are considered equal if both refer to the same object, or if both are null. · Two expressions of type string are considered equal if the string instances have identical lengths and identical characters in each character position, or if both are null. The example class Test { static void Main() { string s = "Test"; string t = string.Copy(s); Console.WriteLine(s == t); Console.WriteLine((object)s == (object)t); } } produces the output True False because the first comparison compares two expressions of type string, and the second comparison compares two expressions of type object. why is finally block used? Why is the namespace System.collection used? Diff b/w Array and Arraylist? What is a Destructor ? Ans : A destructor is a member that implements the actions required to destruct an instance of a class. Destructors cannot have parameters, cannot have accessibility modifiers, and cannot be called explicitly. The destructor for an instance is called automatically during garbage collection. What is a instance constructor? Ans : An instance constructor is a member that implements the actions required to initialize an instance of a class. What is a Static Constructor? Ans : A static constructor is a member that implements the actions required to initialize a class. Static constructors cannot have parameters, cannot have accessibility modifiers, and cannot be called explicitly. The static constructor for a class is called automatically. what is static Readonly fields ? Ans : Static fields are not a perfect match for this scenario. The fields are initialized at some point before they are used, but after this initialization there is nothing to stop a client from changing them. Such a modification could cause unpredictable errors in other programs that use Color and assume that the values do not change.

Readonly fields can be used to prevent such problems. Assignments to a readonly field can only occur as part of the declaration, or in an instance or static constructor in the same class. A static readonly field can be assigned in a static constructor, and a non-static readonly field can be assigned in an instance constructor. Thus, the Color class can be enhanced by adding the readonly modifier to the static fields: class Color { internal ushort redPart; internal ushort bluePart; internal ushort greenPart; public Color(ushort red, ushort blue, ushort green) { redPart = red; bluePart = blue; greenPart = green; } public static readonly Color Red = new Color(0xFF, 0, 0); public static readonly Color Blue = new Color(0, 0xFF, 0); public static readonly Color Green = new Color(0, 0, 0xFF); public static readonly Color White = new Color(0xFF, 0xFF, 0xFF); } What is a constant? Ans : A constant is a class member that represents a constant value: a value that can be computed at compile-time. Constants are permitted to depend on other constants within the same program as long as there are no circular dependencies. The rules governing constant expressions are defined in constant expression The example class Constants { public const int A = 1; public const int B = A + 1; } shows a class named Constants that has two public constants. Even though constants are considered static members, a constant declaration neither requires nor allows the static modifier. Constants can be accessed through the class, as in class Test { static void Main() { Console.WriteLine("{0}, {1}", Constants.A, Constants.B); } } which prints out the values of Constants.A and Constants.B. What is a method? Ans : A method is a member that implements a computation or action that can be performed by an object or class. Methods have a list of formal parameters (which may be empty), a return value (or void), and are either static or non-static. Static methods are accessed through the class. Non-static methods, which are also called instance methods, are accessed through instances of the class. Methods can be overloaded, which means that multiple methods may have the same name so long as they have unique signatures. The signature of a method consists of the name of the method and the number, modifiers, and types of its formal parameters.

The signature of a method does not include the return type. What is a Property ? Ans : A property is a member that provides access to a characteristic of an object or a class. Examples of properties include the length of a string, the size of a font, the caption of a window, the name of a customer, and so on. Properties are a natural extension of fields. Both are named members with associated types, and the syntax for accessing fields and properties is the same. However, unlike fields, properties do not denote storage locations. Instead, properties have accessors that specify the statements to be executed when their values are read or written. What r delegates and events? Ans : It suffices to simply state that a delegate is the object-oriented (and type-safe) equivalent of a function pointer. A delegate instance holds a reference to an instance or class method, permitting anonymous invocation of the bound method. Events are special constructs declared on a class that help to expose state changes to interested objects at run time. An event represents a formal abstraction (supported by the CLR and various compilers) of the registration, unregistration, and notification methods we used previously to implement the Observer pattern. Delegates are registered with specific events at run time. When the event is raised, all registered delegates are invoked so that they receive notification of the event. 1)What is usercontrols? 2)Can we have dynamic usercontrols and can we pass values from the usercontrols to the aspx pages? 3)What is the diff between abstract class and interface 4)Can u use javascript in aspx 5)what is the diff between windows dll and com dll 6)Diff between asp and asp.net 7)Diff between having and where clause 8)Can i have mulitple global.asa files 9)Diff between machine.config and web.config 10)what is web.config 11)Types of parameters passed in c# methods 12)byref and byval 13)diff between repeater,datalist and datagrid 14)threading 15)can i have a connected dataset 16)why u need dataadpater 17)diff between servercontrols and htmlcontrols 18)what is response.end,response.clear and response.flush 19)what is diff between asp caching and asp.net caching 20)what is global assembly cache.how to put the components in the GAC and is there any steps before that 21)CLR,CTS and CLS 22)what are strongnames 23)what all u can pass in byval and byref 24)what is assembly 25)what is namespace and can we have nested namespace in a dll and where exactly the namespace is stored 26)what is the version control in .net 27)what is the disadvantage of using static 28)Apart from DOM how can u retreive records in XML 29)how to use com in .net and vice versa 30)oops,operator overloading(What happend when the return type is different and the signature is the same)

31)What is the difference between operator overloading and overiding 32)What is the namespace used for creating the collection object 33)can u force the garbage collector 34)can u use try without catch 35)how to create disconnected recordset in asp 36)what is the process flow of asp.net page 37)what is the problem of using server.transer 1)what is xmldatadocument and xmldocument 2)what is response.buffer 3)can i have multiple web.config files in the application 4)can i use javascript in the webservercontrols 5)how to access server variables inside javascript 6)what is the difff between htmlservercontrols and webservercontrols 7)how to configure smtp server for sending mails 8)can i use variable in the include file 9)what is the diff between server.transfer and response.redirect 10)how is the version is maintained in the assembly 11)how can i refer to an assembly with a different version 12)can i use action="a.exe" inside the form tag 13)can i use server.createobject(a.exe) 14)can i pass querystring in server.transfer 15)diff between server.transfer and server.execute 16)what is the step to be done before making an instance of excel file using server.createobject 17)what are type datasets 18)what is the difference between manifest and metadata .net framework diff between asp and asp.net diff types of assemblies boxing and unboxing diff between classes and structs, what to use when diff types of joins diff between in clause and exists diff between truncate and delete what are the various methods by which u can populate dataset apart from dataadapter

Related Documents

Cfaq
November 2019 36