C#FAQ
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?
• 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?
• 8. Miscellaneous
o 8.1 String comparisons using == seem to be case-sensitive? How do I doa case-insensitive string
comparison?
o 8.2 I've seen some string literals which use the @ symbol, and somewhich don't. What's that all about?
o 8.3 Does C# support a variable number of arguments?
o 8.4 How can I process command-line arguments?
o 8.5 Does C# do array bounds checking?
o 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.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.
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 32-
bit 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 );
}
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 );
}
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.
E_POINTER ArgumentNullException
E_NOTIMPL NotImplementedException
E_OUTOFMEMORY OutOfMemoryException
Other standard exceptions that you might want to re-use are IndexOutOfRangeException and ArithmeticException .
class CApp
{
public static void Main()
{
try
{
f();
}
catch( Exception e )
{
Console.WriteLine( "System.Exception stack trace = \n{0}", e.StackTrace );
}
}
class CApp
{
public static void Main()
{
string s = "fred";
long i = 10;
class CTest
{
class CApp
{
public static void Main()
{
long i = 10;
CTest ctest = new CTest();
DisplayTypeInfo( ctest );
DisplayTypeInfo( i );
}
class CAmerican
{
public void BePatriotic()
{
Console.WriteLine( "... <gulp> ... 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();
}
// Reveal yourselves!
RevealYourStereotype(stereotypes );
}
}
This produces the following result:
... <gulp>... God bless America.
Bloody foreigners ...
interface IPerson
{
string GetName();
}
// IPerson
public string GetName()
{
return m_name;
}
// IPerson2
public string GetName() { return m_name; }
public int GetAge() { return m_age; }
private string m_name; private int m_age;
}
DisplayAge( bob );
DisplayAge( sheila );
}
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.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"
class CApp
{
public static void Main( string[] args )
{
Console.WriteLine( "You passed the following arguments:" );
foreach( string arg in args )
Console.WriteLine( arg );
}
}
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();
class Military {
public delegate void 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();
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 Test {
static Employee e1 = new Employee();
static Missile e2 = new Missile();
struct A {
}
class B {
}
Properties
Structs
Unchecked Exceptions
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"
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:
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:
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...
}
// 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 '<namespace name>' 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.
class Test
{
public static void Swap(ref object a, ref object b) {
object temp;
temp = a;
a = b;
b = temp;
}
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.
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.
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 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.
class ThreadTest
{
public void Runme()
{
Console.WriteLine("Runme Called");
Thread.Sleep(10000);
}
t.Join();
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.
...
...
To expand on the static readonly case a bit, the containing class can only modify it:
class Bar
{
Colors color;
Bar() { color = Colors.GREEN;}
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: 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.
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.
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)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);
}
}
True
False
because the first comparison compares two expressions of type string, and the second comparison compares two
expressions of type object.
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.
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.
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
.net framework
diff between asp and asp.net
diff types of assemblies
boxing and unboxing
diff between classes and structs, what to use when
what are the various methods by which u can populate dataset apart from dataadapter